Add basic activity log view
This commit is contained in:
parent
d1da46c5aa
commit
c6e8b893c8
9 changed files with 267 additions and 17 deletions
24
resources/scripts/api/account/activity.ts
Normal file
24
resources/scripts/api/account/activity.ts
Normal file
|
@ -0,0 +1,24 @@
|
|||
import useUserSWRContentKey from '@/plugins/useUserSWRContentKey';
|
||||
import useSWR, { ConfigInterface, responseInterface } from 'swr';
|
||||
import { ActivityLog, Transformers } from '@definitions/user';
|
||||
import { AxiosError } from 'axios';
|
||||
import http, { PaginatedResult } from '@/api/http';
|
||||
import { toPaginatedSet } from '@definitions/helpers';
|
||||
|
||||
const useActivityLogs = (page = 1, config?: ConfigInterface<PaginatedResult<ActivityLog>, AxiosError>): responseInterface<PaginatedResult<ActivityLog>, AxiosError> => {
|
||||
const key = useUserSWRContentKey([ 'account', 'activity', page.toString() ]);
|
||||
|
||||
return useSWR<PaginatedResult<ActivityLog>>(key, async () => {
|
||||
const { data } = await http.get('/api/client/account/activity', {
|
||||
params: {
|
||||
include: [ 'actor' ],
|
||||
sort: '-timestamp',
|
||||
page: page,
|
||||
},
|
||||
});
|
||||
|
||||
return toPaginatedSet(data, Transformers.toActivityLog);
|
||||
}, { revalidateOnMount: false, ...(config || {}) });
|
||||
};
|
||||
|
||||
export { useActivityLogs };
|
|
@ -1,13 +1,20 @@
|
|||
import { FractalResponseData, FractalResponseList } from '@/api/http';
|
||||
import {
|
||||
FractalPaginatedResponse,
|
||||
FractalResponseData,
|
||||
FractalResponseList,
|
||||
getPaginationSet,
|
||||
PaginatedResult,
|
||||
} from '@/api/http';
|
||||
import { Model } from '@definitions/index';
|
||||
|
||||
type Transformer<T> = (callback: FractalResponseData) => T;
|
||||
type TransformerFunc<T> = (callback: FractalResponseData) => T;
|
||||
|
||||
const isList = (data: FractalResponseList | FractalResponseData): data is FractalResponseList => data.object === 'list';
|
||||
|
||||
function transform<T, M>(data: null | undefined, transformer: Transformer<T>, missing?: M): M;
|
||||
function transform<T, M>(data: FractalResponseData | null | undefined, transformer: Transformer<T>, missing?: M): T | M;
|
||||
function transform<T, M>(data: FractalResponseList | null | undefined, transformer: Transformer<T>, missing?: M): T[] | M;
|
||||
function transform<T> (data: FractalResponseData | FractalResponseList | null | undefined, transformer: Transformer<T>, missing = undefined) {
|
||||
function transform<T, M>(data: null | undefined, transformer: TransformerFunc<T>, missing?: M): M;
|
||||
function transform<T, M>(data: FractalResponseData | null | undefined, transformer: TransformerFunc<T>, missing?: M): T | M;
|
||||
function transform<T, M>(data: FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc<T>, missing?: M): T[] | M;
|
||||
function transform<T> (data: FractalResponseData | FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc<T>, missing = undefined) {
|
||||
if (data === undefined || data === null) {
|
||||
return missing;
|
||||
}
|
||||
|
@ -23,4 +30,14 @@ function transform<T> (data: FractalResponseData | FractalResponseList | null |
|
|||
return transformer(data);
|
||||
}
|
||||
|
||||
export { transform };
|
||||
function toPaginatedSet<T extends TransformerFunc<Model>> (
|
||||
response: FractalPaginatedResponse,
|
||||
transformer: T,
|
||||
): PaginatedResult<ReturnType<T>> {
|
||||
return {
|
||||
items: transform(response, transformer) as ReturnType<T>[],
|
||||
pagination: getPaginationSet(response.meta.pagination),
|
||||
};
|
||||
}
|
||||
|
||||
export { transform, toPaginatedSet };
|
||||
|
|
|
@ -3,7 +3,7 @@ import { FractalResponseData } from '@/api/http';
|
|||
import { transform } from '@definitions/helpers';
|
||||
|
||||
export default class Transformers {
|
||||
static toSSHKey (data: Record<any, any>): Models.SSHKey {
|
||||
static toSSHKey = (data: Record<any, any>): Models.SSHKey => {
|
||||
return {
|
||||
name: data.name,
|
||||
publicKey: data.public_key,
|
||||
|
@ -12,7 +12,7 @@ export default class Transformers {
|
|||
};
|
||||
}
|
||||
|
||||
static toUser ({ attributes }: FractalResponseData): Models.User {
|
||||
static toUser = ({ attributes }: FractalResponseData): Models.User => {
|
||||
return {
|
||||
uuid: attributes.uuid,
|
||||
username: attributes.username,
|
||||
|
@ -27,7 +27,7 @@ export default class Transformers {
|
|||
};
|
||||
}
|
||||
|
||||
static toActivityLog ({ attributes }: FractalResponseData): Models.ActivityLog {
|
||||
static toActivityLog = ({ attributes }: FractalResponseData): Models.ActivityLog => {
|
||||
const { actor } = attributes.relationships || {};
|
||||
|
||||
return {
|
||||
|
|
|
@ -77,12 +77,26 @@ export interface FractalResponseList {
|
|||
data: FractalResponseData[];
|
||||
}
|
||||
|
||||
export interface FractalPaginatedResponse extends FractalResponseList {
|
||||
meta: {
|
||||
pagination: {
|
||||
total: number;
|
||||
count: number;
|
||||
/* eslint-disable camelcase */
|
||||
per_page: number;
|
||||
current_page: number;
|
||||
total_pages: number;
|
||||
/* eslint-enable camelcase */
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface PaginatedResult<T> {
|
||||
items: T[];
|
||||
pagination: PaginationDataSet;
|
||||
}
|
||||
|
||||
interface PaginationDataSet {
|
||||
export interface PaginationDataSet {
|
||||
total: number;
|
||||
count: number;
|
||||
perPage: number;
|
||||
|
@ -99,3 +113,43 @@ export function getPaginationSet (data: any): PaginationDataSet {
|
|||
totalPages: data.total_pages,
|
||||
};
|
||||
}
|
||||
|
||||
type QueryBuilderFilterValue = string | number | boolean | null;
|
||||
|
||||
export interface QueryBuilderParams<FilterKeys extends string = string, SortKeys extends string = string> {
|
||||
filters?: {
|
||||
[K in FilterKeys]?: QueryBuilderFilterValue | Readonly<QueryBuilderFilterValue[]>;
|
||||
};
|
||||
sorts?: {
|
||||
[K in SortKeys]?: -1 | 0 | 1 | 'asc' | 'desc' | null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function that parses a data object provided and builds query parameters
|
||||
* for the Laravel Query Builder package automatically. This will apply sorts and
|
||||
* filters deterministically based on the provided values.
|
||||
*/
|
||||
export const withQueryBuilderParams = (data?: QueryBuilderParams): Record<string, unknown> => {
|
||||
if (!data) return {};
|
||||
|
||||
const filters = Object.keys(data.filters || {}).reduce((obj, key) => {
|
||||
const value = data.filters?.[key];
|
||||
|
||||
return !value || value === '' ? obj : { ...obj, [`filter[${key}]`]: value };
|
||||
}, {} as NonNullable<QueryBuilderParams['filters']>);
|
||||
|
||||
const sorts = Object.keys(data.sorts || {}).reduce((arr, key) => {
|
||||
const value = data.sorts?.[key];
|
||||
if (!value || ![ 'asc', 'desc', 1, -1 ].includes(value)) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
return [ ...arr, (value === -1 || value === 'desc' ? '-' : '') + key ];
|
||||
}, [] as string[]);
|
||||
|
||||
return {
|
||||
...filters,
|
||||
sorts: !sorts.length ? undefined : sorts.join(','),
|
||||
};
|
||||
};
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import { useActivityLogs } from '@/api/account/activity';
|
||||
import { useFlashKey } from '@/plugins/useFlash';
|
||||
import PageContentBlock from '@/components/elements/PageContentBlock';
|
||||
import FlashMessageRender from '@/components/FlashMessageRender';
|
||||
import { format, formatDistanceToNowStrict } from 'date-fns';
|
||||
import { Link } from 'react-router-dom';
|
||||
import PaginationFooter from '@/components/elements/table/PaginationFooter';
|
||||
import { UserIcon } from '@heroicons/react/outline';
|
||||
import Tooltip from '@/components/elements/tooltip/Tooltip';
|
||||
import { DesktopComputerIcon } from '@heroicons/react/solid';
|
||||
|
||||
export default () => {
|
||||
const { clearAndAddHttpError } = useFlashKey('account');
|
||||
const [ page, setPage ] = useState(1);
|
||||
const { data, isValidating: _, error } = useActivityLogs(page, {
|
||||
revalidateOnMount: true,
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
clearAndAddHttpError(error);
|
||||
}, [ error ]);
|
||||
|
||||
return (
|
||||
<PageContentBlock title={'Account Activity Log'}>
|
||||
<FlashMessageRender byKey={'account'}/>
|
||||
<div className={'bg-gray-700'}>
|
||||
{data?.items.map((activity) => (
|
||||
<div
|
||||
key={`${activity.event}|${activity.timestamp.toString()}`}
|
||||
className={'grid grid-cols-10 py-4 border-b-2 border-gray-800 last:rounded-b last:border-0'}
|
||||
>
|
||||
<div className={'col-span-1 flex items-center justify-center select-none'}>
|
||||
<div className={'flex items-center w-8 h-8 rounded-full bg-gray-600 overflow-hidden'}>
|
||||
{activity.relationships.actor ?
|
||||
<img src={activity.relationships.actor.image} alt={'User avatar'}/>
|
||||
:
|
||||
<UserIcon className={'w-5 h-5 mx-auto'}/>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div className={'col-span-9'}>
|
||||
<div className={'flex items-center text-gray-50'}>
|
||||
{activity.relationships.actor?.username || 'system'}
|
||||
<span className={'text-gray-400'}> — </span>
|
||||
<Link to={`#event=${activity.event}`}>
|
||||
{activity.event}
|
||||
</Link>
|
||||
{typeof activity.properties.useragent === 'string' &&
|
||||
<Tooltip content={activity.properties.useragent} placement={'top'}>
|
||||
<DesktopComputerIcon className={'ml-2 w-4 h-4 cursor-pointer'}/>
|
||||
</Tooltip>
|
||||
}
|
||||
</div>
|
||||
{/* <p className={'mt-1'}>{activity.description || JSON.stringify(activity.properties)}</p> */}
|
||||
<div className={'mt-1 flex items-center text-sm'}>
|
||||
<Link to={`#ip=${activity.ip}`}>{activity.ip}</Link>
|
||||
<span className={'text-gray-400'}> | </span>
|
||||
<Tooltip placement={'right'} content={format(activity.timestamp, 'MMM do, yyyy h:mma')}>
|
||||
<span>
|
||||
{formatDistanceToNowStrict(activity.timestamp, { addSuffix: true })}
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{data && <PaginationFooter pagination={data.pagination} onPageSelect={setPage}/>}
|
||||
</PageContentBlock>
|
||||
);
|
||||
};
|
|
@ -19,10 +19,18 @@
|
|||
@apply p-1;
|
||||
}
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
@apply cursor-not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
@apply bg-transparent focus:ring-neutral-300 focus:ring-opacity-50 hover:bg-neutral-500 active:bg-neutral-500;
|
||||
@apply text-gray-50 bg-transparent focus:ring-neutral-300 focus:ring-opacity-50 hover:bg-neutral-500 active:bg-neutral-500;
|
||||
|
||||
&:disabled {
|
||||
@apply hover:bg-transparent text-gray-300;
|
||||
}
|
||||
}
|
||||
|
||||
.danger {
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
import React from 'react';
|
||||
import { PaginationDataSet } from '@/api/http';
|
||||
import classNames from 'classnames';
|
||||
import { Button } from '@/components/elements/button/index';
|
||||
import { ChevronDoubleLeftIcon, ChevronDoubleRightIcon } from '@heroicons/react/solid';
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
pagination: PaginationDataSet;
|
||||
onPageSelect: (page: number) => void;
|
||||
}
|
||||
|
||||
const PaginationFooter = ({ pagination, className, onPageSelect }: Props) => {
|
||||
const start = (pagination.currentPage - 1) * pagination.perPage;
|
||||
const end = ((pagination.currentPage - 1) * pagination.perPage) + pagination.count;
|
||||
|
||||
const { currentPage: current, totalPages: total } = pagination;
|
||||
|
||||
const pages = { previous: [] as number[], next: [] as number[] };
|
||||
for (let i = 1; i <= 2; i++) {
|
||||
if (current - i >= 1) {
|
||||
pages.previous.push(current - i);
|
||||
}
|
||||
if (current + i <= total) {
|
||||
pages.next.push(current + i);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={classNames('flex items-center justify-between my-2', className)}>
|
||||
<p className={'text-sm text-neutral-500'}>
|
||||
Showing
|
||||
<span className={'font-semibold text-neutral-400'}>
|
||||
{Math.max(start, Math.min(pagination.total, 1))}
|
||||
</span> to
|
||||
<span className={'font-semibold text-neutral-400'}>{end}</span> of
|
||||
<span className={'font-semibold text-neutral-400'}>{pagination.total}</span> results.
|
||||
</p>
|
||||
{pagination.totalPages > 1 &&
|
||||
<div className={'flex space-x-1'}>
|
||||
<Button.Text small disabled={pages.previous.length !== 2} onClick={() => onPageSelect(1)}>
|
||||
<ChevronDoubleLeftIcon className={'w-3 h-3'}/>
|
||||
</Button.Text>
|
||||
{pages.previous.reverse().map((value) => (
|
||||
<Button.Text small key={`previous-${value}`} onClick={() => onPageSelect(value)}>
|
||||
{value}
|
||||
</Button.Text>
|
||||
))}
|
||||
<Button small disabled>{current}</Button>
|
||||
{pages.next.map((value) => (
|
||||
<Button.Text small key={`next-${value}`} onClick={() => onPageSelect(value)}>
|
||||
{value}
|
||||
</Button.Text>
|
||||
))}
|
||||
<Button.Text small disabled={pages.next.length !== 2} onClick={() => onPageSelect(total)}>
|
||||
<ChevronDoubleRightIcon className={'w-3 h-3'}/>
|
||||
</Button.Text>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PaginationFooter;
|
|
@ -19,6 +19,7 @@ import { AnimatePresence, motion } from 'framer-motion';
|
|||
|
||||
interface Props {
|
||||
content: string | React.ReactChild;
|
||||
disabled?: boolean;
|
||||
arrow?: boolean;
|
||||
placement?: Placement;
|
||||
strategy?: Strategy;
|
||||
|
@ -33,8 +34,8 @@ const arrowSides: Record<Side, Side> = {
|
|||
right: 'left',
|
||||
};
|
||||
|
||||
export default ({ content, children, ...props }: Props) => {
|
||||
const arrowEl = useRef<HTMLSpanElement>(null);
|
||||
export default ({ content, children, disabled = false, ...props }: Props) => {
|
||||
const arrowEl = useRef<HTMLDivElement>(null);
|
||||
const [ open, setOpen ] = useState(false);
|
||||
|
||||
const { x, y, reference, floating, middlewareData, strategy, context } = useFloating({
|
||||
|
@ -56,12 +57,16 @@ export default ({ content, children, ...props }: Props) => {
|
|||
const side = arrowSides[(props.placement || 'top').split('-')[0] as Side];
|
||||
const { x: ax, y: ay } = middlewareData.arrow || {};
|
||||
|
||||
if (disabled) {
|
||||
return children;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{cloneElement(children, getReferenceProps({ ref: reference, ...children.props }))}
|
||||
<AnimatePresence>
|
||||
{open &&
|
||||
<motion.span
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.85 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
|
@ -78,7 +83,7 @@ export default ({ content, children, ...props }: Props) => {
|
|||
>
|
||||
{content}
|
||||
{props.arrow &&
|
||||
<span
|
||||
<div
|
||||
ref={arrowEl}
|
||||
style={{
|
||||
transform: `translate(${Math.round(ax || 0)}px, ${Math.round(ay || 0)}px)`,
|
||||
|
@ -87,7 +92,7 @@ export default ({ content, children, ...props }: Props) => {
|
|||
className={'absolute top-0 left-0 bg-gray-900 w-3 h-3 rotate-45'}
|
||||
/>
|
||||
}
|
||||
</motion.span>
|
||||
</motion.div>
|
||||
}
|
||||
</AnimatePresence>
|
||||
</>
|
||||
|
|
|
@ -9,6 +9,7 @@ import TransitionRouter from '@/TransitionRouter';
|
|||
import SubNavigation from '@/components/elements/SubNavigation';
|
||||
import AccountSSHContainer from '@/components/dashboard/ssh/AccountSSHContainer';
|
||||
import { useLocation } from 'react-router';
|
||||
import ActivityLogContainer from '@/components/dashboard/activity/ActivityLogContainer';
|
||||
|
||||
export default () => {
|
||||
const location = useLocation();
|
||||
|
@ -22,6 +23,7 @@ export default () => {
|
|||
<NavLink to={'/account'} exact>Settings</NavLink>
|
||||
<NavLink to={'/account/api'}>API Credentials</NavLink>
|
||||
<NavLink to={'/account/ssh'}>SSH Keys</NavLink>
|
||||
<NavLink to={'/account/activity'}>Activity</NavLink>
|
||||
</div>
|
||||
</SubNavigation>
|
||||
}
|
||||
|
@ -39,6 +41,9 @@ export default () => {
|
|||
<Route path={'/account/ssh'} exact>
|
||||
<AccountSSHContainer/>
|
||||
</Route>
|
||||
<Route path={'/account/activity'} exact>
|
||||
<ActivityLogContainer />
|
||||
</Route>
|
||||
<Route path={'*'}>
|
||||
<NotFound/>
|
||||
</Route>
|
||||
|
|
Loading…
Reference in a new issue