Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
f2356e7
fix: Workspace - The new WS names appear in English when Spanish is s…
Krishna2323 Jan 28, 2025
61faaac
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Jan 29, 2025
04956f8
fix regex.
Krishna2323 Jan 29, 2025
cce2332
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Feb 1, 2025
d0c0a57
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Feb 3, 2025
a777e8f
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Feb 6, 2025
570944a
minor fixes.
Krishna2323 Feb 6, 2025
72934b8
minor fix.
Krishna2323 Feb 6, 2025
8aa5ad6
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Feb 10, 2025
b4d7bd4
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Feb 12, 2025
6050236
prettier fix.
Krishna2323 Feb 12, 2025
d8f6fa0
use workspace translation from translation files.
Krishna2323 Feb 12, 2025
ab7e0f8
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Feb 15, 2025
5cbcb2d
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Feb 17, 2025
f710ed2
fix prettier test.
Krishna2323 Feb 17, 2025
fcd009d
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Feb 18, 2025
84acf45
update regex.
Krishna2323 Feb 18, 2025
1b6dd9b
update regex.
Krishna2323 Feb 18, 2025
1cc31c6
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Feb 21, 2025
5dbcd85
add tests for generateDefaultWorkspaceName.
Krishna2323 Feb 22, 2025
bd32149
minor update.
Krishna2323 Feb 22, 2025
4dcbb66
fix eslint.
Krishna2323 Feb 22, 2025
c871736
fix eslint.
Krishna2323 Feb 22, 2025
3e84282
Merge branch 'Expensify:main' into krishna2323/issue/53599
Krishna2323 Feb 26, 2025
2b02548
fix NaN values in workspaceNumbers.
Krishna2323 Mar 1, 2025
b1f617c
fix failint unit test.
Krishna2323 Mar 1, 2025
7d9787e
Merge branch 'main' into krishna2323/issue/53599
Krishna2323 Mar 3, 2025
349e5f4
minor fix.
Krishna2323 Mar 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ import type {
MissingPropertyParams,
MovedFromPersonalSpaceParams,
NeedCategoryForExportToIntegrationParams,
NewWorkspaceNameParams,
NoLongerHaveAccessParams,
NotAllowedExtensionParams,
NotYouParams,
Expand Down Expand Up @@ -4027,6 +4028,8 @@ const translations = {
newWorkspace: 'New workspace',
getTheExpensifyCardAndMore: 'Get the Expensify Card and more',
confirmWorkspace: 'Confirm Workspace',
myGroupWorkspace: 'My Group Workspace',
workspaceName: ({userName, workspaceNumber}: NewWorkspaceNameParams) => `${userName}'s Workspace${workspaceNumber ? ` ${workspaceNumber}` : ''}`,
},
people: {
genericFailureMessage: 'An error occurred removing a member from the workspace, please try again.',
Expand Down
3 changes: 3 additions & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ import type {
MissingPropertyParams,
MovedFromPersonalSpaceParams,
NeedCategoryForExportToIntegrationParams,
NewWorkspaceNameParams,
NoLongerHaveAccessParams,
NotAllowedExtensionParams,
NotYouParams,
Expand Down Expand Up @@ -4073,6 +4074,8 @@ const translations = {
newWorkspace: 'Nuevo espacio de trabajo',
getTheExpensifyCardAndMore: 'Consigue la Tarjeta Expensify y más',
confirmWorkspace: 'Confirmar espacio de trabajo',
myGroupWorkspace: 'Mi Espacio de Trabajo en Grupo',
workspaceName: ({userName, workspaceNumber}: NewWorkspaceNameParams) => `Espacio de trabajo${workspaceNumber ? ` ${workspaceNumber}` : ''} de ${userName}`,
},
people: {
genericFailureMessage: 'Se ha producido un error al intentar eliminar a un miembro del espacio de trabajo. Por favor, inténtalo más tarde.',
Expand Down
3 changes: 3 additions & 0 deletions src/languages/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@ type UserIsAlreadyMemberParams = {login: string; name: string};

type GoToRoomParams = {roomName: string};

type NewWorkspaceNameParams = {userName: string; workspaceNumber?: number};

type RoomNameReservedErrorParams = {reservedName: string};

type RenamedRoomActionParams = {oldName: string; newName: string};
Expand Down Expand Up @@ -878,6 +880,7 @@ export type {
UpdatedPolicyDescriptionParams,
EditDestinationSubtitleParams,
FlightLayoverParams,
NewWorkspaceNameParams,
AddedOrDeletedPolicyReportFieldParams,
AddedPolicyCustomUnitRateParams,
UpdatedPolicyTagParams,
Expand Down
37 changes: 22 additions & 15 deletions src/libs/actions/Policy/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import * as ErrorUtils from '@libs/ErrorUtils';
import {createFile} from '@libs/fileDownload/FileUtils';
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import GoogleTagManager from '@libs/GoogleTagManager';
import {translate, translateLocal} from '@libs/Localize';
import Log from '@libs/Log';
import * as NetworkStore from '@libs/Network/NetworkStore';
import * as NumberUtils from '@libs/NumberUtils';
Expand Down Expand Up @@ -1579,40 +1580,46 @@ function removeWorkspace(policyID: string) {
*/
function generateDefaultWorkspaceName(email = ''): string {
const emailParts = email ? email.split('@') : sessionEmail.split('@');
let defaultWorkspaceName = '';
if (!emailParts || emailParts.length !== 2) {
return defaultWorkspaceName;
return '';
}
const username = emailParts.at(0) ?? '';
const domain = emailParts.at(1) ?? '';
const userDetails = PersonalDetailsUtils.getPersonalDetailByEmail(sessionEmail);
const displayName = userDetails?.displayName?.trim();
let displayNameForWorkspace = '';

if (!PUBLIC_DOMAINS.some((publicDomain) => publicDomain === domain.toLowerCase())) {
defaultWorkspaceName = `${Str.UCFirst(domain.split('.').at(0) ?? '')}'s Workspace`;
displayNameForWorkspace = Str.UCFirst(domain.split('.').at(0) ?? '');
} else if (displayName) {
defaultWorkspaceName = `${Str.UCFirst(displayName)}'s Workspace`;
displayNameForWorkspace = Str.UCFirst(displayName);
} else if (PUBLIC_DOMAINS.some((publicDomain) => publicDomain === domain.toLowerCase())) {
defaultWorkspaceName = `${Str.UCFirst(username)}'s Workspace`;
displayNameForWorkspace = Str.UCFirst(username);
} else {
defaultWorkspaceName = userDetails?.phoneNumber ?? '';
displayNameForWorkspace = userDetails?.phoneNumber ?? '';
}

if (`@${domain.toLowerCase()}` === CONST.SMS.DOMAIN) {
defaultWorkspaceName = 'My Group Workspace';
if (`@${domain}` === CONST.SMS.DOMAIN) {
return translateLocal('workspace.new.myGroupWorkspace');
}

if (isEmptyObject(allPolicies)) {
return defaultWorkspaceName;
return translateLocal('workspace.new.workspaceName', {userName: displayNameForWorkspace});
}

// find default named workspaces and increment the last number
const numberRegEx = new RegExp(`${escapeRegExp(defaultWorkspaceName)} ?(\\d*)`, 'i');
const parsedWorkspaceNumbers = Object.values(allPolicies ?? {})
.filter((policy) => policy?.name && numberRegEx.test(policy.name))
.map((policy) => Number(numberRegEx.exec(policy?.name ?? '')?.[1] ?? '1')); // parse the number at the end
const lastWorkspaceNumber = Math.max(...parsedWorkspaceNumbers);
return lastWorkspaceNumber !== -Infinity ? `${defaultWorkspaceName} ${lastWorkspaceNumber + 1}` : defaultWorkspaceName;
const escapedName = escapeRegExp(displayNameForWorkspace);
const workspaceTranslations = CONST.LANGUAGES.map((lang) => translate(lang, 'workspace.common.workspace')).join('|');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const workspaceTranslations = CONST.LANGUAGES.map((lang) => translate(lang, 'workspace.common.workspace')).join('|');
const workspaceTranslations = CONST.LANGUAGES.map((lang) => translate(lang, 'workspace.new.workspaceName', {userName: escapedName})).join('|');

This seems to work too, could you double check please?
Then workspaceRegex could lose the de part

const workspaceRegex = new RegExp(`(?:${workspaceTranslations})\\s*(\\d+)?\\s*?$`, 'i');

regex can be simplified further of course

@Krishna2323 Krishna2323 Feb 18, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eVoloshchak thanks for the suggestion. I have verified it and it works well. It has been updated now.

EDIT: The suggested regex wasn't working in Spanish language so I had to update it to:

    const workspaceTranslations = CONST.LANGUAGES.map((lang) => translate(lang, 'workspace.common.workspace')).join('|');
    const workspaceRegex = new RegExp(`^(?=.*${escapedName})(?:.*(?:${workspaceTranslations})\\s*(\\d+)?)`, 'i');

^(?=.*${escapeRegex(escapedName)}):

  • This is a lookahead assertion to ensure that escapedName is present somewhere in the string.
    It doesn’t consume characters; it just verifies the condition.

(?:Workspace|Espacio de trabajo):

  • Matches either "Workspace" (English) or "Espacio de trabajo" (Spanish).
    This ensures the regex targets the correct phrases.
    \s*(\d+)?:

Matches an optional number (\d+) that appears immediately after "Workspace" or "Espacio de trabajo".
Captures this number in the first capturing group.
Case-Insensitive (i):

  • Makes the regex case-insensitive to match "workspace" or "WORKSPACE", etc.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks!


const workspaceRegex = new RegExp(`^(?=.*${escapedName})(?:.*(?:${workspaceTranslations})\\s*(\\d+)?)`, 'i');

const workspaceNumbers = Object.values(allPolicies)
.map((policy) => workspaceRegex.exec(policy?.name ?? ''))
.filter(Boolean) // Remove null matches
.map((match) => Number(match?.[1] ?? '0'));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Krishna2323, this stopped incrementing the workspace name (it was working before, there were no changes besides merging with main, weird)

@eVoloshchak, I mistakenly removed the default value "0" when mapping over workspace number and that resulted in NaN which caused the issue. Added the default value back.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works well now, thanks! Could you resolve the conflicts please?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

conflicts resolved.

const lastWorkspaceNumber = workspaceNumbers.length > 0 ? Math.max(...workspaceNumbers) : undefined;

return translateLocal('workspace.new.workspaceName', {userName: displayNameForWorkspace, workspaceNumber: lastWorkspaceNumber !== undefined ? lastWorkspaceNumber + 1 : undefined});
}

/**
Expand Down
118 changes: 118 additions & 0 deletions tests/actions/PolicyTest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import {Str} from 'expensify-common';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import {translateLocal} from '@libs/Localize';
import BaseLocaleListener from '@libs/Localize/LocaleListener/BaseLocaleListener';
// eslint-disable-next-line no-restricted-syntax

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// eslint-disable-next-line no-restricted-syntax

Will deleting this line result in a linter error?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes

import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
import CONST from '@src/CONST';
import OnyxUpdateManager from '@src/libs/actions/OnyxUpdateManager';
import * as Policy from '@src/libs/actions/Policy/Policy';
Expand Down Expand Up @@ -414,6 +419,119 @@ describe('actions/Policy', () => {
});
});

const TEST_EMAIL = 'esh@gmail.com';
const TEST_EMAIL_2 = 'eshofficial@gmail.com';
const TEST_ACCOUNT_ID = 1;
const TEST_DISPLAY_NAME = 'Esh Gupta';
const TEST_PHONE_NUMBER = '1234567890';
const TEST_NON_PUBLIC_DOMAIN_EMAIL = 'esh@example.com';
const TEST_SMS_DOMAIN_EMAIL = 'esh@expensify.sms';

describe('generateDefaultWorkspaceName', () => {
beforeAll(() => {
Onyx.set(ONYXKEYS.COLLECTION.POLICY, {});
});

it('should generate a workspace name based on the email domain when the domain is not public', () => {
const domain = 'example.com';
const displayNameForWorkspace = Str.UCFirst(domain.split('.').at(0) ?? '');

jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: TEST_DISPLAY_NAME,
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_NON_PUBLIC_DOMAIN_EMAIL);

expect(workspaceName).toBe(translateLocal('workspace.new.workspaceName', {userName: displayNameForWorkspace}));
});

it('should generate a workspace name based on the display name when the domain is public and display name is available', () => {
const displayNameForWorkspace = Str.UCFirst(TEST_DISPLAY_NAME);

jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: TEST_DISPLAY_NAME,
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_EMAIL);

expect(workspaceName).toBe(translateLocal('workspace.new.workspaceName', {userName: displayNameForWorkspace}));
});

it('should generate a workspace name based on the username when the domain is public and display name is not available', () => {
const emailParts = TEST_EMAIL_2.split('@');
const username = emailParts.at(0) ?? '';
const displayNameForWorkspace = Str.UCFirst(username);

jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: '',
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_EMAIL_2);

expect(workspaceName).toBe(translateLocal('workspace.new.workspaceName', {userName: displayNameForWorkspace}));
});

it('should generate a workspace name with an incremented number when there are existing policies with similar names', async () => {
const existingPolicies = {
...createRandomPolicy(0, CONST.POLICY.TYPE.PERSONAL, `${TEST_DISPLAY_NAME}'s Workspace`),
...createRandomPolicy(0, CONST.POLICY.TYPE.PERSONAL, `${TEST_DISPLAY_NAME}'s Workspace 1`),
};

jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: TEST_DISPLAY_NAME,
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

await Onyx.set(ONYXKEYS.COLLECTION.POLICY, existingPolicies);

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_EMAIL);

expect(workspaceName).toBe(translateLocal('workspace.new.workspaceName', {userName: TEST_DISPLAY_NAME, workspaceNumber: 2}));
});

it('should return "My Group Workspace" when the domain is SMS', () => {
jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: TEST_DISPLAY_NAME,
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_SMS_DOMAIN_EMAIL);

expect(workspaceName).toBe(translateLocal('workspace.new.myGroupWorkspace'));
});

it('should generate a workspace name with an incremented number even if previous workspaces were created in english lang', async () => {
await Onyx.set(ONYXKEYS.COLLECTION.POLICY, {});
jest.spyOn(BaseLocaleListener, 'getPreferredLocale').mockReturnValue('es');
const existingPolicies = {
...createRandomPolicy(0, CONST.POLICY.TYPE.PERSONAL, `${TEST_DISPLAY_NAME}'s Workspace`),
...createRandomPolicy(0, CONST.POLICY.TYPE.PERSONAL, `${TEST_DISPLAY_NAME}'s Workspace 1`),
};

jest.spyOn(PersonalDetailsUtils, 'getPersonalDetailByEmail').mockReturnValue({
displayName: TEST_DISPLAY_NAME,
phoneNumber: TEST_PHONE_NUMBER,
accountID: TEST_ACCOUNT_ID,
});

jest.spyOn(Str, 'UCFirst').mockReturnValue(TEST_DISPLAY_NAME);

await Onyx.set(ONYXKEYS.COLLECTION.POLICY, existingPolicies);

const workspaceName = Policy.generateDefaultWorkspaceName(TEST_EMAIL);

expect(workspaceName).toBe(translateLocal('workspace.new.workspaceName', {userName: TEST_DISPLAY_NAME, workspaceNumber: 2}));
});
});

describe('enablePolicyWorkflows', () => {
it('should update delayed submission to instant when disabling the workflows feature', async () => {
(fetch as MockFetch)?.pause?.();
Expand Down
4 changes: 2 additions & 2 deletions tests/utils/collections/policies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import type {ValueOf} from 'type-fest';
import CONST from '@src/CONST';
import type {Policy} from '@src/types/onyx';

export default function createRandomPolicy(index: number, type?: ValueOf<typeof CONST.POLICY.TYPE>): Policy {
export default function createRandomPolicy(index: number, type?: ValueOf<typeof CONST.POLICY.TYPE>, name?: string): Policy {
return {
id: index.toString(),
name: randWord(),
name: name ?? randWord(),
type: type ?? rand(Object.values(CONST.POLICY.TYPE)),
autoReporting: randBoolean(),
isPolicyExpenseChatEnabled: randBoolean(),
Expand Down