Skip to content

Commit c6e8b89

Browse files
committed
Add basic activity log view
1 parent d1da46c commit c6e8b89

File tree

9 files changed

+267
-17
lines changed

9 files changed

+267
-17
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import useUserSWRContentKey from '@/plugins/useUserSWRContentKey';
2+
import useSWR, { ConfigInterface, responseInterface } from 'swr';
3+
import { ActivityLog, Transformers } from '@definitions/user';
4+
import { AxiosError } from 'axios';
5+
import http, { PaginatedResult } from '@/api/http';
6+
import { toPaginatedSet } from '@definitions/helpers';
7+
8+
const useActivityLogs = (page = 1, config?: ConfigInterface<PaginatedResult<ActivityLog>, AxiosError>): responseInterface<PaginatedResult<ActivityLog>, AxiosError> => {
9+
const key = useUserSWRContentKey([ 'account', 'activity', page.toString() ]);
10+
11+
return useSWR<PaginatedResult<ActivityLog>>(key, async () => {
12+
const { data } = await http.get('/api/client/account/activity', {
13+
params: {
14+
include: [ 'actor' ],
15+
sort: '-timestamp',
16+
page: page,
17+
},
18+
});
19+
20+
return toPaginatedSet(data, Transformers.toActivityLog);
21+
}, { revalidateOnMount: false, ...(config || {}) });
22+
};
23+
24+
export { useActivityLogs };

resources/scripts/api/definitions/helpers.ts

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
1-
import { FractalResponseData, FractalResponseList } from '@/api/http';
1+
import {
2+
FractalPaginatedResponse,
3+
FractalResponseData,
4+
FractalResponseList,
5+
getPaginationSet,
6+
PaginatedResult,
7+
} from '@/api/http';
8+
import { Model } from '@definitions/index';
29

3-
type Transformer<T> = (callback: FractalResponseData) => T;
10+
type TransformerFunc<T> = (callback: FractalResponseData) => T;
411

512
const isList = (data: FractalResponseList | FractalResponseData): data is FractalResponseList => data.object === 'list';
613

7-
function transform<T, M>(data: null | undefined, transformer: Transformer<T>, missing?: M): M;
8-
function transform<T, M>(data: FractalResponseData | null | undefined, transformer: Transformer<T>, missing?: M): T | M;
9-
function transform<T, M>(data: FractalResponseList | null | undefined, transformer: Transformer<T>, missing?: M): T[] | M;
10-
function transform<T> (data: FractalResponseData | FractalResponseList | null | undefined, transformer: Transformer<T>, missing = undefined) {
14+
function transform<T, M>(data: null | undefined, transformer: TransformerFunc<T>, missing?: M): M;
15+
function transform<T, M>(data: FractalResponseData | null | undefined, transformer: TransformerFunc<T>, missing?: M): T | M;
16+
function transform<T, M>(data: FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc<T>, missing?: M): T[] | M;
17+
function transform<T> (data: FractalResponseData | FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc<T>, missing = undefined) {
1118
if (data === undefined || data === null) {
1219
return missing;
1320
}
@@ -23,4 +30,14 @@ function transform<T> (data: FractalResponseData | FractalResponseList | null |
2330
return transformer(data);
2431
}
2532

26-
export { transform };
33+
function toPaginatedSet<T extends TransformerFunc<Model>> (
34+
response: FractalPaginatedResponse,
35+
transformer: T,
36+
): PaginatedResult<ReturnType<T>> {
37+
return {
38+
items: transform(response, transformer) as ReturnType<T>[],
39+
pagination: getPaginationSet(response.meta.pagination),
40+
};
41+
}
42+
43+
export { transform, toPaginatedSet };

resources/scripts/api/definitions/user/transformers.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { FractalResponseData } from '@/api/http';
33
import { transform } from '@definitions/helpers';
44

55
export default class Transformers {
6-
static toSSHKey (data: Record<any, any>): Models.SSHKey {
6+
static toSSHKey = (data: Record<any, any>): Models.SSHKey => {
77
return {
88
name: data.name,
99
publicKey: data.public_key,
@@ -12,7 +12,7 @@ export default class Transformers {
1212
};
1313
}
1414

15-
static toUser ({ attributes }: FractalResponseData): Models.User {
15+
static toUser = ({ attributes }: FractalResponseData): Models.User => {
1616
return {
1717
uuid: attributes.uuid,
1818
username: attributes.username,
@@ -27,7 +27,7 @@ export default class Transformers {
2727
};
2828
}
2929

30-
static toActivityLog ({ attributes }: FractalResponseData): Models.ActivityLog {
30+
static toActivityLog = ({ attributes }: FractalResponseData): Models.ActivityLog => {
3131
const { actor } = attributes.relationships || {};
3232

3333
return {

resources/scripts/api/http.ts

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,26 @@ export interface FractalResponseList {
7777
data: FractalResponseData[];
7878
}
7979

80+
export interface FractalPaginatedResponse extends FractalResponseList {
81+
meta: {
82+
pagination: {
83+
total: number;
84+
count: number;
85+
/* eslint-disable camelcase */
86+
per_page: number;
87+
current_page: number;
88+
total_pages: number;
89+
/* eslint-enable camelcase */
90+
};
91+
}
92+
}
93+
8094
export interface PaginatedResult<T> {
8195
items: T[];
8296
pagination: PaginationDataSet;
8397
}
8498

85-
interface PaginationDataSet {
99+
export interface PaginationDataSet {
86100
total: number;
87101
count: number;
88102
perPage: number;
@@ -99,3 +113,43 @@ export function getPaginationSet (data: any): PaginationDataSet {
99113
totalPages: data.total_pages,
100114
};
101115
}
116+
117+
type QueryBuilderFilterValue = string | number | boolean | null;
118+
119+
export interface QueryBuilderParams<FilterKeys extends string = string, SortKeys extends string = string> {
120+
filters?: {
121+
[K in FilterKeys]?: QueryBuilderFilterValue | Readonly<QueryBuilderFilterValue[]>;
122+
};
123+
sorts?: {
124+
[K in SortKeys]?: -1 | 0 | 1 | 'asc' | 'desc' | null;
125+
};
126+
}
127+
128+
/**
129+
* Helper function that parses a data object provided and builds query parameters
130+
* for the Laravel Query Builder package automatically. This will apply sorts and
131+
* filters deterministically based on the provided values.
132+
*/
133+
export const withQueryBuilderParams = (data?: QueryBuilderParams): Record<string, unknown> => {
134+
if (!data) return {};
135+
136+
const filters = Object.keys(data.filters || {}).reduce((obj, key) => {
137+
const value = data.filters?.[key];
138+
139+
return !value || value === '' ? obj : { ...obj, [`filter[${key}]`]: value };
140+
}, {} as NonNullable<QueryBuilderParams['filters']>);
141+
142+
const sorts = Object.keys(data.sorts || {}).reduce((arr, key) => {
143+
const value = data.sorts?.[key];
144+
if (!value || ![ 'asc', 'desc', 1, -1 ].includes(value)) {
145+
return arr;
146+
}
147+
148+
return [ ...arr, (value === -1 || value === 'desc' ? '-' : '') + key ];
149+
}, [] as string[]);
150+
151+
return {
152+
...filters,
153+
sorts: !sorts.length ? undefined : sorts.join(','),
154+
};
155+
};
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import React, { useEffect, useState } from 'react';
2+
import { useActivityLogs } from '@/api/account/activity';
3+
import { useFlashKey } from '@/plugins/useFlash';
4+
import PageContentBlock from '@/components/elements/PageContentBlock';
5+
import FlashMessageRender from '@/components/FlashMessageRender';
6+
import { format, formatDistanceToNowStrict } from 'date-fns';
7+
import { Link } from 'react-router-dom';
8+
import PaginationFooter from '@/components/elements/table/PaginationFooter';
9+
import { UserIcon } from '@heroicons/react/outline';
10+
import Tooltip from '@/components/elements/tooltip/Tooltip';
11+
import { DesktopComputerIcon } from '@heroicons/react/solid';
12+
13+
export default () => {
14+
const { clearAndAddHttpError } = useFlashKey('account');
15+
const [ page, setPage ] = useState(1);
16+
const { data, isValidating: _, error } = useActivityLogs(page, {
17+
revalidateOnMount: true,
18+
revalidateOnFocus: false,
19+
});
20+
21+
useEffect(() => {
22+
clearAndAddHttpError(error);
23+
}, [ error ]);
24+
25+
return (
26+
<PageContentBlock title={'Account Activity Log'}>
27+
<FlashMessageRender byKey={'account'}/>
28+
<div className={'bg-gray-700'}>
29+
{data?.items.map((activity) => (
30+
<div
31+
key={`${activity.event}|${activity.timestamp.toString()}`}
32+
className={'grid grid-cols-10 py-4 border-b-2 border-gray-800 last:rounded-b last:border-0'}
33+
>
34+
<div className={'col-span-1 flex items-center justify-center select-none'}>
35+
<div className={'flex items-center w-8 h-8 rounded-full bg-gray-600 overflow-hidden'}>
36+
{activity.relationships.actor ?
37+
<img src={activity.relationships.actor.image} alt={'User avatar'}/>
38+
:
39+
<UserIcon className={'w-5 h-5 mx-auto'}/>
40+
}
41+
</div>
42+
</div>
43+
<div className={'col-span-9'}>
44+
<div className={'flex items-center text-gray-50'}>
45+
{activity.relationships.actor?.username || 'system'}
46+
<span className={'text-gray-400'}>&nbsp;&mdash;&nbsp;</span>
47+
<Link to={`#event=${activity.event}`}>
48+
{activity.event}
49+
</Link>
50+
{typeof activity.properties.useragent === 'string' &&
51+
<Tooltip content={activity.properties.useragent} placement={'top'}>
52+
<DesktopComputerIcon className={'ml-2 w-4 h-4 cursor-pointer'}/>
53+
</Tooltip>
54+
}
55+
</div>
56+
{/* <p className={'mt-1'}>{activity.description || JSON.stringify(activity.properties)}</p> */}
57+
<div className={'mt-1 flex items-center text-sm'}>
58+
<Link to={`#ip=${activity.ip}`}>{activity.ip}</Link>
59+
<span className={'text-gray-400'}>&nbsp;|&nbsp;</span>
60+
<Tooltip placement={'right'} content={format(activity.timestamp, 'MMM do, yyyy h:mma')}>
61+
<span>
62+
{formatDistanceToNowStrict(activity.timestamp, { addSuffix: true })}
63+
</span>
64+
</Tooltip>
65+
</div>
66+
</div>
67+
</div>
68+
))}
69+
</div>
70+
{data && <PaginationFooter pagination={data.pagination} onPageSelect={setPage}/>}
71+
</PageContentBlock>
72+
);
73+
};

resources/scripts/components/elements/button/style.module.css

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,18 @@
1919
@apply p-1;
2020
}
2121
}
22+
23+
&:disabled {
24+
@apply cursor-not-allowed;
25+
}
2226
}
2327

2428
.text {
25-
@apply bg-transparent focus:ring-neutral-300 focus:ring-opacity-50 hover:bg-neutral-500 active:bg-neutral-500;
29+
@apply text-gray-50 bg-transparent focus:ring-neutral-300 focus:ring-opacity-50 hover:bg-neutral-500 active:bg-neutral-500;
30+
31+
&:disabled {
32+
@apply hover:bg-transparent text-gray-300;
33+
}
2634
}
2735

2836
.danger {
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import React from 'react';
2+
import { PaginationDataSet } from '@/api/http';
3+
import classNames from 'classnames';
4+
import { Button } from '@/components/elements/button/index';
5+
import { ChevronDoubleLeftIcon, ChevronDoubleRightIcon } from '@heroicons/react/solid';
6+
7+
interface Props {
8+
className?: string;
9+
pagination: PaginationDataSet;
10+
onPageSelect: (page: number) => void;
11+
}
12+
13+
const PaginationFooter = ({ pagination, className, onPageSelect }: Props) => {
14+
const start = (pagination.currentPage - 1) * pagination.perPage;
15+
const end = ((pagination.currentPage - 1) * pagination.perPage) + pagination.count;
16+
17+
const { currentPage: current, totalPages: total } = pagination;
18+
19+
const pages = { previous: [] as number[], next: [] as number[] };
20+
for (let i = 1; i <= 2; i++) {
21+
if (current - i >= 1) {
22+
pages.previous.push(current - i);
23+
}
24+
if (current + i <= total) {
25+
pages.next.push(current + i);
26+
}
27+
}
28+
29+
return (
30+
<div className={classNames('flex items-center justify-between my-2', className)}>
31+
<p className={'text-sm text-neutral-500'}>
32+
Showing&nbsp;
33+
<span className={'font-semibold text-neutral-400'}>
34+
{Math.max(start, Math.min(pagination.total, 1))}
35+
</span>&nbsp;to&nbsp;
36+
<span className={'font-semibold text-neutral-400'}>{end}</span> of&nbsp;
37+
<span className={'font-semibold text-neutral-400'}>{pagination.total}</span> results.
38+
</p>
39+
{pagination.totalPages > 1 &&
40+
<div className={'flex space-x-1'}>
41+
<Button.Text small disabled={pages.previous.length !== 2} onClick={() => onPageSelect(1)}>
42+
<ChevronDoubleLeftIcon className={'w-3 h-3'}/>
43+
</Button.Text>
44+
{pages.previous.reverse().map((value) => (
45+
<Button.Text small key={`previous-${value}`} onClick={() => onPageSelect(value)}>
46+
{value}
47+
</Button.Text>
48+
))}
49+
<Button small disabled>{current}</Button>
50+
{pages.next.map((value) => (
51+
<Button.Text small key={`next-${value}`} onClick={() => onPageSelect(value)}>
52+
{value}
53+
</Button.Text>
54+
))}
55+
<Button.Text small disabled={pages.next.length !== 2} onClick={() => onPageSelect(total)}>
56+
<ChevronDoubleRightIcon className={'w-3 h-3'}/>
57+
</Button.Text>
58+
</div>
59+
}
60+
</div>
61+
);
62+
};
63+
64+
export default PaginationFooter;

resources/scripts/components/elements/tooltip/Tooltip.tsx

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { AnimatePresence, motion } from 'framer-motion';
1919

2020
interface Props {
2121
content: string | React.ReactChild;
22+
disabled?: boolean;
2223
arrow?: boolean;
2324
placement?: Placement;
2425
strategy?: Strategy;
@@ -33,8 +34,8 @@ const arrowSides: Record<Side, Side> = {
3334
right: 'left',
3435
};
3536

36-
export default ({ content, children, ...props }: Props) => {
37-
const arrowEl = useRef<HTMLSpanElement>(null);
37+
export default ({ content, children, disabled = false, ...props }: Props) => {
38+
const arrowEl = useRef<HTMLDivElement>(null);
3839
const [ open, setOpen ] = useState(false);
3940

4041
const { x, y, reference, floating, middlewareData, strategy, context } = useFloating({
@@ -56,12 +57,16 @@ export default ({ content, children, ...props }: Props) => {
5657
const side = arrowSides[(props.placement || 'top').split('-')[0] as Side];
5758
const { x: ax, y: ay } = middlewareData.arrow || {};
5859

60+
if (disabled) {
61+
return children;
62+
}
63+
5964
return (
6065
<>
6166
{cloneElement(children, getReferenceProps({ ref: reference, ...children.props }))}
6267
<AnimatePresence>
6368
{open &&
64-
<motion.span
69+
<motion.div
6570
initial={{ opacity: 0, scale: 0.85 }}
6671
animate={{ opacity: 1, scale: 1 }}
6772
exit={{ opacity: 0 }}
@@ -78,7 +83,7 @@ export default ({ content, children, ...props }: Props) => {
7883
>
7984
{content}
8085
{props.arrow &&
81-
<span
86+
<div
8287
ref={arrowEl}
8388
style={{
8489
transform: `translate(${Math.round(ax || 0)}px, ${Math.round(ay || 0)}px)`,
@@ -87,7 +92,7 @@ export default ({ content, children, ...props }: Props) => {
8792
className={'absolute top-0 left-0 bg-gray-900 w-3 h-3 rotate-45'}
8893
/>
8994
}
90-
</motion.span>
95+
</motion.div>
9196
}
9297
</AnimatePresence>
9398
</>

0 commit comments

Comments
 (0)