-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathWorkspacesSettingsUtils.ts
301 lines (256 loc) · 12.1 KB
/
WorkspacesSettingsUtils.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
import Onyx from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, ReimbursementAccount, Report, ReportActions} from '@src/types/onyx';
import type {Unit} from '@src/types/onyx/Policy';
import * as CurrencyUtils from './CurrencyUtils';
import type {Phrase, PhraseParameters} from './Localize';
import * as OptionsListUtils from './OptionsListUtils';
import {hasCustomUnitsError, hasEmployeeListError, hasPolicyError, hasTaxRateError} from './PolicyUtils';
import * as ReportUtils from './ReportUtils';
type CheckingMethod = () => boolean;
let allReports: OnyxCollection<Report>;
type BrickRoad = ValueOf<typeof CONST.BRICK_ROAD_INDICATOR_STATUS> | undefined;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => (allReports = value),
});
let allPolicies: OnyxCollection<Policy>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
});
let reimbursementAccount: OnyxEntry<ReimbursementAccount>;
Onyx.connect({
key: ONYXKEYS.REIMBURSEMENT_ACCOUNT,
callback: (val) => {
reimbursementAccount = val;
},
});
let allReportActions: OnyxCollection<ReportActions>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
if (!actions) {
return;
}
allReportActions = actions;
},
});
/**
* @param altReportActions Replaces (local) allReportActions used within (local) function getWorkspacesBrickRoads
* @returns BrickRoad for the policy passed as a param and optionally actionsByReport (if passed)
*/
const getBrickRoadForPolicy = (report: Report, altReportActions?: OnyxCollection<ReportActions>): BrickRoad => {
const reportActions = (altReportActions ?? allReportActions)?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.reportID}`] ?? {};
const reportErrors = OptionsListUtils.getAllReportErrors(report, reportActions);
const doesReportContainErrors = Object.keys(reportErrors ?? {}).length !== 0 ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined;
if (doesReportContainErrors) {
return CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
}
// To determine if the report requires attention from the current user, we need to load the parent report action
let itemParentReportAction = {};
if (report.parentReportID) {
const itemParentReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.parentReportID}`] ?? {};
itemParentReportAction = report.parentReportActionID ? itemParentReportActions[report.parentReportActionID] : {};
}
const reportOption = {...report, isUnread: ReportUtils.isUnread(report), isUnreadWithMention: ReportUtils.isUnreadWithMention(report)};
const shouldShowGreenDotIndicator = ReportUtils.requiresAttentionFromCurrentUser(reportOption, itemParentReportAction);
return shouldShowGreenDotIndicator ? CONST.BRICK_ROAD_INDICATOR_STATUS.INFO : undefined;
};
function hasGlobalWorkspaceSettingsRBR(policies: OnyxCollection<Policy>) {
// When attempting to open a policy with an invalid policyID, the policy collection is updated to include policy objects with error information.
// Only policies displayed on the policy list page should be verified. Otherwise, the user will encounter an RBR unrelated to any policies on the list.
const cleanPolicies = Object.fromEntries(Object.entries(policies ?? {}).filter(([, policy]) => policy?.id));
const errorCheckingMethods: CheckingMethod[] = [
() => Object.values(cleanPolicies).some(hasPolicyError),
() => Object.values(cleanPolicies).some(hasCustomUnitsError),
() => Object.values(cleanPolicies).some(hasTaxRateError),
() => Object.values(cleanPolicies).some(hasEmployeeListError),
() => Object.keys(reimbursementAccount?.errors ?? {}).length > 0,
];
return errorCheckingMethods.some((errorCheckingMethod) => errorCheckingMethod());
}
function hasWorkspaceSettingsRBR(policy: Policy) {
const policyMemberError = hasEmployeeListError(policy);
const taxRateError = hasTaxRateError(policy);
return Object.keys(reimbursementAccount?.errors ?? {}).length > 0 || hasPolicyError(policy) || hasCustomUnitsError(policy) || policyMemberError || taxRateError;
}
function getChatTabBrickRoad(policyID?: string): BrickRoad | undefined {
if (!allReports) {
return undefined;
}
// If policyID is undefined, then all reports are checked whether they contain any brick road
const policyReports = policyID ? Object.values(allReports).filter((report) => report?.policyID === policyID) : Object.values(allReports);
let hasChatTabGBR = false;
const hasChatTabRBR = policyReports.some((report) => {
const brickRoad = report ? getBrickRoadForPolicy(report) : undefined;
if (!hasChatTabGBR && brickRoad === CONST.BRICK_ROAD_INDICATOR_STATUS.INFO) {
hasChatTabGBR = true;
}
return brickRoad === CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
});
if (hasChatTabRBR) {
return CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
}
if (hasChatTabGBR) {
return CONST.BRICK_ROAD_INDICATOR_STATUS.INFO;
}
return undefined;
}
function checkIfWorkspaceSettingsTabHasRBR(policyID?: string) {
if (!policyID) {
return hasGlobalWorkspaceSettingsRBR(allPolicies);
}
const policy = allPolicies ? allPolicies[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`] : null;
if (!policy) {
return false;
}
return hasWorkspaceSettingsRBR(policy);
}
/**
* @returns a map where the keys are policyIDs and the values are BrickRoads for each policy
*/
function getWorkspacesBrickRoads(reports: OnyxCollection<Report>, policies: OnyxCollection<Policy>, reportActions: OnyxCollection<ReportActions>): Record<string, BrickRoad> {
if (!reports) {
return {};
}
// The key in this map is the workspace id
const workspacesBrickRoadsMap: Record<string, BrickRoad> = {};
Object.values(policies ?? {}).forEach((policy) => {
// Only policies which user has access to on the list should be checked. Policies that don't have an ID and contain only information about the errors aren't displayed anywhere.
if (!policy?.id) {
return;
}
if (hasWorkspaceSettingsRBR(policy)) {
workspacesBrickRoadsMap[policy.id] = CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR;
}
});
Object.values(reports).forEach((report) => {
const policyID = report?.policyID ?? CONST.POLICY.EMPTY;
if (!report || workspacesBrickRoadsMap[policyID] === CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR) {
return;
}
const workspaceBrickRoad = getBrickRoadForPolicy(report, reportActions);
if (!workspaceBrickRoad && !!workspacesBrickRoadsMap[policyID]) {
return;
}
workspacesBrickRoadsMap[policyID] = workspaceBrickRoad;
});
return workspacesBrickRoadsMap;
}
/**
* @returns a map where the keys are policyIDs and the values are truthy booleans if policy has unread content
*/
function getWorkspacesUnreadStatuses(reports: OnyxCollection<Report>): Record<string, boolean> {
if (!reports) {
return {};
}
const workspacesUnreadStatuses: Record<string, boolean> = {};
Object.values(reports).forEach((report) => {
const policyID = report?.policyID;
if (!policyID || workspacesUnreadStatuses[policyID]) {
return;
}
// When the only message of a report is deleted lastVisibileActionCreated is not reset leading to wrongly
// setting it Unread so we add additional condition here to avoid read workspace indicator from being bold.
workspacesUnreadStatuses[policyID] = ReportUtils.isUnread(report) && !!report.lastActorAccountID;
});
return workspacesUnreadStatuses;
}
/**
* @param unit Unit
* @returns translation key for the unit
*/
function getUnitTranslationKey(unit: Unit): TranslationPaths {
const unitTranslationKeysStrategy: Record<Unit, TranslationPaths> = {
[CONST.CUSTOM_UNITS.DISTANCE_UNIT_KILOMETERS]: 'common.kilometers',
[CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES]: 'common.miles',
};
return unitTranslationKeysStrategy[unit];
}
/**
* @param error workspace change owner error
* @param translate translation function
* @param policy policy object
* @param accountLogin account login/email
* @returns ownership change checks page display text's
*/
function getOwnershipChecksDisplayText(
error: ValueOf<typeof CONST.POLICY.OWNERSHIP_ERRORS>,
translate: <TKey extends TranslationPaths>(phraseKey: TKey, ...phraseParameters: PhraseParameters<Phrase<TKey>>) => string,
policy: OnyxEntry<Policy>,
accountLogin: string | undefined,
) {
let title;
let text;
let buttonText;
const changeOwner = policy?.errorFields?.changeOwner;
const subscription = changeOwner?.subscription as unknown as {ownerUserCount: number; totalUserCount: number};
const ownerOwesAmount = changeOwner?.ownerOwesAmount as unknown as {ownerEmail: string; amount: number; currency: string};
switch (error) {
case CONST.POLICY.OWNERSHIP_ERRORS.AMOUNT_OWED:
title = translate('workspace.changeOwner.amountOwedTitle');
text = translate('workspace.changeOwner.amountOwedText');
buttonText = translate('workspace.changeOwner.amountOwedButtonText');
break;
case CONST.POLICY.OWNERSHIP_ERRORS.OWNER_OWES_AMOUNT:
title = translate('workspace.changeOwner.ownerOwesAmountTitle');
text = translate('workspace.changeOwner.ownerOwesAmountText', {
email: ownerOwesAmount?.ownerEmail,
amount: CurrencyUtils.convertToDisplayString(ownerOwesAmount?.amount, ownerOwesAmount?.currency),
});
buttonText = translate('workspace.changeOwner.ownerOwesAmountButtonText');
break;
case CONST.POLICY.OWNERSHIP_ERRORS.SUBSCRIPTION:
title = translate('workspace.changeOwner.subscriptionTitle');
text = translate('workspace.changeOwner.subscriptionText', {
usersCount: subscription?.ownerUserCount,
finalCount: subscription?.totalUserCount,
});
buttonText = translate('workspace.changeOwner.subscriptionButtonText');
break;
case CONST.POLICY.OWNERSHIP_ERRORS.DUPLICATE_SUBSCRIPTION:
title = translate('workspace.changeOwner.duplicateSubscriptionTitle');
text = translate('workspace.changeOwner.duplicateSubscriptionText', {
email: changeOwner?.duplicateSubscription,
workspaceName: policy?.name,
});
buttonText = translate('workspace.changeOwner.duplicateSubscriptionButtonText');
break;
case CONST.POLICY.OWNERSHIP_ERRORS.HAS_FAILED_SETTLEMENTS:
title = translate('workspace.changeOwner.hasFailedSettlementsTitle');
text = translate('workspace.changeOwner.hasFailedSettlementsText', {email: accountLogin});
buttonText = translate('workspace.changeOwner.hasFailedSettlementsButtonText');
break;
case CONST.POLICY.OWNERSHIP_ERRORS.FAILED_TO_CLEAR_BALANCE:
title = translate('workspace.changeOwner.failedToClearBalanceTitle');
text = translate('workspace.changeOwner.failedToClearBalanceText');
buttonText = translate('workspace.changeOwner.failedToClearBalanceButtonText');
break;
default:
title = '';
text = '';
buttonText = '';
break;
}
return {title, text, buttonText};
}
export {
getBrickRoadForPolicy,
getWorkspacesBrickRoads,
getWorkspacesUnreadStatuses,
hasGlobalWorkspaceSettingsRBR,
checkIfWorkspaceSettingsTabHasRBR,
hasWorkspaceSettingsRBR,
getChatTabBrickRoad,
getUnitTranslationKey,
getOwnershipChecksDisplayText,
};
export type {BrickRoad};