diff --git a/src/locales/en/subaccount.json b/src/locales/en/subaccount.json index a865674d..cb46af9c 100644 --- a/src/locales/en/subaccount.json +++ b/src/locales/en/subaccount.json @@ -8,6 +8,12 @@ "delete": "Delete", "save": "Save" }, + "listStates": { + "retry": "Try again", + "unavailable": "Unavailable", + "genericError": "Something went wrong. Please try again.", + "loadingAriaLabel": "Loading" + }, "shared": { "loadingBrandingAriaLabel": "Loading console branding" }, @@ -46,7 +52,7 @@ "bucketActionsLabel": "Bucket actions", "view": "View", "deleteBucket": "Delete bucket", - "loading": "Loading buckets…", + "loadError": "Couldn't load your buckets", "noBucketsFound": "No buckets found", "tryDifferentSearch": "Try a different search term", "statBucketsHint_one": "In {{count}} region", @@ -108,7 +114,7 @@ "columnLastModified": "Last modified", "columnVersionId": "Version ID", "selectAll": "Select all", - "loadingObjects": "Loading objects…", + "loadError": "Couldn't load this folder", "loadingConfig": "Loading bucket configuration…", "fieldBucketName": "Bucket name", "fieldRegion": "Region", @@ -155,7 +161,6 @@ "shares": { "title": "Shared", "searchPlaceholder": "Search shared links...", - "loading": "Loading shared links…", "emptyDefault": "No shared links yet", "emptyFiltered": "No shared links found", "emptyFilteredHint": "Try a different search term", @@ -355,7 +360,7 @@ "columnActiveStorage": "Active storage (TB)", "columnDeletedStorage": "Deleted storage (TB)", "columnActiveObjects": "Active objects", - "loading": "Loading usage data…", + "loadError": "Couldn't load usage data", "empty": "No usage data for this period", "emptyHint": "Try expanding the date range." }, diff --git a/src/locales/es/subaccount.json b/src/locales/es/subaccount.json index d5bb73b9..57bd3081 100644 --- a/src/locales/es/subaccount.json +++ b/src/locales/es/subaccount.json @@ -8,6 +8,12 @@ "delete": "Eliminar", "save": "Guardar" }, + "listStates": { + "retry": "Reintentar", + "unavailable": "No disponible", + "genericError": "Algo ha salido mal. Inténtalo de nuevo.", + "loadingAriaLabel": "Cargando" + }, "shared": { "loadingBrandingAriaLabel": "Cargando la personalización de la consola" }, @@ -46,7 +52,7 @@ "bucketActionsLabel": "Acciones del bucket", "view": "Ver", "deleteBucket": "Eliminar bucket", - "loading": "Cargando buckets…", + "loadError": "No se pudieron cargar tus buckets", "noBucketsFound": "No se encontraron buckets", "tryDifferentSearch": "Prueba con otro término de búsqueda", "statBucketsHint_one": "En {{count}} región", @@ -108,7 +114,7 @@ "columnLastModified": "Última modificación", "columnVersionId": "ID de versión", "selectAll": "Seleccionar todo", - "loadingObjects": "Cargando objetos…", + "loadError": "No se pudo cargar esta carpeta", "loadingConfig": "Cargando la configuración del bucket…", "fieldBucketName": "Nombre del bucket", "fieldRegion": "Región", @@ -155,7 +161,6 @@ "shares": { "title": "Compartidos", "searchPlaceholder": "Buscar enlaces compartidos...", - "loading": "Cargando enlaces compartidos…", "emptyDefault": "Todavía no hay enlaces compartidos", "emptyFiltered": "No se encontraron enlaces compartidos", "emptyFilteredHint": "Prueba con otro término de búsqueda", @@ -355,7 +360,7 @@ "columnActiveStorage": "Almacenamiento activo (TB)", "columnDeletedStorage": "Almacenamiento eliminado (TB)", "columnActiveObjects": "Objetos activos", - "loading": "Cargando datos de uso…", + "loadError": "No se pudieron cargar los datos de uso", "empty": "No hay datos de uso para este período", "emptyHint": "Prueba a ampliar el rango de fechas." }, diff --git a/src/services/s3.service.ts b/src/services/s3.service.ts index 1017ef10..f0019406 100644 --- a/src/services/s3.service.ts +++ b/src/services/s3.service.ts @@ -71,6 +71,9 @@ export const isAccessDeniedError = (err: unknown): boolean => (err as { name?: string })?.name === 'AccessDenied' || (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode === 403; +export const s3ErrorMessage = (err: unknown, fallback: string): string => + err instanceof Error && err.message ? err.message : fallback; + export const s3Service = { listBuckets: async ( client: S3Client, diff --git a/src/sub-account/components/ListStates.tsx b/src/sub-account/components/ListStates.tsx new file mode 100644 index 00000000..eef8df58 --- /dev/null +++ b/src/sub-account/components/ListStates.tsx @@ -0,0 +1,139 @@ +import { CSSProperties } from 'react'; +import { useTranslation } from 'react-i18next'; +import { WarningIcon } from '@phosphor-icons/react'; +import Skeleton, { SkeletonTheme } from 'react-loading-skeleton'; +import { T } from '../tokens'; +import { ListStatus } from '../hooks/listLoad'; + +export type SkeletonCell = 'tile' | 'icon' | 'text' | 'pill' | 'checkbox' | 'none'; + +const TEXT_WIDTHS = ['55%', '40%', '62%', '35%', '48%']; + +const SkeletonCellContent = ({ cell, row }: { cell: SkeletonCell; row: number }) => { + if (cell === 'none') return ; + if (cell === 'checkbox') return ; + if (cell === 'pill') return ; + if (cell === 'text') return ; + const iconSize = cell === 'tile' ? 32 : 20; + return ( +
+ +
+ +
+
+ ); +}; + +interface ListSkeletonRowsProps { + cells: SkeletonCell[]; + gridTemplateColumns: string; + rowHeight: number; + padding?: string; + rows?: number; +} + +/** Placeholder rows with the same geometry as the real rows, so nothing shifts when data arrives. */ +export const ListSkeletonRows = ({ + cells, + gridTemplateColumns, + rowHeight, + padding = '0 24px', + rows = 5, +}: ListSkeletonRowsProps) => { + const { t } = useTranslation('subaccount'); + const rowStyle: CSSProperties = { + display: 'grid', + gridTemplateColumns, + alignItems: 'center', + padding, + height: rowHeight, + borderBottom: `1px solid ${T.gray15}`, + }; + return ( + +
+ {Array.from({ length: rows }, (_, row) => ( +
+ {cells.map((cell, column) => ( + + ))} +
+ ))} +
+
+ ); +}; + +interface ListErrorStateProps { + title: string; + message: string; + onRetry: () => void; +} + +export const ListErrorState = ({ title, message, onRetry }: ListErrorStateProps) => { + const { t } = useTranslation('subaccount'); + return ( +
+
+
+

{title}

+

{message}

+ +
+ ); +}; + +interface StatPlaceholderProps { + status: Exclude; + height: number; + width: number; +} + +export const StatPlaceholder = ({ status, height, width }: StatPlaceholderProps) => + status === 'loading' ? ( + + + + ) : ( + — + ); diff --git a/src/sub-account/components/shares/SharesCardHeader.tsx b/src/sub-account/components/shares/SharesCardHeader.tsx index 3c65842c..69115c73 100644 --- a/src/sub-account/components/shares/SharesCardHeader.tsx +++ b/src/sub-account/components/shares/SharesCardHeader.tsx @@ -1,14 +1,17 @@ import { useTranslation } from 'react-i18next'; import Input from '../../../components/Input'; import { T } from '../../tokens'; +import { StatPlaceholder } from '../ListStates'; +import { ListStatus } from '../../hooks/listLoad'; interface SharesCardHeaderProps { totalCount: number; + status: ListStatus; search: string; onSearchChange: (value: string) => void; } -export const SharesCardHeader = ({ totalCount, search, onSearchChange }: SharesCardHeaderProps) => { +export const SharesCardHeader = ({ totalCount, status, search, onSearchChange }: SharesCardHeaderProps) => { const { t } = useTranslation('subaccount'); return (

{t('shares.title')}

-

{t('shares.linkCount', { count: totalCount })}

+

+ {status === 'ready' ? ( + t('shares.linkCount', { count: totalCount }) + ) : status === 'loading' ? ( + + ) : ( + ' ' + )} +

void; search: string; onSearchChange: (value: string) => void; onRevoke: (share: ShareListItem) => void; @@ -21,7 +25,9 @@ interface SharesTableProps { export const SharesTable = ({ shares, totalCount, - isLoading, + status, + loadErrorMessage, + onRetry, search, onSearchChange, onRevoke, @@ -29,11 +35,11 @@ export const SharesTable = ({ onToggleVisibility, }: SharesTableProps) => { const { t } = useTranslation('subaccount'); - const bodyState = toBodyState(isLoading, shares.length); + const bodyState = toBodyState(status, shares.length); return (
- +
{COLUMN_KEYS.map((column) => ( @@ -43,7 +49,16 @@ export const SharesTable = ({ ))}
- {bodyState === 'loading' &&
{t('shares.loading')}
} + {bodyState === 'error' && ( + + )} + {bodyState === 'loading' && ( + + )} {bodyState === 'empty' && } {bodyState === 'items' && shares.map((share) => ( diff --git a/src/sub-account/components/shares/constants.ts b/src/sub-account/components/shares/constants.ts index 078df472..e0457781 100644 --- a/src/sub-account/components/shares/constants.ts +++ b/src/sub-account/components/shares/constants.ts @@ -1,5 +1,6 @@ import type { BODY_STATE } from '../../../components/settings/MembersTable'; import { ShareListItem } from '../../services/share.service'; +import { ListStatus } from '../../hooks/listLoad'; export const NO_VALUE = '—'; @@ -21,7 +22,7 @@ export const shareTypeLabelKey = (share: ShareListItem) => (share.isFolder ? 'sh export const shareAccessLabelKey = (share: ShareListItem) => share.isPublic ? 'shares.accessPublic' : 'shares.accessMembers'; -export const toBodyState = (isLoading: boolean, count: number): BODY_STATE => { - if (isLoading) return 'loading'; +export const toBodyState = (status: ListStatus, count: number): BODY_STATE | 'error' => { + if (status !== 'ready') return status; return count === 0 ? 'empty' : 'items'; }; diff --git a/src/sub-account/hooks/listLoad.test.ts b/src/sub-account/hooks/listLoad.test.ts new file mode 100644 index 00000000..5fc1db6c --- /dev/null +++ b/src/sub-account/hooks/listLoad.test.ts @@ -0,0 +1,81 @@ +import { AxiosError, AxiosHeaders } from 'axios'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { useS3ListLoad, toListStatus } from './listLoad'; +import { renderHook, unmountHooks } from '../../testing/render-hook'; + +const render = async (state: ReturnType) => (await renderHook(() => useS3ListLoad(state))).current; + +const apiError = (data: unknown) => + new AxiosError('Request failed with status code 403', 'ERR_BAD_REQUEST', undefined, undefined, { + data, + status: 403, + statusText: '', + headers: new AxiosHeaders(), + config: { headers: new AxiosHeaders() }, + }); + +const input = (overrides: Partial[0]> = {}) => ({ + credentialsError: null, + retryCredentials: vi.fn(), + isLoading: false, + listError: null, + reload: vi.fn(), + fallbackMessage: 'fallback', + ...overrides, +}); + +describe('toListStatus', () => { + test('when a load failed, then it reports the error even while another load is running', () => { + expect(toListStatus(true, new Error('boom'))).toBe('error'); + }); + + test('when nothing failed, then it is loading until the load finishes', () => { + expect(toListStatus(true, null)).toBe('loading'); + expect(toListStatus(false, null)).toBe('ready'); + }); +}); + +describe('useS3ListLoad', () => { + afterEach(unmountHooks); + + test('when the credentials failed, then it reports that error and retry fetches the credentials again', async () => { + const credentialsError = apiError({ message: 'Member does not have S3 credentials yet' }); + const state = input({ credentialsError, isLoading: true }); + + const result = await render(state); + result.retry(); + + expect(result).toMatchObject({ + status: 'error', + error: credentialsError, + message: 'Member does not have S3 credentials yet', + }); + expect(state.retryCredentials).toHaveBeenCalledOnce(); + expect(state.reload).not.toHaveBeenCalled(); + }); + + test('when only the listing failed, then retry reloads the list without refetching the credentials', async () => { + const listError = new Error('Access Denied'); + const state = input({ listError }); + + const result = await render(state); + result.retry(); + + expect(result).toMatchObject({ status: 'error', error: listError, message: 'Access Denied' }); + expect(state.reload).toHaveBeenCalledOnce(); + expect(state.retryCredentials).not.toHaveBeenCalled(); + }); + + test('when the API sent no message, then it shows the fallback instead of the generic axios text', async () => { + expect((await render(input({ credentialsError: apiError({}) }))).message).toBe('fallback'); + }); + + test('when the provider error has no message, then it shows the fallback', async () => { + expect((await render(input({ listError: {} }))).message).toBe('fallback'); + }); + + test('when nothing failed, then it follows the listing load', async () => { + expect((await render(input({ isLoading: true }))).status).toBe('loading'); + expect((await render(input())).status).toBe('ready'); + }); +}); diff --git a/src/sub-account/hooks/listLoad.ts b/src/sub-account/hooks/listLoad.ts new file mode 100644 index 00000000..f08742f4 --- /dev/null +++ b/src/sub-account/hooks/listLoad.ts @@ -0,0 +1,38 @@ +import { useCallback } from 'react'; +import { apiErrorMessage } from '../../utils/apiError'; +import { s3ErrorMessage } from '../../services/s3.service'; + +export type ListStatus = 'loading' | 'error' | 'ready'; + +export const toListStatus = (isLoading: boolean, error: unknown): ListStatus => { + if (error) return 'error'; + return isLoading ? 'loading' : 'ready'; +}; + +interface S3ListLoadInput { + credentialsError: unknown; + retryCredentials: () => void; + isLoading: boolean; + listError: unknown; + reload: () => void; + fallbackMessage: string; +} + +export const useS3ListLoad = ({ + credentialsError, + retryCredentials, + isLoading, + listError, + reload, + fallbackMessage, +}: S3ListLoadInput) => { + const error = credentialsError ?? listError; + const retry = useCallback( + () => (credentialsError ? retryCredentials() : reload()), + [credentialsError, retryCredentials, reload], + ); + const message = credentialsError + ? apiErrorMessage(credentialsError, fallbackMessage) + : s3ErrorMessage(listError, fallbackMessage); + return { status: toListStatus(isLoading, error), error, message, retry }; +}; diff --git a/src/sub-account/hooks/useSubAccountS3Client.test.ts b/src/sub-account/hooks/useSubAccountS3Client.test.ts new file mode 100644 index 00000000..780a9cde --- /dev/null +++ b/src/sub-account/hooks/useSubAccountS3Client.test.ts @@ -0,0 +1,38 @@ +import { act } from 'react'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { useSubAccountS3Client } from './useSubAccountS3Client'; +import { subAccountS3CredentialsService } from '../services/sub-account-s3-credentials.service'; +import { renderHook, settle, unmountHooks } from '../../testing/render-hook'; + +const credentials = { + accessKeyId: 'AKIA', + secretAccessKey: 'secret', + endpoint: 'https://s3.example.com', + region: 'us-east-1', +}; + +describe('useSubAccountS3Client', () => { + afterEach(() => { + unmountHooks(); + vi.restoreAllMocks(); + }); + + test('when fetching the credentials fails, then retry fetches them again and builds the client', async () => { + const failure = new Error('forbidden'); + const getCredentials = vi + .spyOn(subAccountS3CredentialsService, 'getCredentials') + .mockRejectedValueOnce(failure) + .mockResolvedValueOnce(credentials as Awaited>); + + const result = await renderHook(() => useSubAccountS3Client('sa1', 'm1')); + + expect(result.current).toMatchObject({ client: null, isLoading: false, error: failure }); + + await act(async () => result.current.retry()); + await settle(); + + expect(getCredentials).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + expect(result.current.client).not.toBeNull(); + }); +}); diff --git a/src/sub-account/hooks/useSubAccountS3Client.ts b/src/sub-account/hooks/useSubAccountS3Client.ts index 9da088e8..ae5d6972 100644 --- a/src/sub-account/hooks/useSubAccountS3Client.ts +++ b/src/sub-account/hooks/useSubAccountS3Client.ts @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { S3Client } from '@aws-sdk/client-s3'; import { subAccountS3CredentialsService, S3Credentials } from '../services/sub-account-s3-credentials.service'; @@ -9,7 +9,11 @@ interface S3ClientState { error: Error | null; } -export const useSubAccountS3Client = (entityId: string | null, memberId: string | null): S3ClientState => { +interface S3ClientResult extends S3ClientState { + retry: () => void; +} + +export const useSubAccountS3Client = (entityId: string | null, memberId: string | null): S3ClientResult => { const [state, setState] = useState({ client: null, credentials: null, @@ -17,6 +21,12 @@ export const useSubAccountS3Client = (entityId: string | null, memberId: string error: null, }); const clientRef = useRef(null); + const [attempt, setAttempt] = useState(0); + + const retry = useCallback(() => { + setState((prev) => ({ ...prev, isLoading: true, error: null })); + setAttempt((n) => n + 1); + }, []); useEffect(() => { if (!entityId || !memberId) { @@ -50,9 +60,9 @@ export const useSubAccountS3Client = (entityId: string | null, memberId: string return () => { clientRef.current?.destroy(); }; - }, [entityId, memberId]); + }, [entityId, memberId, attempt]); - return state; + return { ...state, retry }; }; export function useOnS3ClientReadyEffect( diff --git a/src/sub-account/hooks/useUsageData.test.ts b/src/sub-account/hooks/useUsageData.test.ts new file mode 100644 index 00000000..80ee527a --- /dev/null +++ b/src/sub-account/hooks/useUsageData.test.ts @@ -0,0 +1,47 @@ +import { act } from 'react'; +import { afterEach, describe, expect, test, vi } from 'vitest'; +import { useUsageData } from './useUsageData'; +import subAccountAxios from '../core/sub-account-axios'; +import { renderHook, settle, unmountHooks } from '../../testing/render-hook'; + +const usageItem = { + startTime: '2026-12-03T00:00:00Z', + endTime: '2026-12-04T00:00:00Z', + activeStorage: 2, + deletedStorage: 0, + activeObjects: 910, +}; + +describe('useUsageData', () => { + afterEach(() => { + unmountHooks(); + vi.restoreAllMocks(); + }); + + test('when the request is still pending, then it reports loading rather than an empty range', async () => { + vi.spyOn(subAccountAxios, 'get').mockReturnValue(new Promise(() => {})); + + const result = await renderHook(() => useUsageData('sa1')); + + expect(result.current).toMatchObject({ isLoading: true, error: null, sorted: [] }); + }); + + test('when the request fails, then it exposes the error and retry loads the data', async () => { + const failure = new Error('provider down'); + const get = vi + .spyOn(subAccountAxios, 'get') + .mockRejectedValueOnce(failure) + .mockResolvedValueOnce({ data: [usageItem] }); + + const result = await renderHook(() => useUsageData('sa1')); + + expect(result.current).toMatchObject({ isLoading: false, error: failure, sorted: [] }); + + await act(async () => result.current.retry()); + await settle(); + + expect(get).toHaveBeenCalledTimes(2); + expect(result.current.error).toBeNull(); + expect(result.current.totals.objects).toBe(910); + }); +}); diff --git a/src/sub-account/hooks/useUsageData.ts b/src/sub-account/hooks/useUsageData.ts index 6c607687..bd4fc523 100644 --- a/src/sub-account/hooks/useUsageData.ts +++ b/src/sub-account/hooks/useUsageData.ts @@ -48,7 +48,9 @@ export function useUsageData(entityId?: string | null) { const [fromDate, setFromDate] = useState(dayjs().subtract(30, 'days').format('YYYY-MM-DD')); const [toDate, setToDate] = useState(dayjs().format('YYYY-MM-DD')); const [records, setRecords] = useState([]); - const [isLoading, setIsLoading] = useState(false); + const [isLoading, setIsLoading] = useState(Boolean(entityId)); + const [error, setError] = useState(null); + const [attempt, setAttempt] = useState(0); const [pageNumber, setPageNumber] = useState(1); const [pageSize, setPageSize] = useState(PAGE_SIZE_OPTIONS[0]); @@ -73,6 +75,7 @@ export function useUsageData(entityId?: string | null) { (async () => { setIsLoading(true); + setError(null); try { const { data } = await subAccountAxios.get(`/sub-accounts/${entityId}/usages`, { params: { from: fromDate, to: toDate, page: 0, perPage: daysBetween(fromDate, toDate) }, @@ -86,8 +89,11 @@ export function useUsageData(entityId?: string | null) { objects: u.activeObjects, })), ); - } catch { - if (!cancelled) setRecords([]); + } catch (err) { + if (!cancelled) { + setRecords([]); + setError(err); + } } finally { if (!cancelled) setIsLoading(false); } @@ -96,7 +102,7 @@ export function useUsageData(entityId?: string | null) { return () => { cancelled = true; }; - }, [fromDate, toDate, entityId]); + }, [fromDate, toDate, entityId, attempt]); const sorted = useMemo(() => { return [...records].sort((a, b) => b.date.localeCompare(a.date)); @@ -122,6 +128,8 @@ export function useUsageData(entityId?: string | null) { handleFromChange, handleToChange, isLoading, + error, + retry: () => setAttempt((n) => n + 1), sorted, paged, totals, diff --git a/src/sub-account/views/SubAccountBucketDetailPage.tsx b/src/sub-account/views/SubAccountBucketDetailPage.tsx index 14f17390..2f1f6534 100644 --- a/src/sub-account/views/SubAccountBucketDetailPage.tsx +++ b/src/sub-account/views/SubAccountBucketDetailPage.tsx @@ -48,6 +48,8 @@ import { useSubAccount } from '../context/useSubAccount'; import { DeleteBucketConfirmModal } from '../components/DeleteBucketConfirmModal'; import { RetentionConfirmModal } from '../components/RetentionConfirmModal'; import { ShareModal } from '../components/ShareModal'; +import { ListErrorState, ListSkeletonRows, StatPlaceholder } from '../components/ListStates'; +import { useS3ListLoad } from '../hooks/listLoad'; import { T, shadow, text } from '../tokens'; import { S3Client } from '@aws-sdk/client-s3'; @@ -513,7 +515,7 @@ export const SubAccountBucketDetailPage = () => { const prefix = searchParams.get('prefix') ?? ''; const { entityId, memberId, isAdmin } = useSubAccount(); - const { credentials } = useSubAccountS3Client(entityId, memberId); + const { credentials, error: credentialsError, retry: retryCredentials } = useSubAccountS3Client(entityId, memberId); const [endpointParam] = useState(() => searchParams.get('endpoint')); const [regionParam] = useState(() => searchParams.get('region')); @@ -534,7 +536,8 @@ export const SubAccountBucketDetailPage = () => { const [activeTab, setActiveTab] = useState<'objects' | 'properties'>('objects'); const [objects, setObjects] = useState([]); - const [isLoading, setIsLoading] = useState(false); + const [isLoading, setIsLoading] = useState(true); + const [objectsError, setObjectsError] = useState(null); const [selectedVersions, setSelectedVersions] = useState>(new Set()); const [searchQuery, setSearchQuery] = useState(''); const [showVersions, setShowVersions] = useLocalStorage('showVersions', false); @@ -850,6 +853,7 @@ export const SubAccountBucketDetailPage = () => { const loadObjects = async (s3: S3Client) => { if (!bucketName) return; setIsLoading(true); + setObjectsError(null); setSelectedVersions(new Set()); try { if (showVersions) { @@ -875,13 +879,29 @@ export const SubAccountBucketDetailPage = () => { recordPage(result); } } catch (err) { - const msg = isAccessDeniedError(err) ? t('bucketDetail.insufficientPermissions') : (err as Error).message; - notificationsService.error({ text: msg }); + setObjectsError(err); } finally { setIsLoading(false); } }; + const { + status: objectsStatus, + error: objectsLoadError, + message: objectsLoadMessage, + retry: retryLoadObjects, + } = useS3ListLoad({ + credentialsError, + retryCredentials, + isLoading, + listError: objectsError, + reload: () => client && loadObjects(client), + fallbackMessage: t('listStates.genericError'), + }); + const objectsLoadErrorMessage = isAccessDeniedError(objectsLoadError) + ? t('bucketDetail.insufficientPermissions') + : objectsLoadMessage; + const navigateToPrefix = (newPrefix: string) => { const next: Record = {}; if (endpointParam) next.endpoint = endpointParam; @@ -1312,7 +1332,11 @@ export const SubAccountBucketDetailPage = () => { fontVariantNumeric: 'tabular-nums', }} > - {t('bucketDetail.objectCount', { count: displayObjects.length })} + {objectsStatus === 'error' ? null : objectsStatus === 'loading' ? ( + + ) : ( + t('bucketDetail.objectCount', { count: displayObjects.length }) + )} {
{/* Rows / states */} - {isLoading ? ( -
- {t('bucketDetail.loadingObjects')} -
+ {objectsStatus === 'error' ? ( + + ) : objectsStatus === 'loading' ? ( + ) : displayObjects.length === 0 ? ( ( @@ -91,7 +101,7 @@ const StatStrip = ({ stats }: { stats: StatItem[] }) => ( fontVariantNumeric: 'tabular-nums', }} > - {s.value} + {s.status && s.status !== 'ready' ? : s.value}

{s.hint}

@@ -221,7 +231,9 @@ interface BucketsTableProps { buckets: BucketRecord[]; totalCount: number; regions: SubAccountRegion[]; - isLoading: boolean; + status: ListStatus; + loadErrorMessage: string; + onRetry: () => void; search: string; onSearchChange: (v: string) => void; onOpen: (bucket: BucketRecord) => void; @@ -233,7 +245,9 @@ const BucketsTable = ({ buckets, totalCount, regions, - isLoading, + status, + loadErrorMessage, + onRetry, search, onSearchChange, onOpen, @@ -265,7 +279,13 @@ const BucketsTable = ({

{t('buckets.title')}

- {t('buckets.totalCount', { count: totalCount })} + {status === 'ready' ? ( + t('buckets.totalCount', { count: totalCount }) + ) : status === 'loading' ? ( + + ) : ( + ' ' + )}

@@ -319,10 +339,10 @@ const BucketsTable = ({
{/* Body */} - {isLoading ? ( -
- {t('buckets.loading')} -
+ {status === 'loading' ? ( + + ) : status === 'error' ? ( + ) : buckets.length === 0 ? (

{t('buckets.noBucketsFound')}

@@ -579,10 +599,16 @@ export const SubAccountBucketsPage = () => { const { t } = useTranslation('subaccount'); const navigate = useNavigate(); const { entityId, memberId } = useSubAccount(); - const { client, credentials } = useSubAccountS3Client(entityId, memberId); + const { + client, + credentials, + error: credentialsError, + retry: retryCredentials, + } = useSubAccountS3Client(entityId, memberId); const [allBuckets, setAllBuckets] = useState([]); - const [isLoading, setIsLoading] = useState(false); + const [isLoading, setIsLoading] = useState(true); + const [bucketsError, setBucketsError] = useState(null); const [search, setSearch] = useState(''); const [regions, setRegions] = useState([]); const [isCreateOpen, setIsCreateOpen] = useState(false); @@ -631,6 +657,7 @@ export const SubAccountBucketsPage = () => { bucketsAbortRef.current = controller; setIsLoading(true); + setBucketsError(null); try { const buckets = await fetchAllBuckets(s3Client, controller.signal); setAllBuckets( @@ -642,7 +669,7 @@ export const SubAccountBucketsPage = () => { ); } catch (err) { if ((err as Error).name !== 'AbortError') { - notificationsService.error({ text: (err as Error).message }); + setBucketsError(err); } } finally { if (bucketsAbortRef.current === controller) { @@ -691,11 +718,32 @@ export const SubAccountBucketsPage = () => { [filteredBuckets, pageNumber, pageSize], ); + const { + status: listStatus, + message: loadErrorMessage, + retry: retryLoad, + } = useS3ListLoad({ + credentialsError, + retryCredentials, + isLoading, + listError: bucketsError, + reload: () => client && refreshBuckets(client), + fallbackMessage: t('listStates.genericError'), + }); + const stats: StatItem[] = [ { label: t('buckets.title'), value: String(allBuckets.length), - hint: t('buckets.statBucketsHint', { count: regionCount }), + hint: + listStatus === 'ready' ? ( + t('buckets.statBucketsHint', { count: regionCount }) + ) : listStatus === 'loading' ? ( + + ) : ( + t('listStates.unavailable') + ), + status: listStatus, }, { label: t('buckets.statObjectsStored'), value: '—', hint: t('buckets.statObjectsStoredHint') }, { label: t('buckets.statUsedStorage'), value: '—', hint: t('buckets.statUsedStorageHint') }, @@ -750,7 +798,9 @@ export const SubAccountBucketsPage = () => { buckets={pagedBuckets} totalCount={filteredBuckets.length} regions={regions} - isLoading={isLoading} + status={listStatus} + loadErrorMessage={loadErrorMessage} + onRetry={retryLoad} search={search} onSearchChange={onSearchChange} onOpen={handleOpen} @@ -766,7 +816,7 @@ export const SubAccountBucketsPage = () => { hasNextPage={pageNumber < pageCount} onPrev={() => setPageNumber((n) => Math.max(1, n - 1))} onNext={() => setPageNumber((n) => Math.min(pageCount, n + 1))} - isLoading={isLoading} + isLoading={listStatus === 'loading'} /> { const [shares, setShares] = useState([]); const isPublicSharingEnabled = usePublicSharingEnabled(entityId).isEnabled === true; const [isTogglingVisibility, setIsTogglingVisibility] = useState(false); - const [isLoading, setIsLoading] = useState(false); + const [isLoading, setIsLoading] = useState(Boolean(entityId)); + const [loadError, setLoadError] = useState(null); const [search, setSearch] = useState(''); const [pageNumber, setPageNumber] = useState(1); const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE); @@ -42,18 +44,21 @@ export const SubAccountSharedPage = () => { } }; - useEffect(() => { + const loadShares = useCallback(() => { if (!entityId) return; - // eslint-disable-next-line react-hooks/set-state-in-effect setIsLoading(true); + setLoadError(null); shareService .listShares(entityId) .then(setShares) - .catch((err) => { - notificationsService.error({ text: apiErrorMessage(err, t('shares.loadError')) }); - }) + .catch(setLoadError) .finally(() => setIsLoading(false)); - }, [entityId, t]); + }, [entityId]); + + useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect + loadShares(); + }, [loadShares]); const canToggleVisibility = (share: ShareListItem) => isPublicSharingEnabled && (isAdmin || share.memberId === memberId); @@ -122,7 +127,9 @@ export const SubAccountSharedPage = () => { ( +const StatStrip = ({ stats, status }: { stats: StatItem[]; status: ListStatus }) => (
{stats.map((s, i) => (
( fontVariantNumeric: 'tabular-nums', }} > - {s.value} + {status === 'ready' ? s.value : } - {s.unit && {s.unit}} + {s.unit && status === 'ready' && {s.unit}}

{s.hint}

@@ -218,6 +221,8 @@ export const UsageView = () => { handleFromChange, handleToChange, isLoading, + error, + retry, sorted, paged, totals, @@ -228,6 +233,17 @@ export const UsageView = () => { goToNextPage, } = useUsageData(entityId); + const status = toListStatus(isLoading, error); + + const objectsHint = + status === 'ready' ? ( + t('usage.statActiveObjectsHint', { count: totals.objects.toLocaleString('en-US') }) + ) : status === 'loading' ? ( + + ) : ( + t('listStates.unavailable') + ); + const stats: StatItem[] = [ { label: t('usage.statActiveStorage'), @@ -244,7 +260,7 @@ export const UsageView = () => { { label: t('usage.statActiveObjects'), value: fmtObjects(totals.objects), - hint: t('usage.statActiveObjectsHint', { count: totals.objects.toLocaleString('en-US') }), + hint: objectsHint, }, ]; @@ -269,7 +285,7 @@ export const UsageView = () => { padding: '8px 0 32px', }} > - + {/* Account Usage card */}
@@ -391,10 +407,14 @@ export const UsageView = () => {
{/* Rows */} - {isLoading ? ( -
- {t('usage.loading')} -
+ {status === 'error' ? ( + + ) : status === 'loading' ? ( + ) : sorted.length === 0 ? (

{t('usage.empty')}

diff --git a/src/testing/render-hook.ts b/src/testing/render-hook.ts new file mode 100644 index 00000000..a1f3fc49 --- /dev/null +++ b/src/testing/render-hook.ts @@ -0,0 +1,31 @@ +import { act, createElement } from 'react'; +import { createRoot } from 'react-dom/client'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const mounted: (() => void)[] = []; + +export async function settle() { + for (let i = 0; i < 10; i++) { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + } +} + +export async function renderHook(useHook: () => T) { + const result: { current: T } = { current: undefined as unknown as T }; + const Probe = () => { + result.current = useHook(); + return null; + }; + const root = createRoot(document.createElement('div')); + await act(async () => root.render(createElement(Probe))); + mounted.push(() => act(() => root.unmount())); + await settle(); + return result; +} + +export function unmountHooks() { + mounted.splice(0).forEach((unmount) => unmount()); +} diff --git a/src/wholesalers/hooks/usePartnerMonthlyUsage.test.ts b/src/wholesalers/hooks/usePartnerMonthlyUsage.test.ts index 3680666e..d3fb56ec 100644 --- a/src/wholesalers/hooks/usePartnerMonthlyUsage.test.ts +++ b/src/wholesalers/hooks/usePartnerMonthlyUsage.test.ts @@ -1,36 +1,13 @@ -import { act, createElement } from 'react'; -import { createRoot } from 'react-dom/client'; +import { act } from 'react'; import dayjs from 'dayjs'; import { afterEach, describe, expect, test, vi } from 'vitest'; import { usePartnerMonthlyUsage } from './usePartnerMonthlyUsage'; import { wholesalersService, PartnerMonthlyUsageChunk } from '../services/wholesalers.service'; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +import { renderHook, settle, unmountHooks } from '../../testing/render-hook'; type HookResult = ReturnType; -async function settle() { - for (let i = 0; i < 10; i++) { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - } -} - -const cleanups: (() => void)[] = []; - -async function renderUsageHook(partnerId = 'p1') { - const result: { current: HookResult } = { current: undefined as unknown as HookResult }; - const Probe = () => { - result.current = usePartnerMonthlyUsage(partnerId); - return null; - }; - const root = createRoot(document.createElement('div')); - await act(async () => root.render(createElement(Probe))); - cleanups.push(() => act(() => root.unmount())); - await settle(); - return result; -} +const renderUsageHook = (partnerId = 'p1') => renderHook(() => usePartnerMonthlyUsage(partnerId)); function mockServer(lastMonth: string, firstMonth: string) { return vi @@ -52,7 +29,7 @@ const months = (result: { current: HookResult }) => result.current.items.map((it describe('usePartnerMonthlyUsage', () => { afterEach(() => { - cleanups.splice(0).forEach((cleanup) => cleanup()); + unmountHooks(); vi.restoreAllMocks(); });