Skip to content

Commit

Permalink
Merge pull request #34657 from koko57/refactor/31312-consolidate-getd…
Browse files Browse the repository at this point in the history
…isplayname-methods-pt3

refactor: move methods to personalDetailsUtils, remove unused one
  • Loading branch information
puneetlath authored Feb 5, 2024
2 parents 20e144d + 6fee255 commit f0ad2ac
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 79 deletions.
59 changes: 59 additions & 0 deletions src/libs/PersonalDetailsUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
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';
Expand All @@ -8,6 +9,11 @@ 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({
Expand Down Expand Up @@ -195,6 +201,57 @@ function getEffectiveDisplayName(personalDetail?: PersonalDetails): string | und
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 +15857527441@expensify.sms 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
*/
Expand All @@ -213,4 +270,6 @@ export {
getFormattedStreet,
getStreetLines,
getEffectiveDisplayName,
createDisplayName,
extractFirstAndLastNameFromAvailableDetails,
};
75 changes: 1 addition & 74 deletions src/libs/actions/PersonalDetails.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Str from 'expensify-common/lib/str';
import type {OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import * as API from '@libs/API';
Expand All @@ -16,7 +15,6 @@ import type {
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import type {CustomRNImageManipulatorResult} from '@libs/cropOrRotateImage/types';
import DateUtils from '@libs/DateUtils';
import * as LocalePhoneNumber from '@libs/LocalePhoneNumber';
import Navigation from '@libs/Navigation/Navigation';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as UserUtils from '@libs/UserUtils';
Expand All @@ -27,11 +25,6 @@ import type {DateOfBirthForm, PersonalDetails, PersonalDetailsList, PrivatePerso
import type {SelectedTimezone, Timezone} from '@src/types/onyx/PersonalDetails';
import * as Session from './Session';

type FirstAndLastName = {
firstName: string;
lastName: string;
};

let currentUserEmail = '';
let currentUserAccountID = -1;
Onyx.connect({
Expand All @@ -54,69 +47,6 @@ Onyx.connect({
callback: (val) => (privatePersonalDetails = val),
});

/**
* Creates a new displayName for a user based on passed personal details or login.
*/
function createDisplayName(login: string, personalDetails: Pick<PersonalDetails, 'firstName' | 'lastName'> | OnyxEntry<PersonalDetails>): string {
// If we have a number like +15857527441@expensify.sms then let's remove @expensify.sms and format it
// so that the option looks cleaner in our UI.
const userLogin = LocalePhoneNumber.formatPhoneNumber(login);

if (!personalDetails) {
return userLogin;
}

const firstName = personalDetails.firstName ?? '';
const lastName = personalDetails.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: ''};
}

/**
* Convert country names obtained from the backend to their respective ISO codes
* This is for backward compatibility of stored data before E/App#15507
*/
function getCountryISO(countryName: string): string {
if (!countryName || countryName.length === 2) {
return countryName;
}

return Object.entries(CONST.ALL_COUNTRIES).find(([, value]) => value === countryName)?.[0] ?? '';
}

function updatePronouns(pronouns: string) {
if (currentUserAccountID) {
const parameters: UpdatePronounsParams = {pronouns};
Expand Down Expand Up @@ -152,7 +82,7 @@ function updateDisplayName(firstName: string, lastName: string) {
[currentUserAccountID]: {
firstName,
lastName,
displayName: createDisplayName(currentUserEmail ?? '', {
displayName: PersonalDetailsUtils.createDisplayName(currentUserEmail ?? '', {
firstName,
lastName,
}),
Expand Down Expand Up @@ -524,9 +454,6 @@ function getPrivatePersonalDetails(): OnyxEntry<PrivatePersonalDetails> {
export {
clearAvatarErrors,
deleteAvatar,
extractFirstAndLastNameFromAvailableDetails,
getCountryISO,
createDisplayName,
getPrivatePersonalDetails,
openPersonalDetailsPage,
openPublicProfilePage,
Expand Down
4 changes: 2 additions & 2 deletions src/libs/actions/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import * as ErrorUtils from '@libs/ErrorUtils';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import * as SequentialQueue from '@libs/Network/SequentialQueue';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import * as Pusher from '@libs/Pusher/pusher';
import PusherUtils from '@libs/PusherUtils';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
Expand All @@ -40,7 +41,6 @@ import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import * as Link from './Link';
import * as OnyxUpdates from './OnyxUpdates';
import * as PersonalDetails from './PersonalDetails';
import * as Report from './Report';
import * as Session from './Session';

Expand Down Expand Up @@ -705,7 +705,7 @@ function setContactMethodAsDefault(newDefaultContactMethod: string) {
value: {
[currentUserAccountID]: {
login: newDefaultContactMethod,
displayName: PersonalDetails.createDisplayName(newDefaultContactMethod, myPersonalDetails),
displayName: PersonalDetailsUtils.createDisplayName(newDefaultContactMethod, myPersonalDetails),
},
},
},
Expand Down
6 changes: 3 additions & 3 deletions src/pages/EnablePayments/AdditionalDetailsStep.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ import withCurrentUserPersonalDetails, {withCurrentUserPersonalDetailsDefaultPro
import withLocalize, {withLocalizePropTypes} from '@components/withLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import compose from '@libs/compose';
import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import {parsePhoneNumber} from '@libs/PhoneNumber';
import * as ValidationUtils from '@libs/ValidationUtils';
import AddressForm from '@pages/ReimbursementAccount/AddressForm';
import * as PersonalDetails from '@userActions/PersonalDetails';
import * as Wallet from '@userActions/Wallet';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -194,7 +194,7 @@ function AdditionalDetailsStep({walletAdditionalDetails, translate, currentUserP
label={translate(fieldNameTranslationKeys.legalFirstName)}
accessibilityLabel={translate(fieldNameTranslationKeys.legalFirstName)}
role={CONST.ROLE.PRESENTATION}
defaultValue={PersonalDetails.extractFirstAndLastNameFromAvailableDetails(currentUserPersonalDetails).firstName}
defaultValue={PersonalDetailsUtils.extractFirstAndLastNameFromAvailableDetails(currentUserPersonalDetails).firstName}
shouldSaveDraft
/>
<InputWrapper
Expand All @@ -204,7 +204,7 @@ function AdditionalDetailsStep({walletAdditionalDetails, translate, currentUserP
label={translate(fieldNameTranslationKeys.legalLastName)}
accessibilityLabel={translate(fieldNameTranslationKeys.legalLastName)}
role={CONST.ROLE.PRESENTATION}
defaultValue={PersonalDetails.extractFirstAndLastNameFromAvailableDetails(currentUserPersonalDetails).lastName}
defaultValue={PersonalDetailsUtils.extractFirstAndLastNameFromAvailableDetails(currentUserPersonalDetails).lastName}
shouldSaveDraft
/>
<AddressForm
Expand Down

0 comments on commit f0ad2ac

Please sign in to comment.