-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
PersonalDetailsUtils.ts
275 lines (242 loc) · 9.53 KB
/
PersonalDetailsUtils.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
import Str from 'expensify-common/lib/str';
import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {PersonalDetails, PersonalDetailsList, PrivatePersonalDetails} from '@src/types/onyx';
import type {OnyxData} from '@src/types/onyx/Request';
import * as LocalePhoneNumber from './LocalePhoneNumber';
import * as Localize from './Localize';
import * as UserUtils from './UserUtils';
type FirstAndLastName = {
firstName: string;
lastName: string;
};
let personalDetails: Array<PersonalDetails | null> = [];
let allPersonalDetails: OnyxEntry<PersonalDetailsList> = {};
Onyx.connect({
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => {
personalDetails = Object.values(val ?? {});
allPersonalDetails = val;
},
});
function getDisplayNameOrDefault(passedPersonalDetails?: Partial<PersonalDetails> | null, defaultValue = '', shouldFallbackToHidden = true): string {
const displayName = passedPersonalDetails?.displayName ? passedPersonalDetails.displayName.replace(CONST.REGEX.MERGED_ACCOUNT_PREFIX, '') : '';
const fallbackValue = shouldFallbackToHidden ? Localize.translateLocal('common.hidden') : '';
return displayName || defaultValue || fallbackValue;
}
/**
* Given a list of account IDs (as number) it will return an array of personal details objects.
* @param accountIDs - Array of accountIDs
* @param currentUserAccountID
* @param shouldChangeUserDisplayName - It will replace the current user's personal detail object's displayName with 'You'.
* @returns - Array of personal detail objects
*/
function getPersonalDetailsByIDs(accountIDs: number[], currentUserAccountID: number, shouldChangeUserDisplayName = false): PersonalDetails[] {
const result: PersonalDetails[] = accountIDs
.filter((accountID) => !!allPersonalDetails?.[accountID])
.map((accountID) => {
const detail = (allPersonalDetails?.[accountID] ?? {}) as PersonalDetails;
if (shouldChangeUserDisplayName && currentUserAccountID === detail.accountID) {
return {
...detail,
displayName: Localize.translateLocal('common.you'),
};
}
return detail;
});
return result;
}
/**
* Given a list of logins, find the associated personal detail and return related accountIDs.
*
* @param logins Array of user logins
* @returns Array of accountIDs according to passed logins
*/
function getAccountIDsByLogins(logins: string[]): number[] {
return logins.reduce<number[]>((foundAccountIDs, login) => {
const currentDetail = personalDetails.find((detail) => detail?.login === login);
if (!currentDetail) {
// generate an account ID because in this case the detail is probably new, so we don't have a real accountID yet
foundAccountIDs.push(UserUtils.generateAccountID(login));
} else {
foundAccountIDs.push(Number(currentDetail.accountID));
}
return foundAccountIDs;
}, []);
}
/**
* Given a list of accountIDs, find the associated personal detail and return related logins.
*
* @param accountIDs Array of user accountIDs
* @returns Array of logins according to passed accountIDs
*/
function getLoginsByAccountIDs(accountIDs: number[]): string[] {
return accountIDs.reduce((foundLogins: string[], accountID) => {
const currentDetail: Partial<PersonalDetails> = personalDetails.find((detail) => Number(detail?.accountID) === Number(accountID)) ?? {};
if (currentDetail.login) {
foundLogins.push(currentDetail.login);
}
return foundLogins;
}, []);
}
/**
* Given a list of logins and accountIDs, return Onyx data for users with no existing personal details stored
*
* @param logins Array of user logins
* @param accountIDs Array of user accountIDs
* @returns Object with optimisticData, successData and failureData (object of personal details objects)
*/
function getNewPersonalDetailsOnyxData(logins: string[], accountIDs: number[]): Required<Pick<OnyxData, 'optimisticData' | 'finallyData'>> {
const personalDetailsNew: PersonalDetailsList = {};
const personalDetailsCleanup: PersonalDetailsList = {};
logins.forEach((login, index) => {
const accountID = accountIDs[index];
if (allPersonalDetails && Object.keys(allPersonalDetails?.[accountID] ?? {}).length === 0) {
personalDetailsNew[accountID] = {
login,
accountID,
avatar: UserUtils.getDefaultAvatarURL(accountID),
displayName: LocalePhoneNumber.formatPhoneNumber(login),
};
/**
* Cleanup the optimistic user to ensure it does not permanently persist.
* This is done to prevent duplicate entries (upon success) since the BE will return other personal details with the correct account IDs.
*/
personalDetailsCleanup[accountID] = null;
}
});
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: personalDetailsNew,
},
];
const finallyData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: personalDetailsCleanup,
},
];
return {
optimisticData,
finallyData,
};
}
/**
* Applies common formatting to each piece of an address
*
* @param piece - address piece to format
* @returns - formatted piece
*/
function formatPiece(piece?: string): string {
return piece ? `${piece}, ` : '';
}
/**
*
* @param street1 - street line 1
* @param street2 - street line 2
* @returns formatted street
*/
function getFormattedStreet(street1 = '', street2 = '') {
return `${street1}\n${street2}`;
}
/**
*
* @param - formatted address
* @returns [street1, street2]
*/
function getStreetLines(street = '') {
const streets = street.split('\n');
return [streets[0], streets[1]];
}
/**
* Formats an address object into an easily readable string
*
* @param privatePersonalDetails - details object
* @returns - formatted address
*/
function getFormattedAddress(privatePersonalDetails: PrivatePersonalDetails): string {
const {address} = privatePersonalDetails;
const [street1, street2] = getStreetLines(address?.street);
const formattedAddress =
formatPiece(street1) + formatPiece(street2) + formatPiece(address?.city) + formatPiece(address?.state) + formatPiece(address?.zip) + formatPiece(address?.country);
// Remove the last comma of the address
return formattedAddress.trim().replace(/,$/, '');
}
/**
* @param personalDetail - details object
* @returns - The effective display name
*/
function getEffectiveDisplayName(personalDetail?: PersonalDetails): string | undefined {
if (personalDetail) {
return LocalePhoneNumber.formatPhoneNumber(personalDetail?.login ?? '') || personalDetail.displayName;
}
return undefined;
}
/**
* Creates a new displayName for a user based on passed personal details or login.
*/
function createDisplayName(login: string, passedPersonalDetails: Pick<PersonalDetails, 'firstName' | 'lastName'> | OnyxEntry<PersonalDetails>): string {
// If we have a number like [email protected] then let's remove @expensify.sms and format it
// so that the option looks cleaner in our UI.
const userLogin = LocalePhoneNumber.formatPhoneNumber(login);
if (!passedPersonalDetails) {
return userLogin;
}
const firstName = passedPersonalDetails.firstName ?? '';
const lastName = passedPersonalDetails.lastName ?? '';
const fullName = `${firstName} ${lastName}`.trim();
// It's possible for fullName to be empty string, so we must use "||" to fallback to userLogin.
return fullName || userLogin;
}
/**
* Gets the first and last name from the user's personal details.
* If the login is the same as the displayName, then they don't exist,
* so we return empty strings instead.
*/
function extractFirstAndLastNameFromAvailableDetails({login, displayName, firstName, lastName}: PersonalDetails): FirstAndLastName {
// It's possible for firstName to be empty string, so we must use "||" to consider lastName instead.
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
if (firstName || lastName) {
return {firstName: firstName ?? '', lastName: lastName ?? ''};
}
if (login && Str.removeSMSDomain(login) === displayName) {
return {firstName: '', lastName: ''};
}
if (displayName) {
const firstSpaceIndex = displayName.indexOf(' ');
const lastSpaceIndex = displayName.lastIndexOf(' ');
if (firstSpaceIndex === -1) {
return {firstName: displayName, lastName: ''};
}
return {
firstName: displayName.substring(0, firstSpaceIndex).trim(),
lastName: displayName.substring(lastSpaceIndex).trim(),
};
}
return {firstName: '', lastName: ''};
}
/**
* Whether personal details is empty
*/
function isPersonalDetailsEmpty() {
return !personalDetails.length;
}
export {
isPersonalDetailsEmpty,
getDisplayNameOrDefault,
getPersonalDetailsByIDs,
getAccountIDsByLogins,
getLoginsByAccountIDs,
getNewPersonalDetailsOnyxData,
getFormattedAddress,
getFormattedStreet,
getStreetLines,
getEffectiveDisplayName,
createDisplayName,
extractFirstAndLastNameFromAvailableDetails,
};