Skip to content

Commit

Permalink
feat: Merge branch 'main' into feature/simulate
Browse files Browse the repository at this point in the history
  • Loading branch information
shahargl committed Jan 25, 2024
2 parents dae6b83 + 7ad31b2 commit c4886de
Show file tree
Hide file tree
Showing 31 changed files with 1,049 additions and 895 deletions.
17 changes: 6 additions & 11 deletions keep-ui/app/alerts/alert-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,17 @@ import { Button } from "@tremor/react";
import { getSession } from "next-auth/react";
import { getApiURL } from "utils/apiUrl";
import { AlertDto } from "./models";
import { useAlerts } from "utils/hooks/useAlerts";

interface Props {
selectedRowIds: string[];
onDelete: (
fingerprint: string,
lastReceived: Date,
restore?: boolean
) => void;
alerts: AlertDto[];
}

export default function AlertActions({
selectedRowIds,
onDelete: callDelete,
alerts,
}: Props) {
export default function AlertActions({ selectedRowIds, alerts }: Props) {
const { useAllAlerts } = useAlerts();
const { mutate } = useAllAlerts();

const onDelete = async () => {
const confirmed = confirm(
`Are you sure you want to delete ${selectedRowIds.length} alert(s)?`
Expand Down Expand Up @@ -50,7 +45,7 @@ export default function AlertActions({
body: JSON.stringify(body),
});
if (res.ok) {
callDelete(fingerprint, alert.lastReceived);
await mutate();
}
}
}
Expand Down
13 changes: 6 additions & 7 deletions keep-ui/app/alerts/alert-assignee.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { useState } from "react";
import { User } from "app/settings/models";
import { NameInitialsAvatar } from "react-name-initials-avatar";
import { useUsers } from "utils/hooks/useUsers";

export default function AlertAssignee({
assignee,
users,
}: {
interface Props {
assignee: string | undefined;
users: User[];
}) {
}

export default function AlertAssignee({ assignee }: Props) {
const [imageError, setImageError] = useState(false);
const { data: users = [] } = useUsers({ revalidateOnFocus: false });

if (!assignee || users.length < 1) {
return null;
Expand Down
10 changes: 4 additions & 6 deletions keep-ui/app/alerts/alert-columns-select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,8 @@ import { Column } from "@tanstack/react-table";

interface AlertColumnsSelectProps {
table: Table<AlertDto>;
columnOrder: string[];
presetName?: string;
isLoading: boolean;
setColumnVisibility: any;
}

export interface Option {
Expand Down Expand Up @@ -93,9 +91,7 @@ const filterFixedPositionColumns = (column: Column<AlertDto, unknown>) => {
export default function AlertColumnsSelect({
table,
presetName,
setColumnVisibility,
isLoading,
columnOrder,
}: AlertColumnsSelectProps) {
const columnsOptions = table
.getAllLeafColumns()
Expand All @@ -106,7 +102,9 @@ export default function AlertColumnsSelect({
.filter((col) => col.getIsVisible() && filterFixedPositionColumns(col))
.map(convertColumnToOption)
.sort(
(a, b) => columnOrder.indexOf(a.label) - columnOrder.indexOf(b.label)
(a, b) =>
table.getState().columnOrder.indexOf(a.label) -
table.getState().columnOrder.indexOf(b.label)
);

const onChange = (valueKeys: string[]) => {
Expand All @@ -124,7 +122,7 @@ export default function AlertColumnsSelect({
getHiddenColumnsLocalStorageKey(presetName),
JSON.stringify(hiddenColumns)
);
setColumnVisibility(hiddenColumns);
table.setColumnVisibility(hiddenColumns);
saveColumnsOrder(valueKeys);
};

Expand Down
43 changes: 23 additions & 20 deletions keep-ui/app/alerts/alert-extra-payload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,26 @@ export const getExtraPayloadNoKnownKeys = (alert: AlertDto) => {

interface Props {
alert: AlertDto;
isToggled: boolean;
setIsToggled: (newValue: boolean) => void;
}

export default function AlertExtraPayload({ alert }: Props) {
export default function AlertExtraPayload({
alert,
isToggled = false,
setIsToggled,
}: Props) {
const ref = useRef<HTMLDivElement>(null);
const [isExpanded, setIsExpanded] = useState(false);

function handleAccordionToggle() {
setIsExpanded(!isExpanded);
}
const onAccordionToggle = () => {
setIsToggled(!isToggled);
};

useEffect(() => {
if (isExpanded && ref.current) {
ref.current.scrollIntoView({ behavior: "smooth", block: "end" });
if (isToggled && ref.current) {
ref.current.scrollIntoView({ behavior: "smooth", block: "center" });
}
}, [isExpanded]);
}, [isToggled]);

const { extraPayload, extraPayloadLength } =
getExtraPayloadNoKnownKeys(alert);
Expand All @@ -39,17 +44,15 @@ export default function AlertExtraPayload({ alert }: Props) {
}

return (
<div>
<Accordion>
<AccordionHeader onClick={handleAccordionToggle}>
Extra Payload
</AccordionHeader>
<AccordionBody ref={ref}>
<pre className="overflow-y-scroll">
{JSON.stringify(extraPayload, null, 2)}
</pre>
</AccordionBody>
</Accordion>
</div>
<Accordion defaultOpen={isToggled}>
<AccordionHeader onClick={onAccordionToggle}>
Extra Payload
</AccordionHeader>
<AccordionBody ref={ref}>
<pre className="overflow-y-scroll">
{JSON.stringify(extraPayload, null, 2)}
</pre>
</AccordionBody>
</Accordion>
);
}
126 changes: 64 additions & 62 deletions keep-ui/app/alerts/alert-history.tsx
Original file line number Diff line number Diff line change
@@ -1,70 +1,63 @@
import { Dialog, Transition } from "@headlessui/react";
import { Fragment } from "react";
import { Fragment, useState } from "react";
import { AlertDto } from "./models";
import { AlertTable } from "./alert-table";
import { AlertTable, useAlertTableCols } from "./alert-table";
import { Button, Flex, Subtitle, Title, Divider } from "@tremor/react";
import { User } from "app/settings/models";
import { User as NextUser } from "next-auth";
import AlertHistoryCharts from "./alert-history-charts";
import useSWR from "swr";
import { getApiURL } from "utils/apiUrl";
import { fetcher } from "utils/fetcher";
import { useAlerts } from "utils/hooks/useAlerts";
import Loading from "app/loading";
import { PaginationState } from "@tanstack/react-table";
import { useRouter, useSearchParams } from "next/navigation";

interface Props {
isOpen: boolean;
closeModal: () => void;
selectedAlert: AlertDto | null;
users?: User[];
currentUser: NextUser;
accessToken?: string;
alerts: AlertDto[];
}

export function AlertHistory({
isOpen,
closeModal,
selectedAlert,
users = [],
currentUser,
accessToken,
}: Props) {
const apiUrl = getApiURL();
const historyUrl =
selectedAlert && accessToken
? `${apiUrl}/alerts/${selectedAlert.fingerprint}/history/?provider_id=${
selectedAlert.providerId
}&provider_type=${selectedAlert.source ? selectedAlert.source[0] : ""}`
: null;
const {
data: alerts,
error,
isLoading,
} = useSWR<AlertDto[]>(historyUrl, (url) => fetcher(url, accessToken!), {
revalidateOnFocus: false,
export function AlertHistory({ alerts }: Props) {
const [rowPagination, setRowPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});

if (!selectedAlert || isLoading) {
return <></>;
}
const router = useRouter();

if (!alerts || error) {
return <Loading />;
}
alerts.forEach(
(alert) => (alert.lastReceived = new Date(alert.lastReceived))
);
alerts.sort((a, b) => b.lastReceived.getTime() - a.lastReceived.getTime());
const lastReceivedData = alerts.map((alert) => alert.lastReceived);
const maxLastReceived: Date = new Date(
Math.max(...lastReceivedData.map((date) => date.getTime()))
const searchParams = useSearchParams();
const selectedAlert = alerts.find((alert) =>
searchParams ? searchParams.get("id") === alert.id : undefined
);
const minLastReceived: Date = new Date(
Math.min(...lastReceivedData.map((date) => date.getTime()))

const { useAlertHistory } = useAlerts();
const { data: alertHistory = [], isLoading } = useAlertHistory(
selectedAlert,
{
revalidateOnFocus: false,
}
);

const alertTableColumns = useAlertTableCols();

if (isLoading) {
return <Loading />;
}

const alertsHistoryWithDate = alertHistory.map((alert) => ({
...alert,
lastReceived: new Date(alert.lastReceived),
}));

const sortedHistoryAlert = alertsHistoryWithDate
.map((alert) => alert.lastReceived.getTime());

const maxLastReceived = new Date(Math.max(...sortedHistoryAlert));
const minLastReceived = new Date(Math.min(...sortedHistoryAlert));

return (
<Transition appear show={isOpen} as={Fragment}>
<Dialog as="div" className="relative z-50" onClose={closeModal}>
<Transition appear show={selectedAlert !== undefined} as={Fragment}>
<Dialog
as="div"
className="relative z-50"
onClose={() => router.replace("/alerts", { scroll: false })}
>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
Expand Down Expand Up @@ -93,8 +86,10 @@ export function AlertHistory({
>
<Flex alignItems="center" justifyContent="between">
<div>
<Title>History of: {alerts[0]?.name}</Title>
<Subtitle>Total alerts: {alerts.length}</Subtitle>
<Title>History of: {alertsHistoryWithDate[0]?.name}</Title>
<Subtitle>
Total alerts: {alertsHistoryWithDate.length}
</Subtitle>
<Subtitle>
First Occurence: {minLastReceived.toString()}
</Subtitle>
Expand All @@ -104,23 +99,30 @@ export function AlertHistory({
</div>
<Button
className="mt-2 bg-white border-gray-200 text-gray-500 hover:bg-gray-50 hover:border-gray-300"
onClick={closeModal}
onClick={() => router.replace("/alerts", { scroll: false })}
>
Close
</Button>
</Flex>
<Divider />
<AlertHistoryCharts
maxLastReceived={maxLastReceived}
minLastReceived={minLastReceived}
alerts={alerts}
/>
{selectedAlert && (
<AlertHistoryCharts
maxLastReceived={maxLastReceived}
minLastReceived={minLastReceived}
alerts={alertsHistoryWithDate}
/>
)}
<Divider />
<AlertTable
alerts={alerts}
users={users}
currentUser={currentUser}
alerts={alertsHistoryWithDate}
columns={alertTableColumns}
columnsToExclude={["description"]}
isMenuColDisplayed={false}
isRefreshAllowed={false}
rowPagination={{
state: rowPagination,
onChange: setRowPagination,
}}
/>
</Dialog.Panel>
</Transition.Child>
Expand Down
Loading

0 comments on commit c4886de

Please sign in to comment.