-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
PolicyUtils.ts
1079 lines (922 loc) · 42.2 KB
/
PolicyUtils.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
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 {Str} from 'expensify-common';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import type {SelectorType} from '@components/SelectionScreen';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import INPUT_IDS from '@src/types/form/NetSuiteCustomFieldForm';
import type {OnyxInputOrEntry, Policy, PolicyCategories, PolicyEmployeeList, PolicyTagLists, PolicyTags, TaxRate} from '@src/types/onyx';
import type {ErrorFields, PendingAction, PendingFields} from '@src/types/onyx/OnyxCommon';
import type {
ConnectionLastSync,
ConnectionName,
Connections,
CustomUnit,
InvoiceItem,
NetSuiteAccount,
NetSuiteConnection,
NetSuiteCustomList,
NetSuiteCustomSegment,
NetSuiteTaxAccount,
NetSuiteVendor,
PolicyConnectionSyncProgress,
PolicyFeatureName,
Rate,
Tenant,
} from '@src/types/onyx/Policy';
import type PolicyEmployee from '@src/types/onyx/PolicyEmployee';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import {getSynchronizationErrorMessage} from './actions/connections';
import * as Localize from './Localize';
import Navigation from './Navigation/Navigation';
import * as NetworkStore from './Network/NetworkStore';
import {getAccountIDsByLogins, getLoginsByAccountIDs, getPersonalDetailByEmail} from './PersonalDetailsUtils';
type MemberEmailsToAccountIDs = Record<string, number>;
type WorkspaceDetails = {
policyID: string | undefined;
name: string;
};
type ConnectionWithLastSyncData = {
/** State of the last synchronization */
lastSync?: ConnectionLastSync;
};
let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
});
/**
* Filter out the active policies, which will exclude policies with pending deletion
* These are policies that we can use to create reports with in NewDot.
*/
function getActivePolicies(policies: OnyxCollection<Policy> | null): Policy[] {
return Object.values(policies ?? {}).filter<Policy>(
(policy): policy is Policy => !!policy && policy.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && !!policy.name && !!policy.id,
);
}
/**
* Checks if we have any errors stored within the policy?.employeeList. Determines whether we should show a red brick road error or not.
*/
function hasEmployeeListError(policy: OnyxEntry<Policy>): boolean {
return Object.values(policy?.employeeList ?? {}).some((employee) => Object.keys(employee?.errors ?? {}).length > 0);
}
/**
* Check if the policy has any tax rate errors.
*/
function hasTaxRateError(policy: OnyxEntry<Policy>): boolean {
return Object.values(policy?.taxRates?.taxes ?? {}).some((taxRate) => Object.keys(taxRate?.errors ?? {}).length > 0 || Object.values(taxRate?.errorFields ?? {}).some(Boolean));
}
/**
* Check if the policy has any errors within the categories.
*/
function hasPolicyCategoriesError(policyCategories: OnyxEntry<PolicyCategories>): boolean {
return Object.keys(policyCategories ?? {}).some((categoryName) => Object.keys(policyCategories?.[categoryName]?.errors ?? {}).length > 0);
}
/**
* Checks if the policy had a sync error.
*/
function hasSyncError(policy: OnyxEntry<Policy>): boolean {
return (Object.keys(policy?.connections ?? {}) as ConnectionName[]).some((connection) => !!getSynchronizationErrorMessage(policy, connection, false));
}
/**
* Check if the policy has any error fields.
*/
function hasPolicyErrorFields(policy: OnyxEntry<Policy>): boolean {
return Object.values(policy?.errorFields ?? {}).some((fieldErrors) => Object.keys(fieldErrors ?? {}).length > 0);
}
/**
* Check if the policy has any errors, and if it doesn't, then check if it has any error fields.
*/
function hasPolicyError(policy: OnyxEntry<Policy>): boolean {
return Object.keys(policy?.errors ?? {}).length > 0 ? true : hasPolicyErrorFields(policy);
}
/**
* Checks if we have any errors stored within the policy custom units.
*/
function hasCustomUnitsError(policy: OnyxEntry<Policy>): boolean {
return Object.keys(policy?.customUnits?.errors ?? {}).length > 0;
}
function getNumericValue(value: number | string, toLocaleDigit: (arg: string) => string): number | string {
const numValue = parseFloat(value.toString().replace(toLocaleDigit('.'), '.'));
if (Number.isNaN(numValue)) {
return NaN;
}
return numValue.toFixed(CONST.CUSTOM_UNITS.RATE_DECIMALS);
}
/**
* Retrieves the distance custom unit object for the given policy
*/
function getCustomUnit(policy: OnyxEntry<Policy>): CustomUnit | undefined {
return Object.values(policy?.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
}
/**
* Retrieves custom unit rate object from the given customUnitRateID
*/
function getCustomUnitRate(policy: OnyxEntry<Policy>, customUnitRateID: string): Rate | undefined {
const distanceUnit = getCustomUnit(policy);
return distanceUnit?.rates[customUnitRateID];
}
function getRateDisplayValue(value: number, toLocaleDigit: (arg: string) => string): string {
const numValue = getNumericValue(value, toLocaleDigit);
if (Number.isNaN(numValue)) {
return '';
}
return numValue.toString().replace('.', toLocaleDigit('.')).substring(0, value.toString().length);
}
function getUnitRateValue(toLocaleDigit: (arg: string) => string, customUnitRate?: Rate) {
return getRateDisplayValue((customUnitRate?.rate ?? 0) / CONST.POLICY.CUSTOM_UNIT_RATE_BASE_OFFSET, toLocaleDigit);
}
/**
* Get the brick road indicator status for a policy. The policy has an error status if there is a policy member error, a custom unit error or a field error.
*/
function getPolicyBrickRoadIndicatorStatus(policy: OnyxEntry<Policy>): ValueOf<typeof CONST.BRICK_ROAD_INDICATOR_STATUS> | undefined {
if (hasEmployeeListError(policy) || hasCustomUnitsError(policy) || hasPolicyErrorFields(policy) || hasSyncError(policy)) {
return CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
}
return undefined;
}
/**
* Check if the policy can be displayed
* If offline, always show the policy pending deletion.
* If online, show the policy pending deletion only if there is an error.
* Note: Using a local ONYXKEYS.NETWORK subscription will cause a delay in
* updating the screen. Passing the offline status from the component.
*/
function shouldShowPolicy(policy: OnyxEntry<Policy>, isOffline: boolean): boolean {
return (
!!policy &&
(policy?.type !== CONST.POLICY.TYPE.PERSONAL || !!policy?.isJoinRequestPending) &&
(isOffline || policy?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policy.errors ?? {}).length > 0) &&
!!policy?.role
);
}
function isExpensifyTeam(email: string | undefined): boolean {
const emailDomain = Str.extractEmailDomain(email ?? '');
return emailDomain === CONST.EXPENSIFY_PARTNER_NAME || emailDomain === CONST.EMAIL.GUIDES_DOMAIN;
}
/**
* Checks if the current user is an admin of the policy.
*/
const isPolicyAdmin = (policy: OnyxInputOrEntry<Policy>, currentUserLogin?: string): boolean =>
(policy?.role ?? (currentUserLogin && policy?.employeeList?.[currentUserLogin]?.role)) === CONST.POLICY.ROLE.ADMIN;
/**
* Checks if the current user is of the role "user" on the policy.
*/
const isPolicyUser = (policy: OnyxInputOrEntry<Policy>, currentUserLogin?: string): boolean =>
(policy?.role ?? (currentUserLogin && policy?.employeeList?.[currentUserLogin]?.role)) === CONST.POLICY.ROLE.USER;
/**
* Checks if the policy is a free group policy.
*/
const isFreeGroupPolicy = (policy: OnyxEntry<Policy>): boolean => policy?.type === CONST.POLICY.TYPE.FREE;
const isPolicyEmployee = (policyID: string, policies: OnyxCollection<Policy>): boolean => Object.values(policies ?? {}).some((policy) => policy?.id === policyID);
/**
* Checks if the current user is an owner (creator) of the policy.
*/
const isPolicyOwner = (policy: OnyxInputOrEntry<Policy>, currentUserAccountID: number): boolean => policy?.ownerAccountID === currentUserAccountID;
/**
* Create an object mapping member emails to their accountIDs. Filter for members without errors if includeMemberWithErrors is false, and get the login email from the personalDetail object using the accountID.
*
* If includeMemberWithErrors is false, We only return members without errors. Otherwise, the members with errors would immediately be removed before the user has a chance to read the error.
*/
function getMemberAccountIDsForWorkspace(employeeList: PolicyEmployeeList | undefined, includeMemberWithErrors = false): MemberEmailsToAccountIDs {
const members = employeeList ?? {};
const memberEmailsToAccountIDs: MemberEmailsToAccountIDs = {};
Object.keys(members).forEach((email) => {
if (!includeMemberWithErrors) {
const member = members?.[email];
if (Object.keys(member?.errors ?? {})?.length > 0) {
return;
}
}
const personalDetail = getPersonalDetailByEmail(email);
if (!personalDetail?.login) {
return;
}
memberEmailsToAccountIDs[email] = Number(personalDetail.accountID);
});
return memberEmailsToAccountIDs;
}
/**
* Get login list that we should not show in the workspace invite options
*/
function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] {
const policyEmployeeList = employeeList ?? {};
const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
Object.keys(policyEmployeeList).forEach((email) => {
const policyEmployee = policyEmployeeList?.[email];
// Policy members that are pending delete or have errors are not valid and we should show them in the invite options (don't exclude them).
if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
return;
}
if (!email) {
return;
}
memberEmailsToExclude.push(email);
});
return memberEmailsToExclude;
}
function getSortedTagKeys(policyTagList: OnyxEntry<PolicyTagLists>): Array<keyof PolicyTagLists> {
if (isEmptyObject(policyTagList)) {
return [];
}
return Object.keys(policyTagList).sort((key1, key2) => policyTagList[key1].orderWeight - policyTagList[key2].orderWeight);
}
/**
* Gets a tag name of policy tags based on a tag's orderWeight.
*/
function getTagListName(policyTagList: OnyxEntry<PolicyTagLists>, orderWeight: number): string {
if (isEmptyObject(policyTagList)) {
return '';
}
return Object.values(policyTagList).find((tag) => tag.orderWeight === orderWeight)?.name ?? '';
}
/**
* Gets all tag lists of a policy
*/
function getTagLists(policyTagList: OnyxEntry<PolicyTagLists>): Array<ValueOf<PolicyTagLists>> {
if (isEmptyObject(policyTagList)) {
return [];
}
return Object.values(policyTagList)
.filter((policyTagListValue) => policyTagListValue !== null)
.sort((tagA, tagB) => tagA.orderWeight - tagB.orderWeight);
}
/**
* Gets a tag list of a policy by a tag index
*/
function getTagList(policyTagList: OnyxEntry<PolicyTagLists>, tagIndex: number): ValueOf<PolicyTagLists> {
const tagLists = getTagLists(policyTagList);
return (
tagLists[tagIndex] ?? {
name: '',
required: false,
tags: {},
}
);
}
function getTagNamesFromTagsLists(policyTagLists: PolicyTagLists): string[] {
const uniqueTagNames = new Set<string>();
for (const policyTagList of Object.values(policyTagLists ?? {})) {
for (const tag of Object.values(policyTagList.tags)) {
uniqueTagNames.add(getCleanedTagName(tag.name));
}
}
return Array.from(uniqueTagNames);
}
/**
* Cleans up escaping of colons (used to create multi-level tags, e.g. "Parent: Child") in the tag name we receive from the backend
*/
function getCleanedTagName(tag: string) {
return tag?.replace(/\\:/g, CONST.COLON);
}
/**
* Escape colon from tag name
*/
function escapeTagName(tag: string) {
return tag?.replaceAll(CONST.COLON, '\\:');
}
/**
* Gets a count of enabled tags of a policy
*/
function getCountOfEnabledTagsOfList(policyTags: PolicyTags) {
return Object.values(policyTags).filter((policyTag) => policyTag.enabled).length;
}
/**
* Whether the policy has multi-level tags
*/
function isMultiLevelTags(policyTagList: OnyxEntry<PolicyTagLists>): boolean {
return Object.keys(policyTagList ?? {}).length > 1;
}
function isPendingDeletePolicy(policy: OnyxEntry<Policy>): boolean {
return policy?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
}
function isPaidGroupPolicy(policy: OnyxEntry<Policy>): boolean {
return policy?.type === CONST.POLICY.TYPE.TEAM || policy?.type === CONST.POLICY.TYPE.CORPORATE;
}
function isControlPolicy(policy: OnyxEntry<Policy>): boolean {
return policy?.type === CONST.POLICY.TYPE.CORPORATE;
}
function isTaxTrackingEnabled(isPolicyExpenseChat: boolean, policy: OnyxEntry<Policy>, isDistanceRequest: boolean): boolean {
const distanceUnit = getCustomUnit(policy);
const customUnitID = distanceUnit?.customUnitID ?? 0;
const isPolicyTaxTrackingEnabled = isPolicyExpenseChat && policy?.tax?.trackingEnabled;
const isTaxEnabledForDistance = isPolicyTaxTrackingEnabled && policy?.customUnits?.[customUnitID]?.attributes?.taxEnabled;
return !!(isDistanceRequest ? isTaxEnabledForDistance : isPolicyTaxTrackingEnabled);
}
/**
* Checks if policy's scheduled submit / auto reporting frequency is "instant".
* Note: Free policies have "instant" submit always enabled.
*/
function isInstantSubmitEnabled(policy: OnyxInputOrEntry<Policy>): boolean {
return policy?.type === CONST.POLICY.TYPE.FREE || (policy?.autoReporting === true && policy?.autoReportingFrequency === CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT);
}
/**
* This gets a "corrected" value for autoReportingFrequency. The purpose of this function is to encapsulate some logic around the "immediate" frequency.
*
* - "immediate" is actually not immediate. For that you want "instant".
* - (immediate && harvesting.enabled) === daily
* - (immediate && !harvesting.enabled) === manual
*
* Note that "daily" and "manual" only exist as options for the API, not in the database or Onyx.
*/
function getCorrectedAutoReportingFrequency(policy: OnyxInputOrEntry<Policy>): ValueOf<typeof CONST.POLICY.AUTO_REPORTING_FREQUENCIES> | undefined {
if (policy?.autoReportingFrequency !== CONST.POLICY.AUTO_REPORTING_FREQUENCIES.IMMEDIATE) {
return policy?.autoReportingFrequency;
}
if (policy?.harvesting?.enabled) {
// This is actually not really "immediate". It's "daily". Surprise!
return CONST.POLICY.AUTO_REPORTING_FREQUENCIES.IMMEDIATE;
}
// "manual" is really just "immediate" (aka "daily") with harvesting disabled
return CONST.POLICY.AUTO_REPORTING_FREQUENCIES.MANUAL;
}
/**
* Checks if policy's approval mode is "optional", a.k.a. "Submit & Close"
*/
function isSubmitAndClose(policy: OnyxInputOrEntry<Policy>): boolean {
return policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.OPTIONAL;
}
function isControlOnAdvancedApprovalMode(policy: OnyxInputOrEntry<Policy>): boolean {
return policy?.type === CONST.POLICY.TYPE.CORPORATE && getApprovalWorkflow(policy) === CONST.POLICY.APPROVAL_MODE.ADVANCED;
}
function extractPolicyIDFromPath(path: string) {
return path.match(CONST.REGEX.POLICY_ID_FROM_PATH)?.[1];
}
/**
* Whether the policy has active accounting integration connections
*/
function hasAccountingConnections(policy: OnyxEntry<Policy>) {
return !isEmptyObject(policy?.connections);
}
function getPathWithoutPolicyID(path: string) {
return path.replace(CONST.REGEX.PATH_WITHOUT_POLICY_ID, '/');
}
function getPolicyEmployeeListByIdWithoutCurrentUser(policies: OnyxCollection<Pick<Policy, 'employeeList'>>, currentPolicyID?: string, currentUserAccountID?: number) {
const policy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${currentPolicyID}`] ?? null;
const policyMemberEmailsToAccountIDs = getMemberAccountIDsForWorkspace(policy?.employeeList);
return Object.values(policyMemberEmailsToAccountIDs)
.map((policyMemberAccountID) => Number(policyMemberAccountID))
.filter((policyMemberAccountID) => policyMemberAccountID !== currentUserAccountID);
}
function goBackFromInvalidPolicy() {
Navigation.navigate(ROUTES.SETTINGS_WORKSPACES);
}
/** Get a tax with given ID from policy */
function getTaxByID(policy: OnyxEntry<Policy>, taxID: string): TaxRate | undefined {
return policy?.taxRates?.taxes?.[taxID];
}
/** Get a tax rate object built like Record<TaxRateName, RelatedTaxRateKeys>.
* We want to allow user to choose over TaxRateName and there might be a situation when one TaxRateName has two possible keys in different policies */
function getAllTaxRatesNamesAndKeys(): Record<string, string[]> {
const allTaxRates: Record<string, string[]> = {};
Object.values(allPolicies ?? {})?.forEach((policy) => {
if (!policy?.taxRates?.taxes) {
return;
}
Object.entries(policy?.taxRates?.taxes).forEach(([taxRateKey, taxRate]) => {
if (!allTaxRates[taxRate.name]) {
allTaxRates[taxRate.name] = [taxRateKey];
return;
}
allTaxRates[taxRate.name].push(taxRateKey);
});
});
return allTaxRates;
}
/**
* Whether the tax rate can be deleted and disabled
*/
function canEditTaxRate(policy: Policy, taxID: string): boolean {
return policy.taxRates?.defaultExternalID !== taxID && policy.taxRates?.foreignTaxDefault !== taxID;
}
function isPolicyFeatureEnabled(policy: OnyxEntry<Policy>, featureName: PolicyFeatureName): boolean {
if (featureName === CONST.POLICY.MORE_FEATURES.ARE_TAXES_ENABLED) {
return !!policy?.tax?.trackingEnabled;
}
if (featureName === CONST.POLICY.MORE_FEATURES.ARE_CONNECTIONS_ENABLED) {
return policy?.[featureName] ? !!policy?.[featureName] : !isEmptyObject(policy?.connections);
}
return !!policy?.[featureName];
}
function getApprovalWorkflow(policy: OnyxEntry<Policy>): ValueOf<typeof CONST.POLICY.APPROVAL_MODE> {
if (policy?.type === CONST.POLICY.TYPE.PERSONAL) {
return CONST.POLICY.APPROVAL_MODE.OPTIONAL;
}
return policy?.approvalMode ?? CONST.POLICY.APPROVAL_MODE.ADVANCED;
}
function getDefaultApprover(policy: OnyxEntry<Policy>): string {
return policy?.approver ?? policy?.owner ?? '';
}
/**
* Returns the accountID to whom the given employeeAccountID submits reports to in the given Policy.
*/
function getSubmitToAccountID(policy: OnyxEntry<Policy>, employeeAccountID: number): number {
const employeeLogin = getLoginsByAccountIDs([employeeAccountID])[0];
const defaultApprover = getDefaultApprover(policy);
// For policy using the optional or basic workflow, the manager is the policy default approver.
if (([CONST.POLICY.APPROVAL_MODE.OPTIONAL, CONST.POLICY.APPROVAL_MODE.BASIC] as Array<ValueOf<typeof CONST.POLICY.APPROVAL_MODE>>).includes(getApprovalWorkflow(policy))) {
return getAccountIDsByLogins([defaultApprover])[0];
}
const employee = policy?.employeeList?.[employeeLogin];
if (!employee) {
return -1;
}
return getAccountIDsByLogins([employee.submitsTo ?? defaultApprover])[0];
}
function getSubmitToEmail(policy: OnyxEntry<Policy>, employeeAccountID: number): string {
const submitToAccountID = getSubmitToAccountID(policy, employeeAccountID);
return getLoginsByAccountIDs([submitToAccountID])[0] ?? '';
}
/**
* Returns the email of the account to forward the report to depending on the approver's approval limit.
* Used for advanced approval mode only.
*/
function getForwardsToAccount(policy: OnyxEntry<Policy>, employeeEmail: string, reportTotal: number): string {
if (!isControlOnAdvancedApprovalMode(policy)) {
return '';
}
const employee = policy?.employeeList?.[employeeEmail];
if (!employee) {
return '';
}
const positiveReportTotal = Math.abs(reportTotal);
if (employee.approvalLimit && employee.overLimitForwardsTo && positiveReportTotal > employee.approvalLimit) {
return employee.overLimitForwardsTo;
}
return employee.forwardsTo ?? '';
}
/**
* Returns the accountID of the policy reimburser, if not available — falls back to the policy owner.
*/
function getReimburserAccountID(policy: OnyxEntry<Policy>): number {
const reimburserEmail = policy?.achAccount?.reimburser ?? policy?.owner ?? '';
return getAccountIDsByLogins([reimburserEmail])[0];
}
function getPersonalPolicy() {
return Object.values(allPolicies ?? {}).find((policy) => policy?.type === CONST.POLICY.TYPE.PERSONAL);
}
function getAdminEmployees(policy: OnyxEntry<Policy>): PolicyEmployee[] {
if (!policy || !policy.employeeList) {
return [];
}
return Object.keys(policy.employeeList)
.map((email) => ({...policy.employeeList?.[email], email}))
.filter((employee) => employee.role === CONST.POLICY.ROLE.ADMIN);
}
/**
* Returns the policy of the report
*/
function getPolicy(policyID: string | undefined): OnyxEntry<Policy> {
if (!allPolicies || !policyID) {
return undefined;
}
return allPolicies[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
}
/** Return active policies where current user is an admin */
function getActiveAdminWorkspaces(policies: OnyxCollection<Policy> | null): Policy[] {
const activePolicies = getActivePolicies(policies);
return activePolicies.filter((policy) => shouldShowPolicy(policy, NetworkStore.isOffline()) && isPolicyAdmin(policy));
}
/** Whether the user can send invoice from the workspace */
function canSendInvoiceFromWorkspace(policyID: string | undefined): boolean {
const policy = getPolicy(policyID);
return policy?.areInvoicesEnabled ?? false;
}
/** Whether the user can send invoice */
function canSendInvoice(policies: OnyxCollection<Policy> | null): boolean {
return getActiveAdminWorkspaces(policies).length > 0;
// TODO: Uncomment the following line when the invoices screen is ready - https://github.com/Expensify/App/issues/45175.
// return getActiveAdminWorkspaces(policies).some((policy) => canSendInvoiceFromWorkspace(policy.id));
}
function hasDependentTags(policy: OnyxEntry<Policy>, policyTagList: OnyxEntry<PolicyTagLists>) {
if (!policy?.hasMultipleTagLists) {
return false;
}
return Object.values(policyTagList ?? {}).some((tagList) => Object.values(tagList.tags).some((tag) => !!tag.rules?.parentTagsFilter || !!tag.parentTagsFilter));
}
/** Get the Xero organizations connected to the policy */
function getXeroTenants(policy: Policy | undefined): Tenant[] {
// Due to the way optional chain is being handled in this useMemo we are forced to use this approach to properly handle undefined values
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
if (!policy || !policy.connections || !policy.connections.xero || !policy.connections.xero.data) {
return [];
}
return policy.connections.xero.data.tenants ?? [];
}
function findCurrentXeroOrganization(tenants: Tenant[] | undefined, organizationID: string | undefined): Tenant | undefined {
return tenants?.find((tenant) => tenant.id === organizationID);
}
function getCurrentXeroOrganizationName(policy: Policy | undefined): string | undefined {
return findCurrentXeroOrganization(getXeroTenants(policy), policy?.connections?.xero?.config?.tenantID)?.name;
}
function getXeroBankAccounts(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const bankAccounts = policy?.connections?.xero?.data?.bankAccounts ?? [];
return (bankAccounts ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedBankAccountId === id,
}));
}
function areSettingsInErrorFields(settings?: string[], errorFields?: ErrorFields) {
if (settings === undefined || errorFields === undefined) {
return false;
}
const keys = Object.keys(errorFields);
return settings.some((setting) => keys.includes(setting));
}
function settingsPendingAction(settings?: string[], pendingFields?: PendingFields<string>): PendingAction | undefined {
if (settings === undefined || pendingFields === undefined) {
return null;
}
const key = Object.keys(pendingFields).find((setting) => settings.includes(setting));
return pendingFields[key ?? '-1'];
}
function findSelectedVendorWithDefaultSelect(vendors: NetSuiteVendor[] | undefined, selectedVendorId: string | undefined) {
const selectedVendor = (vendors ?? []).find(({id}) => id === selectedVendorId);
return selectedVendor ?? vendors?.[0] ?? undefined;
}
function findSelectedBankAccountWithDefaultSelect(accounts: NetSuiteAccount[] | undefined, selectedBankAccountId: string | undefined) {
const selectedBankAccount = (accounts ?? []).find(({id}) => id === selectedBankAccountId);
return selectedBankAccount ?? accounts?.[0] ?? undefined;
}
function findSelectedInvoiceItemWithDefaultSelect(invoiceItems: InvoiceItem[] | undefined, selectedItemId: string | undefined) {
const selectedInvoiceItem = (invoiceItems ?? []).find(({id}) => id === selectedItemId);
return selectedInvoiceItem ?? invoiceItems?.[0] ?? undefined;
}
function findSelectedTaxAccountWithDefaultSelect(taxAccounts: NetSuiteTaxAccount[] | undefined, selectedAccountId: string | undefined) {
const selectedTaxAccount = (taxAccounts ?? []).find(({externalID}) => externalID === selectedAccountId);
return selectedTaxAccount ?? taxAccounts?.[0] ?? undefined;
}
function getNetSuiteVendorOptions(policy: Policy | undefined, selectedVendorId: string | undefined): SelectorType[] {
const vendors = policy?.connections?.netsuite.options.data.vendors;
const selectedVendor = findSelectedVendorWithDefaultSelect(vendors, selectedVendorId);
return (vendors ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedVendor?.id === id,
}));
}
function getNetSuitePayableAccountOptions(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const payableAccounts = policy?.connections?.netsuite.options.data.payableList;
const selectedPayableAccount = findSelectedBankAccountWithDefaultSelect(payableAccounts, selectedBankAccountId);
return (payableAccounts ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedPayableAccount?.id === id,
}));
}
function getNetSuiteReceivableAccountOptions(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const receivableAccounts = policy?.connections?.netsuite.options.data.receivableList;
const selectedReceivableAccount = findSelectedBankAccountWithDefaultSelect(receivableAccounts, selectedBankAccountId);
return (receivableAccounts ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedReceivableAccount?.id === id,
}));
}
function getNetSuiteInvoiceItemOptions(policy: Policy | undefined, selectedItemId: string | undefined): SelectorType[] {
const invoiceItems = policy?.connections?.netsuite.options.data.items;
const selectedInvoiceItem = findSelectedInvoiceItemWithDefaultSelect(invoiceItems, selectedItemId);
return (invoiceItems ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedInvoiceItem?.id === id,
}));
}
function getNetSuiteTaxAccountOptions(policy: Policy | undefined, subsidiaryCountry?: string, selectedAccountId?: string): SelectorType[] {
const taxAccounts = policy?.connections?.netsuite.options.data.taxAccountsList;
const accountOptions = (taxAccounts ?? []).filter(({country}) => country === subsidiaryCountry);
const selectedTaxAccount = findSelectedTaxAccountWithDefaultSelect(accountOptions, selectedAccountId);
return accountOptions.map(({externalID, name}) => ({
value: externalID,
text: name,
keyForList: externalID,
isSelected: selectedTaxAccount?.externalID === externalID,
}));
}
function canUseTaxNetSuite(canUseNetSuiteUSATax?: boolean, subsidiaryCountry?: string) {
return !!canUseNetSuiteUSATax || CONST.NETSUITE_TAX_COUNTRIES.includes(subsidiaryCountry ?? '');
}
function canUseProvincialTaxNetSuite(subsidiaryCountry?: string) {
return subsidiaryCountry === '_canada';
}
function getFilteredReimbursableAccountOptions(payableAccounts: NetSuiteAccount[] | undefined) {
return (payableAccounts ?? []).filter(({type}) => type === CONST.NETSUITE_ACCOUNT_TYPE.BANK || type === CONST.NETSUITE_ACCOUNT_TYPE.CREDIT_CARD);
}
function getNetSuiteReimbursableAccountOptions(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const payableAccounts = policy?.connections?.netsuite.options.data.payableList;
const accountOptions = getFilteredReimbursableAccountOptions(payableAccounts);
const selectedPayableAccount = findSelectedBankAccountWithDefaultSelect(accountOptions, selectedBankAccountId);
return accountOptions.map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedPayableAccount?.id === id,
}));
}
function getFilteredCollectionAccountOptions(payableAccounts: NetSuiteAccount[] | undefined) {
return (payableAccounts ?? []).filter(({type}) => type === CONST.NETSUITE_ACCOUNT_TYPE.BANK);
}
function getNetSuiteCollectionAccountOptions(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const payableAccounts = policy?.connections?.netsuite.options.data.payableList;
const accountOptions = getFilteredCollectionAccountOptions(payableAccounts);
const selectedPayableAccount = findSelectedBankAccountWithDefaultSelect(accountOptions, selectedBankAccountId);
return accountOptions.map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedPayableAccount?.id === id,
}));
}
function getFilteredApprovalAccountOptions(payableAccounts: NetSuiteAccount[] | undefined) {
return (payableAccounts ?? []).filter(({type}) => type === CONST.NETSUITE_ACCOUNT_TYPE.ACCOUNTS_PAYABLE);
}
function getNetSuiteApprovalAccountOptions(policy: Policy | undefined, selectedBankAccountId: string | undefined): SelectorType[] {
const payableAccounts = policy?.connections?.netsuite.options.data.payableList;
const defaultApprovalAccount: NetSuiteAccount = {
id: CONST.NETSUITE_APPROVAL_ACCOUNT_DEFAULT,
name: Localize.translateLocal('workspace.netsuite.advancedConfig.defaultApprovalAccount'),
type: CONST.NETSUITE_ACCOUNT_TYPE.ACCOUNTS_PAYABLE,
};
const accountOptions = getFilteredApprovalAccountOptions([defaultApprovalAccount].concat(payableAccounts ?? []));
const selectedPayableAccount = findSelectedBankAccountWithDefaultSelect(accountOptions, selectedBankAccountId);
return accountOptions.map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedPayableAccount?.id === id,
}));
}
function getCustomersOrJobsLabelNetSuite(policy: Policy | undefined, translate: LocaleContextProps['translate']): string | undefined {
const importMapping = policy?.connections?.netsuite?.options?.config?.syncOptions?.mapping;
if (!importMapping?.customers && !importMapping?.jobs) {
return undefined;
}
const importFields: string[] = [];
const importCustomer = importMapping?.customers ?? CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT;
const importJobs = importMapping?.jobs ?? CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT;
if (importCustomer === CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT && importJobs === CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT) {
return undefined;
}
const importedValue = importMapping?.customers !== CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT ? importCustomer : importJobs;
if (importCustomer !== CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT) {
importFields.push(translate('workspace.netsuite.import.customersOrJobs.customers'));
}
if (importJobs !== CONST.INTEGRATION_ENTITY_MAP_TYPES.NETSUITE_DEFAULT) {
importFields.push(translate('workspace.netsuite.import.customersOrJobs.jobs'));
}
const importedValueLabel = translate(`workspace.netsuite.import.customersOrJobs.label`, importFields, translate(`workspace.accounting.importTypes.${importedValue}`).toLowerCase());
return importedValueLabel.charAt(0).toUpperCase() + importedValueLabel.slice(1);
}
function isNetSuiteCustomSegmentRecord(customField: NetSuiteCustomList | NetSuiteCustomSegment): boolean {
return 'segmentName' in customField;
}
function getNameFromNetSuiteCustomField(customField: NetSuiteCustomList | NetSuiteCustomSegment): string {
return 'segmentName' in customField ? customField.segmentName : customField.listName;
}
function isNetSuiteCustomFieldPropertyEditable(customField: NetSuiteCustomList | NetSuiteCustomSegment, fieldName: string) {
const fieldsAllowedToEdit = isNetSuiteCustomSegmentRecord(customField) ? [INPUT_IDS.SEGMENT_NAME, INPUT_IDS.INTERNAL_ID, INPUT_IDS.SCRIPT_ID, INPUT_IDS.MAPPING] : [INPUT_IDS.MAPPING];
const fieldKey = fieldName as keyof typeof customField;
return fieldsAllowedToEdit.includes(fieldKey);
}
function getIntegrationLastSuccessfulDate(connection?: Connections[keyof Connections], connectionSyncProgress?: PolicyConnectionSyncProgress) {
let syncSuccessfulDate;
if (!connection) {
return undefined;
}
if ((connection as NetSuiteConnection)?.lastSyncDate) {
syncSuccessfulDate = (connection as NetSuiteConnection)?.lastSyncDate;
} else {
syncSuccessfulDate = (connection as ConnectionWithLastSyncData)?.lastSync?.successfulDate;
}
if (
connectionSyncProgress &&
connectionSyncProgress.stageInProgress === CONST.POLICY.CONNECTIONS.SYNC_STAGE_NAME.JOB_DONE &&
syncSuccessfulDate &&
connectionSyncProgress.timestamp > syncSuccessfulDate
) {
syncSuccessfulDate = connectionSyncProgress.timestamp;
}
return syncSuccessfulDate;
}
function getCurrentSageIntacctEntityName(policy: Policy | undefined, defaultNameIfNoEntity: string): string | undefined {
const currentEntityID = policy?.connections?.intacct?.config?.entity;
if (!currentEntityID) {
return defaultNameIfNoEntity;
}
const entities = policy?.connections?.intacct?.data?.entities;
return entities?.find((entity) => entity.id === currentEntityID)?.name;
}
function getSageIntacctBankAccounts(policy?: Policy, selectedBankAccountId?: string): SelectorType[] {
const bankAccounts = policy?.connections?.intacct?.data?.bankAccounts ?? [];
return (bankAccounts ?? []).map(({id, name}) => ({
value: id,
text: name,
keyForList: id,
isSelected: selectedBankAccountId === id,
}));
}
function getSageIntacctVendors(policy?: Policy, selectedVendorId?: string): SelectorType[] {
const vendors = policy?.connections?.intacct?.data?.vendors ?? [];
return vendors.map(({id, value}) => ({
value: id,
text: value,
keyForList: id,
isSelected: selectedVendorId === id,
}));
}
function getSageIntacctNonReimbursableActiveDefaultVendor(policy?: Policy): string | undefined {
const {
nonReimbursableCreditCardChargeDefaultVendor: creditCardDefaultVendor,
nonReimbursableVendor: expenseReportDefaultVendor,
nonReimbursable,
} = policy?.connections?.intacct?.config.export ?? {};
return nonReimbursable === CONST.SAGE_INTACCT_NON_REIMBURSABLE_EXPENSE_TYPE.CREDIT_CARD_CHARGE ? creditCardDefaultVendor : expenseReportDefaultVendor;
}
function getSageIntacctCreditCards(policy?: Policy, selectedAccount?: string): SelectorType[] {
const creditCards = policy?.connections?.intacct?.data?.creditCards ?? [];
return creditCards.map(({name}) => ({
value: name,
text: name,
keyForList: name,
isSelected: name === selectedAccount,
}));
}
/**
* Sort the workspaces by their name, while keeping the selected one at the beginning.
* @param workspace1 Details of the first workspace to be compared.
* @param workspace2 Details of the second workspace to be compared.
* @param selectedWorkspaceID ID of the selected workspace which needs to be at the beginning.
*/
const sortWorkspacesBySelected = (workspace1: WorkspaceDetails, workspace2: WorkspaceDetails, selectedWorkspaceID: string | undefined): number => {
if (workspace1.policyID === selectedWorkspaceID) {
return -1;
}
if (workspace2.policyID === selectedWorkspaceID) {
return 1;
}
return workspace1.name?.toLowerCase().localeCompare(workspace2.name?.toLowerCase() ?? '') ?? 0;
};
/**
* Takes removes pendingFields and errorFields from a customUnit
*/
function removePendingFieldsFromCustomUnit(customUnit: CustomUnit): CustomUnit {
const cleanedCustomUnit = {...customUnit};
delete cleanedCustomUnit.pendingFields;
delete cleanedCustomUnit.errorFields;
return cleanedCustomUnit;
}
function navigateWhenEnableFeature(policyID: string) {
setTimeout(() => {
Navigation.navigate(ROUTES.WORKSPACE_INITIAL.getRoute(policyID));
}, CONST.WORKSPACE_ENABLE_FEATURE_REDIRECT_DELAY);
}
function getConnectedIntegration(policy: Policy | undefined, accountingIntegrations?: ConnectionName[]) {
return (accountingIntegrations ?? Object.values(CONST.POLICY.CONNECTIONS.NAME)).find((integration) => !!policy?.connections?.[integration]);
}
function hasIntegrationAutoSync(policy: Policy | undefined, connectedIntegration?: ConnectionName) {
return (connectedIntegration && policy?.connections?.[connectedIntegration]?.config?.autoSync?.enabled) ?? false;
}
function getCurrentConnectionName(policy: Policy | undefined): string | undefined {
const accountingIntegrations = Object.values(CONST.POLICY.CONNECTIONS.NAME);
const connectionKey = accountingIntegrations.find((integration) => !!policy?.connections?.[integration]);
return connectionKey ? CONST.POLICY.CONNECTIONS.NAME_USER_FRIENDLY[connectionKey] : undefined;
}
/**
* Check if the policy member is deleted from the workspace
*/
function isDeletedPolicyEmployee(policyEmployee: PolicyEmployee, isOffline: boolean) {
return !isOffline && policyEmployee.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && isEmptyObject(policyEmployee.errors);
}
function hasNoPolicyOtherThanPersonalType() {
return (
Object.values(allPolicies ?? {}).filter((policy) => policy && policy.type !== CONST.POLICY.TYPE.PERSONAL && policy.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE)
.length === 0
);
}
function getCurrentTaxID(policy: OnyxEntry<Policy>, taxID: string): string | undefined {
return Object.keys(policy?.taxRates?.taxes ?? {}).find((taxIDKey) => policy?.taxRates?.taxes?.[taxIDKey].previousTaxCode === taxID || taxIDKey === taxID);
}
function getWorkspaceAccountID(policyID: string) {
const policy = getPolicy(policyID);
if (!policy) {
return 0;
}
return policy.workspaceAccountID ?? 0;
}
export {
canEditTaxRate,
extractPolicyIDFromPath,
escapeTagName,
getActivePolicies,
getAdminEmployees,
getCleanedTagName,
getConnectedIntegration,
getCountOfEnabledTagsOfList,
getIneligibleInvitees,
getMemberAccountIDsForWorkspace,
getNumericValue,
isMultiLevelTags,
getPathWithoutPolicyID,
getPersonalPolicy,
getPolicy,
getPolicyBrickRoadIndicatorStatus,
getPolicyEmployeeListByIdWithoutCurrentUser,
getSortedTagKeys,
getTagList,
getTagListName,
getTagLists,
getTaxByID,
getUnitRateValue,
goBackFromInvalidPolicy,
hasAccountingConnections,
hasSyncError,
hasCustomUnitsError,
hasEmployeeListError,