Skip to content
Draft
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
112 changes: 48 additions & 64 deletions assets/src/admin/logs/apiService.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';

/**
* Internal dependencies
*/
import type {
APIResponse,
fetchReturn,
FilterOptions,
OneLogsDataType,
SharedSite,
} from './types';
import apiFetch from '@wordpress/api-fetch';
import { NONCE, API_KEY } from '../../js/constants';

declare global {
interface Window {
OneLogsData?: OneLogsDataType;
}
}
import { REST_NAMESPACE, SHARED_SITES } from '../../js/constants';

type FetchOptions = {
filters?: {
site_url?: string | undefined;
};
queryParams?: URLSearchParams;
returnKey?: string;
headers?: Record< string, string >;
};

export const fetchLogs = async ( filters: FilterOptions ) => {
Expand All @@ -31,39 +31,23 @@ export const fetchLogs = async ( filters: FilterOptions ) => {
date_to: filters.date_to ? `${ filters.date_to } 23:59:59` : undefined,
};

if ( filters.site_url === 'governing-site' ) {
formattedFilters.current_site_logs = true;
const isBrandSite =
!! filters.site_url && filters.site_url !== 'governing-site';

// The governing site fetches a selected brand site's logs for the browser.
formattedFilters.current_site_logs = ! isBrandSite;
formattedFilters.include_shared_sites = isBrandSite;
if ( ! isBrandSite ) {
formattedFilters.site_url = undefined;
formattedFilters.include_shared_sites = false;
} else {
formattedFilters.current_site_logs = false;
formattedFilters.include_shared_sites = true;
}

if ( ! formattedFilters.current_site_logs ) {
const queryParams = new URLSearchParams();
formattedFilters.include_shared_sites = true;

Object.entries( formattedFilters ).forEach( ( [ key, value ] ) => {
if ( value !== undefined && value !== null && key !== 'site_id' ) {
queryParams.append( key, String( value ) );
}
} );

const apiResponse = await oneLogsFetch< APIResponse >( 'logs', {
queryParams,
} );

return {
logs: apiResponse?.data || [],
total: apiResponse?.meta.total || 0,
pages: apiResponse?.meta.total_pages || 1,
errors: apiResponse?.meta.errors,
};
}
const queryParams = new URLSearchParams();
Object.entries( formattedFilters ).forEach( ( [ key, value ] ) => {
if ( value !== undefined && value !== null ) {
if (
value !== undefined &&
value !== null &&
! ( isBrandSite && key === 'site_id' )
) {
queryParams.append( key, String( value ) );
}
} );
Expand All @@ -73,10 +57,11 @@ export const fetchLogs = async ( filters: FilterOptions ) => {
} );

return {
logs: apiResponse.data,
total: apiResponse.meta.total,
pages: apiResponse.meta.total_pages,
errors: null,
// A missing list is no logs, never a crash.
logs: Array.isArray( apiResponse?.data ) ? apiResponse.data : [],
total: apiResponse?.meta?.total || 0,
pages: apiResponse?.meta?.total_pages || 1,
errors: isBrandSite ? apiResponse?.meta?.errors : null,
};
};

Expand Down Expand Up @@ -104,12 +89,21 @@ export const fetchUsers = async (
filters: FilterOptions
): Promise< APIResponse > => oneLogsFetch( 'logs/users', { filters } );

export const fetchSharedSites = async () =>
oneLogsFetch( 'shared-sites', { returnKey: 'shared_sites' } );

export const fetchSiteType = async () =>
oneLogsFetch( 'site-type', { returnKey: 'site_type' } );

/**
* Gets the governing site's brand sites, which the page already has.
*/
export const fetchSharedSites = async (): Promise< SharedSite[] > =>
SHARED_SITES;

/**
* Requests a OneLogs route on this site.
*
* WordPress sets up apiFetch with the REST root and nonce, so requests only need the path.
* Rejects with the REST error, like `{ code, message }`, when the route fails.
*
* @param endpoint The route, relative to the OneLogs namespace.
* @param options The query, and the key of the response to return.
*/
const oneLogsFetch = async < T extends fetchReturn >(
endpoint: string,
options: FetchOptions = {}
Expand All @@ -121,25 +115,15 @@ const oneLogsFetch = async < T extends fetchReturn >(
if ( queryParams ) {
query = `?${ queryParams.toString() }`;
} else if ( filters?.site_url && filters.site_url !== 'governing-site' ) {
query = `?site_url=${ filters.site_url }`;
query = `?${ new URLSearchParams( {
site_url: filters.site_url,
} ).toString() }`;
}

apiFetch.use( apiFetch.createNonceMiddleware( NONCE ) );

apiFetch.use( ( fetchOptions, next ) => {
fetchOptions.headers = {
...( fetchOptions.headers || {} ),
'X-OneLogs-Token': API_KEY,
};
return next( fetchOptions );
} );

const apiResponse = await apiFetch( {
path: `/onelogs/v1/${ endpoint }${ query }`,
const result = await apiFetch< APIResponse >( {
path: `/${ REST_NAMESPACE }/${ endpoint }${ query }`,
method: 'GET',
} );

const result = apiResponse as APIResponse;

return ( returnKey ? result[ returnKey ] ?? [] : result ) as T;
return ( returnKey ? result?.[ returnKey ] ?? [] : result ) as T;
};
25 changes: 4 additions & 21 deletions assets/src/admin/logs/components/FiltersPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useRef } from 'react';
import { __ } from '@wordpress/i18n';
import { Button, SelectControl, TextControl } from '@wordpress/components';

Check warning on line 3 in assets/src/admin/logs/components/FiltersPanel.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `InputControl` from `@wordpress/ui` instead. See migration guide in the lint rule documentation
import { debounce } from '@wordpress/compose';
import { fetchSiteType } from '../apiService';
import type {
fetchReturn,
FilterOptions,
SharedSite,
UserOption,
} from '../types';
import { SITE_TYPE } from '../../../js/constants';
import type { FilterOptions, SharedSite, UserOption } from '../types';

interface FiltersPanelProps {
localSearch: string;
Expand Down Expand Up @@ -51,21 +46,9 @@
( ( searchValue: string | undefined ) => void ) | null
>( null );

const [ siteType, setSiteType ] = useState< string | fetchReturn >( '' );
const today = new Date().toISOString().split( 'T' )[ 0 ];

const loadSiteType = async () => {
try {
const data = await fetchSiteType();
setSiteType( data );
} catch ( err ) {
// eslint-disable-next-line no-console
console.log( err );
}
};

useEffect( () => {
loadSiteType();
const debouncedFn = debounce( ( searchValue: unknown ) => {
handleFilterChange( 'search', searchValue as string );
}, 500 );
Expand All @@ -76,7 +59,7 @@
return (
<div>
<div className="onelogs-advanced-filters-grid">
{ siteType && siteType === 'governing-site' && (
{ SITE_TYPE === 'governing-site' && (
<SelectControl
__next40pxDefaultSize
__nextHasNoMarginBottom
Expand Down
65 changes: 48 additions & 17 deletions assets/src/admin/logs/components/LogsDashboard.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useCallback } from 'react';
import { createRoot } from 'react-dom/client';
import { __, sprintf } from '@wordpress/i18n';
import { Card, CardBody, CardHeader, Spinner } from '@wordpress/components';

Check warning on line 4 in assets/src/admin/logs/components/LogsDashboard.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Header` (and optionally `Card.Title`) from `@wordpress/ui` instead

Check warning on line 4 in assets/src/admin/logs/components/LogsDashboard.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Content` from `@wordpress/ui` instead

Check warning on line 4 in assets/src/admin/logs/components/LogsDashboard.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Root` from `@wordpress/ui` instead
import {
fetchActions,
fetchConnectors as apiFetchConnectors,
Expand All @@ -20,6 +20,7 @@
SortState,
UserOption,
} from '../types';
import { getErrorMessage } from '../../../js/utils';

const LogsDashboard: React.FC = () => {
const [ logs, setLogs ] = useState< LogEntry[] >( [] );
Expand Down Expand Up @@ -55,7 +56,7 @@

try {
const result = await apiFetchLogs( filters );
setLogs( result.logs as LogEntry[] );
setLogs( ( result.logs ?? [] ) as LogEntry[] );
setTotalLogs( result.total );
setTotalPages( result.pages );

Expand All @@ -69,10 +70,15 @@
);
}
} catch ( err ) {
// Clear the previous site's logs, so they're not shown under this error.
setLogs( [] );
setTotalLogs( 0 );
setTotalPages( 1 );
setError(
err instanceof Error
? err.message
: __( 'An error occurred while fetching logs', 'onelogs' )
getErrorMessage(
err,
__( 'An error occurred while fetching logs', 'onelogs' )
)
);
} finally {
setLoading( false );
Expand Down Expand Up @@ -164,27 +170,46 @@
const loadContexts = useCallback( async () => {
try {
const data = await apiFetchContexts( filters );
setContexts( data );
} catch {
setError( __( 'Error fetching contexts:', 'onelogs' ) );
setContexts( Array.isArray( data ) ? data : [] );
} catch ( err ) {
setContexts( [] );
setError(
getErrorMessage(
err,
__( 'Error fetching contexts.', 'onelogs' )
)
);
}
}, [ filters ] );

const loadConnectors = useCallback( async () => {
try {
const data = await apiFetchConnectors( filters );
setConnectors( data );
} catch {
setError( __( 'Error fetching connectors:', 'onelogs' ) );
setConnectors( Array.isArray( data ) ? data : [] );
} catch ( err ) {
setConnectors( [] );
setError(
getErrorMessage(
err,
__( 'Error fetching connectors.', 'onelogs' )
)
);
}
}, [ filters ] );

const loadUsers = useCallback( async () => {
try {
const response = await apiFetchUsers( filters );
setUsers( response.data as UserOption[] );
} catch {
setError( __( 'Error fetching users:', 'onelogs' ) );
setUsers(
Array.isArray( response?.data )
? ( response.data as UserOption[] )
: []
);
} catch ( err ) {
setUsers( [] );
setError(
getErrorMessage( err, __( 'Error fetching users.', 'onelogs' ) )
);
}
}, [ filters ] );

Expand All @@ -193,16 +218,22 @@
const response = await apiFetchSharedSites();
setSharedSites( response as SharedSite[] );
} catch {
setError( __( 'Error fetching shared sites:', 'onelogs' ) );
setError( __( 'Error fetching shared sites.', 'onelogs' ) );
}
}, [] );

const loadActions = useCallback( async () => {
try {
const data = await fetchActions( filters );
setActions( data );
} catch {
setError( __( 'Error fetching shared sites:', 'onelogs' ) );
setActions( Array.isArray( data ) ? data : [] );
} catch ( err ) {
setActions( [] );
setError(
getErrorMessage(
err,
__( 'Error fetching actions.', 'onelogs' )
)
);
}
}, [ filters ] );

Expand Down
22 changes: 5 additions & 17 deletions assets/src/admin/logs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,9 @@ export type APIResponse = {

export type StringArrayResponse = string[];

export type fetchReturn =
| APIResponse
| StringArrayResponse
| string
| SharedSite[];
export type fetchReturn = APIResponse | StringArrayResponse;

export interface SharedSite {
api_key: string;
id: string;
name: string;
url: string;
}

export interface OneLogsDataType {
restUrl: string;
nonce: string;
apiKey: string;
}
/**
* A brand site, without its API key, which never leaves the server.
*/
export type { OneLogsSharedSite as SharedSite } from '@/types/global';
14 changes: 1 addition & 13 deletions assets/src/admin/onboarding/index.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
import { createRoot } from 'react-dom/client';
import OnboardingScreen, { type SiteType } from './page';

interface OneLogsSettings {
nonce: string;
siteType: SiteType | '';
setupUrl: string;
}

declare global {
interface Window {
OneLogsSettings: OneLogsSettings;
}
}
import OnboardingScreen from './page';

// Render to the target element.
const target = document.getElementById( 'onelogs-site-selection-modal' );
Expand Down
9 changes: 3 additions & 6 deletions assets/src/admin/onboarding/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import {
Card,

Check warning on line 5 in assets/src/admin/onboarding/page.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Root` from `@wordpress/ui` instead
CardHeader,

Check warning on line 6 in assets/src/admin/onboarding/page.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Header` (and optionally `Card.Title`) from `@wordpress/ui` instead
CardBody,

Check warning on line 7 in assets/src/admin/onboarding/page.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Card.Content` from `@wordpress/ui` instead
Notice,

Check warning on line 8 in assets/src/admin/onboarding/page.tsx

View workflow job for this annotation

GitHub Actions / CSS/JS Lint / JS Lint & TypeScript

Use `Notice` from `@wordpress/ui` instead
Button,
SelectControl,
} from '@wordpress/components';
Expand All @@ -20,12 +20,9 @@
message: string;
}

const { nonce, setupUrl, siteType: initialSiteType } = window.OneLogsSettings;

/**
* Create NONCE middleware for apiFetch
*/
apiFetch.use( apiFetch.createNonceMiddleware( nonce ) );
// WordPress sets up apiFetch's nonce and root URL, so no middleware is needed here.
const setupUrl = window.OneLogsSettings?.setupUrl ?? '';
const initialSiteType = window.OneLogsSettings?.siteType ?? '';

const SiteTypeSelector = ( {
value,
Expand Down
Loading
Loading