Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
116 changes: 116 additions & 0 deletions src/api/generated/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6671,6 +6671,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/v1/me/workspaces/default": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Ensure my default workspace
* @description Idempotent. When the signed-in user belongs to no workspace, creates their first one and returns it; otherwise returns `workspace: null`.
*/
post: operations["me.ensureDefaultWorkspace"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/v1/me/device-tokens": {
parameters: {
query?: never;
Expand Down Expand Up @@ -162708,6 +162728,102 @@ export interface operations {
};
};
};
"me.ensureDefaultWorkspace": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: {
content: {
"application/json": {
/** @description Name for the new workspace. Defaults to "<user>'s workspace". */
name?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
workspace: {
id: string;
/** Format: date-time */
createdAt: string;
/** Format: date-time */
updatedAt: string;
name: string;
defaultReply: string | null;
/** @enum {string} */
defaultReplyFrequency: "allTime" | "oncePerHour" | "oncePerDay";
targetCountry: string | null;
language: string;
timezone: string;
brandColor: string;
developmentMode: boolean;
smartResponseDelaySeconds: number | null;
isActive: boolean;
startTime: string | null;
endTime: string | null;
logo: string | null;
scheduledDeletionAt: string | null;
deletionRequestedById?: unknown | null;
deletionRequestedAt: string | null;
purgeStartedAt: string | null;
supportAccessUntil: string | null;
capiLimitedDataUse: boolean;
ownerId?: unknown;
tenantId?: unknown;
} | null;
};
};
};
/** @description 400 */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @constant */
defined: true;
/** @constant */
code: "WORKSPACE_SELECTION_REQUIRED";
/** @constant */
status: 400;
/** @default Workspace selection is required */
message: string;
data?: unknown;
} | {
/** @constant */
defined: true;
/** @constant */
code: "systemError";
/** @constant */
status: 400;
/** @default The request could not be processed */
message: string;
data?: unknown;
} | {
/** @constant */
defined: true;
/** @constant */
code: "businessError";
/** @constant */
status: 400;
/** @default An error occurred while processing your request */
message: string;
data?: unknown;
} | components["schemas"]["UndefinedError"];
};
};
};
};
"me.registerDeviceToken": {
parameters: {
query?: never;
Expand Down
29 changes: 28 additions & 1 deletion src/app/(app)/workspace-picker.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, RefreshControl, View } from 'react-native';

Expand All @@ -8,6 +9,7 @@ import { ErrorBanner } from '@/components/ui/error-banner';
import { Screen } from '@/components/ui/screen';
import { SkeletonRow } from '@/components/ui/skeleton';
import { Text } from '@/components/ui/text';
import { useEnsureDefaultWorkspace } from '@/features/workspaces/api/use-ensure-default-workspace';
import { useSwitchWorkspace } from '@/features/workspaces/api/use-switch-workspace';
import { useWorkspaces, type Workspace } from '@/features/workspaces/api/use-workspaces';
import { WorkspaceRow } from '@/features/workspaces/workspace-row';
Expand All @@ -20,6 +22,25 @@ export default function WorkspacePickerScreen() {
const currentWorkspaceId = useWorkspaceStore((state) => state.currentWorkspaceId);
const { data: workspaces, isPending, isError, isRefetching, error, refetch } = useWorkspaces();
const switchWorkspace = useSwitchWorkspace();
const ensureDefault = useEnsureDefaultWorkspace();
const hasRequestedDefault = useRef(false);
const isListEmpty = workspaces !== undefined && workspaces.length === 0;
const { mutate: createDefaultWorkspace } = ensureDefault;

const requestDefaultWorkspace = useCallback(() => {
hasRequestedDefault.current = true;
createDefaultWorkspace(undefined, {
onSuccess: (workspace) => {
if (workspace) switchWorkspace(workspace.id, { navigate: true });
},
});
}, [createDefaultWorkspace, switchWorkspace]);

// A brand-new account has no membership yet; web creates the first workspace lazily on its home
// page, so mobile asks the (idempotent) backend to do the same once the list resolves empty.
useEffect(() => {
if (isListEmpty && !hasRequestedDefault.current) requestDefaultWorkspace();
}, [isListEmpty, requestDefaultWorkspace]);

function handleSelect(workspace: Workspace) {
switchWorkspace(workspace.id, { navigate: true });
Expand All @@ -31,7 +52,7 @@ export default function WorkspacePickerScreen() {
{t('workspaces.title')}
</Text>

{isPending ? (
{isPending || (isListEmpty && (ensureDefault.isPending || ensureDefault.isIdle)) ? (
<View style={{ gap: spacing.sm }}>
<SkeletonRow.Conversation />
<SkeletonRow.Conversation />
Expand All @@ -43,6 +64,12 @@ export default function WorkspacePickerScreen() {
actionLabel={t('common.retry')}
onAction={() => refetch()}
/>
) : isListEmpty && ensureDefault.isError ? (
<ErrorBanner
message={describeApiError(ensureDefault.error, t)}
actionLabel={t('common.retry')}
onAction={requestDefaultWorkspace}
/>
) : workspaces && workspaces.length > 0 ? (
<FlatList
data={workspaces}
Expand Down
93 changes: 93 additions & 0 deletions src/features/workspaces/api/use-ensure-default-workspace.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, renderHook, waitFor } from '@testing-library/react-native';
import type { PropsWithChildren } from 'react';

import { apiClient } from '@/api/client';
import { ApiError } from '@/api/errors';
import { queryKeys } from '@/api/query-keys';
import { useAuthStore } from '@/stores/use-auth-store';
import { useEnsureDefaultWorkspace } from './use-ensure-default-workspace';

jest.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, vars?: { name: string }) => `${key}:${vars?.name ?? ''}`,
}),
}));

jest.mock('@/api/client', () => ({
apiClient: { POST: jest.fn() },
}));

function createWrapper(queryClient: QueryClient) {
return function QueryWrapper({ children }: PropsWithChildren) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};
}

describe('useEnsureDefaultWorkspace', () => {
beforeEach(() => {
useAuthStore.getState().setSignedIn({
id: 'user-1',
email: 'jane@example.com',
name: 'Jane',
mustChangePassword: false,
});
});

afterEach(() => {
jest.clearAllMocks();
});

it('posts a default name and invalidates the workspace list', async () => {
const workspace = { id: 'ws-1', name: "Jane's workspace", logo: null, brandColor: '#123456' };
jest
.mocked(apiClient.POST)
.mockResolvedValue({ data: { workspace }, error: undefined } as never);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const invalidate = jest.spyOn(queryClient, 'invalidateQueries');

const { result } = await renderHook(() => useEnsureDefaultWorkspace(), {
wrapper: createWrapper(queryClient),
});
await act(async () => {
await result.current.mutateAsync();
});

expect(apiClient.POST).toHaveBeenCalledWith('/v1/me/workspaces/default', {
body: { name: 'workspaces.defaultName:Jane' },
});
await waitFor(() => expect(result.current.data).toEqual(workspace));
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.workspaces() });
});

it('resolves to null when the backend declines to create one', async () => {
jest
.mocked(apiClient.POST)
.mockResolvedValue({ data: { workspace: null }, error: undefined } as never);
const queryClient = new QueryClient();

const { result } = await renderHook(() => useEnsureDefaultWorkspace(), {
wrapper: createWrapper(queryClient),
});
await act(async () => {
await result.current.mutateAsync();
});

await waitFor(() => expect(result.current.data).toBeNull());
});

it('throws ApiError on an error response', async () => {
jest.mocked(apiClient.POST).mockResolvedValue({
data: undefined,
error: { code: 'systemError', status: 400, message: 'boom', defined: true },
} as never);
const queryClient = new QueryClient();

const { result } = await renderHook(() => useEnsureDefaultWorkspace(), {
wrapper: createWrapper(queryClient),
});
await act(async () => {
await expect(result.current.mutateAsync()).rejects.toBeInstanceOf(ApiError);
});
});
});
33 changes: 33 additions & 0 deletions src/features/workspaces/api/use-ensure-default-workspace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';

import { apiClient } from '@/api/client';
import { ApiError } from '@/api/errors';
import { queryKeys } from '@/api/query-keys';
import type { Workspace } from '@/features/workspaces/api/use-workspaces';
import { useAuthStore } from '@/stores/use-auth-store';

/**
* Creates the signed-in user's first workspace (`POST /v1/me/workspaces/default`). The backend is
* idempotent and resolves to `null` when the user already belongs to a workspace or a plan limit
* blocks creation, so callers must handle a null result.
*/
export function useEnsureDefaultWorkspace() {
const queryClient = useQueryClient();
const { t } = useTranslation();
const user = useAuthStore((state) => state.user);

return useMutation({
mutationFn: async (): Promise<Workspace | null> => {
const displayName = user?.name || user?.email || '';
const { data, error } = await apiClient.POST('/v1/me/workspaces/default', {
body: { name: t('workspaces.defaultName', { name: displayName }) },
});
if (error) {
throw new ApiError(error);
}
return data.workspace;
},
onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.workspaces() }),
});
}
3 changes: 2 additions & 1 deletion src/i18n/locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "مساحة العمل الحالية",
"switch": "تبديل",
"switchConfirmTitle": "تبديل مساحة العمل؟",
"switchConfirmBody": "هل تريد التبديل إلى {{name}}؟ ستغادر مساحة العمل الحالية."
"switchConfirmBody": "هل تريد التبديل إلى {{name}}؟ ستغادر مساحة العمل الحالية.",
"defaultName": "مساحة عمل {{name}}"
},
"inbox": {
"title": "صندوق الوارد"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/da.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "Nuværende workspace",
"switch": "Skift",
"switchConfirmTitle": "Skift workspace?",
"switchConfirmBody": "Skift til {{name}}? Du forlader dit nuværende workspace."
"switchConfirmBody": "Skift til {{name}}? Du forlader dit nuværende workspace.",
"defaultName": "{{name}}s arbejdsområde"
},
"inbox": {
"title": "Indbakke"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "Aktueller Workspace",
"switch": "Wechseln",
"switchConfirmTitle": "Workspace wechseln?",
"switchConfirmBody": "Zu {{name}} wechseln? Du verlässt deinen aktuellen Workspace."
"switchConfirmBody": "Zu {{name}} wechseln? Du verlässt deinen aktuellen Workspace.",
"defaultName": "Arbeitsbereich von {{name}}"
},
"inbox": {
"title": "Posteingang"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
"current": "Current workspace",
"switch": "Switch",
"switchConfirmTitle": "Switch workspace?",
"switchConfirmBody": "Switch to {{name}}? You'll leave your current workspace."
"switchConfirmBody": "Switch to {{name}}? You'll leave your current workspace.",
"defaultName": "{{name}}'s workspace"
},
"inbox": {
"title": "Inbox"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "Espacio de trabajo actual",
"switch": "Cambiar",
"switchConfirmTitle": "¿Cambiar de espacio de trabajo?",
"switchConfirmBody": "¿Cambiar a {{name}}? Saldrás de tu espacio de trabajo actual."
"switchConfirmBody": "¿Cambiar a {{name}}? Saldrás de tu espacio de trabajo actual.",
"defaultName": "Espacio de trabajo de {{name}}"
},
"inbox": {
"title": "Bandeja de entrada"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/fi.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "Nykyinen työtila",
"switch": "Vaihda",
"switchConfirmTitle": "Vaihdetaanko työtilaa?",
"switchConfirmBody": "Vaihdetaanko työtilaan {{name}}? Poistut nykyisestä työtilastasi."
"switchConfirmBody": "Vaihdetaanko työtilaan {{name}}? Poistut nykyisestä työtilastasi.",
"defaultName": "Työtila: {{name}}"
},
"inbox": {
"title": "Saapuneet"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "Espace de travail actuel",
"switch": "Changer",
"switchConfirmTitle": "Changer d'espace de travail ?",
"switchConfirmBody": "Passer à {{name}} ? Vous quitterez votre espace de travail actuel."
"switchConfirmBody": "Passer à {{name}} ? Vous quitterez votre espace de travail actuel.",
"defaultName": "Espace de travail de {{name}}"
},
"inbox": {
"title": "Boîte de réception"
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/he.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"current": "סביבת העבודה הנוכחית",
"switch": "החלפה",
"switchConfirmTitle": "להחליף סביבת עבודה?",
"switchConfirmBody": "לעבור אל {{name}}? תעזוב את סביבת העבודה הנוכחית."
"switchConfirmBody": "לעבור אל {{name}}? תעזוב את סביבת העבודה הנוכחית.",
"defaultName": "סביבת העבודה של {{name}}"
},
"inbox": {
"title": "תיבת דואר נכנס"
Expand Down
Loading
Loading