Skip to content

Commit

Permalink
refactor(CE): added all necessary files from EE
Browse files Browse the repository at this point in the history
  • Loading branch information
macintushar committed Sep 4, 2024
1 parent 014bc0c commit c840e86
Show file tree
Hide file tree
Showing 11 changed files with 361 additions and 45 deletions.
13 changes: 13 additions & 0 deletions ui/src/components/DataTable/RowsNotFound.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import EmptyState from '@/assets/images/empty-state-illustration.svg';
import { Box, Image, Text } from '@chakra-ui/react';

const RowsNotFound = () => (
<Box display='flex' w='fit-content' mx='auto' flexDirection='column' gap='20px' mt='20%'>
<Image src={EmptyState} alt='empty-table' w='175px' h='132px' />
<Text fontSize='xl' mx='auto' color='gray.600' fontWeight='semibold'>
No rows found
</Text>
</Box>
);

export default RowsNotFound;
7 changes: 4 additions & 3 deletions ui/src/components/DataTable/Table.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Table, Tbody, Td, Th, Thead, Tr } from '@chakra-ui/react';
import { flexRender, getCoreRowModel, useReactTable, ColumnDef } from '@tanstack/react-table';
import { flexRender, getCoreRowModel, useReactTable, ColumnDef, Row } from '@tanstack/react-table';
import { useState } from 'react';

type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[];
data: TData[];
onRowClick?: (row: Row<TData>) => void;
};

const DataTable = <TData, TValue>({ data, columns }: DataTableProps<TData, TValue>) => {
const DataTable = <TData, TValue>({ data, columns, onRowClick }: DataTableProps<TData, TValue>) => {
const [rowSelection, setRowSelection] = useState({});

const table = useReactTable({
Expand Down Expand Up @@ -46,7 +47,7 @@ const DataTable = <TData, TValue>({ data, columns }: DataTableProps<TData, TValu
<Tr
key={row.id}
_hover={{ backgroundColor: 'gray.200', cursor: 'pointer' }}
// onClick={() => onRowClick?.(row)}
onClick={() => onRowClick?.(row)}
backgroundColor='gray.100'
>
{row.getVisibleCells().map((cell) => (
Expand Down
31 changes: 31 additions & 0 deletions ui/src/components/TypeTag/TypeTag.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Tag, Text, Icon, Box } from '@chakra-ui/react';
import { IconType } from 'react-icons/lib';

type TypeTagProps = {
label: string;
leftIcon?: IconType;
};

const TypeTag = ({ label, leftIcon }: TypeTagProps) => (
<Tag
colorScheme='teal'
size='xs'
bgColor='gray.200'
paddingX={2}
fontWeight={600}
borderColor='gray.500'
borderWidth='1px'
borderStyle='solid'
height='22px'
borderRadius='4px'
>
<Box display='flex' gap='4px' alignItems='center'>
<Icon as={leftIcon} color='black.300' />
<Text size='xs' fontWeight='semibold' color='black.300'>
{label}
</Text>
</Box>
</Tag>
);

export default TypeTag;
1 change: 1 addition & 0 deletions ui/src/components/TypeTag/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './TypeTag';
97 changes: 97 additions & 0 deletions ui/src/hooks/syncs/useEditSync.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { editSync } from '@/services/syncs';
import { CreateSyncPayload, CreateSyncResponse } from '@/views/Activate/Syncs/types';
import { CustomToastStatus } from '@/components/Toast/index';
import useCustomToast from '@/hooks/useCustomToast';
import titleCase from '@/utils/TitleCase';
import { SYNCS_LIST_QUERY_KEY } from '@/views/Activate/Syncs/constants';
import { FinalizeSyncFormFields, FieldMap as FieldMapType } from '@/views/Activate/Syncs/types';

const useEditSync = (
configuration: FieldMapType[] | null,
setIsEditLoading: (isLoading: boolean) => void,
syncData?: CreateSyncResponse['attributes'],
destinationId?: string,
modelId?: string,
sourceId?: string,
) => {
const navigate = useNavigate();
const queryClient = useQueryClient();
const showToast = useCustomToast();
const [selectedSyncMode, setSelectedSyncMode] = useState('');
const [cursorField, setCursorField] = useState('');

const handleSubmit = async (data: FinalizeSyncFormFields, syncId: string) => {
setIsEditLoading(true);
try {
if (destinationId && modelId && sourceId && configuration) {
const payload: CreateSyncPayload = {
sync: {
configuration,
destination_id: destinationId,
model_id: modelId,
schedule_type: data.schedule_type,
source_id: sourceId,
stream_name: syncData?.stream_name as string,
sync_interval: data.sync_interval,
sync_interval_unit: data.sync_interval_unit,
sync_mode: selectedSyncMode,
cursor_field: cursorField,
cron_expression: data?.cron_expression,
},
};

const editSyncResponse = await editSync(payload, syncId);
if (editSyncResponse?.data?.attributes) {
showToast({
title: 'Sync updated successfully',
status: CustomToastStatus.Success,
duration: 3000,
isClosable: true,
position: 'bottom-right',
});

queryClient.removeQueries({
queryKey: SYNCS_LIST_QUERY_KEY,
});

navigate('/activate/syncs');
return;
} else {
editSyncResponse.errors?.forEach((error) => {
showToast({
duration: 5000,
isClosable: true,
position: 'bottom-right',
colorScheme: 'red',
status: CustomToastStatus.Warning,
title: titleCase(error.detail),
});
});
}
}
} catch {
showToast({
status: CustomToastStatus.Error,
title: 'Error!!',
description: 'Something went wrong while editing the sync',
position: 'bottom-right',
isClosable: true,
});
} finally {
setIsEditLoading(false);
}
};

return {
handleSubmit,
selectedSyncMode,
setSelectedSyncMode,
cursorField,
setCursorField,
};
};

export default useEditSync;
14 changes: 14 additions & 0 deletions ui/src/hooks/syncs/useGetSyncById.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useQuery } from '@tanstack/react-query';
import { getSyncById } from '@/services/syncs';

const useGetSyncById = (syncId: string, activeWorkspaceId: number) => {
return useQuery({
queryKey: ['sync', syncId, activeWorkspaceId],
queryFn: () => getSyncById(syncId),
refetchOnMount: true,
refetchOnWindowFocus: false,
enabled: !!syncId && activeWorkspaceId > 0,
});
};

export default useGetSyncById;
55 changes: 55 additions & 0 deletions ui/src/hooks/syncs/useManualSync.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useState } from 'react';
import { triggerManualSync, cancelManualSyncSchedule } from '@/services/syncs';
import { TriggerManualSyncPayload, CreateSyncResponse } from '@/views/Activate/Syncs/types';
import { APIRequestMethod } from '@/services/common';
import useApiMutation from '../useAPIMutation';

type TriggerSyncVariables = {
payload: TriggerManualSyncPayload;
method: APIRequestMethod;
};

const useManualSync = (syncId: string) => {
const [showCancelSync, setShowCancelSync] = useState(false);

const { isSubmitting, triggerMutation: triggerSync } = useApiMutation<
CreateSyncResponse,
TriggerSyncVariables
>({
mutationFn: ({ payload, method }: TriggerSyncVariables) => triggerManualSync(payload, method),
successMessage: 'Sync started successfully!',
errorMessage: 'Failed to start sync',
onSuccessCallback: () => {
setShowCancelSync(true); // Update the state to show the cancel option
},
});

const { triggerMutation: cancelSync } = useApiMutation<CreateSyncResponse, string>({
mutationFn: (id) => cancelManualSyncSchedule(id),
successMessage: 'Sync run cancelled successfully!',
errorMessage: 'Failed to cancel sync run',
onSuccessCallback: () => {
setShowCancelSync(false); // Update the state to hide the cancel option
},
});

const runSyncNow = async (method: APIRequestMethod) => {
if (syncId) {
const payload: TriggerManualSyncPayload = {
schedule_sync: {
sync_id: parseInt(syncId, 10),
},
};

if (method === 'post') {
await triggerSync({ payload, method });
} else {
await cancelSync(syncId);
}
}
};

return { isSubmitting, runSyncNow, showCancelSync, setShowCancelSync };
};

export default useManualSync;
14 changes: 14 additions & 0 deletions ui/src/hooks/syncs/useSyncRuns.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useQuery } from '@tanstack/react-query';
import { getSyncRunsBySyncId } from '@/services/syncs';

const useSyncRuns = (syncId: string, currentPage: number, activeWorkspaceId: number) => {
return useQuery({
queryKey: ['activate', 'sync-runs', syncId, 'page-' + currentPage, activeWorkspaceId],
queryFn: () => getSyncRunsBySyncId(syncId, currentPage.toString()),
refetchOnMount: true,
refetchOnWindowFocus: false,
enabled: activeWorkspaceId > 0,
});
};

export default useSyncRuns;
24 changes: 24 additions & 0 deletions ui/src/hooks/syncs/useTestSync.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { testSync } from '@/services/syncs';
import useApiMutation from '../useAPIMutation';
import { MessageResponse } from '@/services/authentication';

const useTestSync = (syncId: string) => {
const { isSubmitting, triggerMutation: triggerTestSync } = useApiMutation<
MessageResponse,
string
>({
mutationFn: (id: string) => testSync(id),
successMessage: 'Test sync triggered successfully!',
errorMessage: 'Failed to trigger test sync',
});

const runTestSync = async () => {
if (syncId) {
await triggerTestSync(syncId);
}
};

return { isSubmitting, runTestSync };
};

export default useTestSync;
53 changes: 11 additions & 42 deletions ui/src/views/Activate/Syncs/SyncRuns/SyncRuns.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,19 @@
import { useQuery } from '@tanstack/react-query';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { getSyncRunsBySyncId } from '@/services/syncs';
import { useMemo, useState, useEffect } from 'react';
import { SYNC_RUNS_COLUMNS } from '@/views/Activate/Syncs/constants';
import { Box } from '@chakra-ui/react';
import Loader from '@/components/Loader';
import Table from '@/components/Table';
import { TableItem } from '@/views/Activate/Syncs/SyncRuns/SyncRunTableItem';
import Pagination from '@/components/Pagination';
<<<<<<< HEAD
=======
import { useStore } from '@/stores';
import useProtectedNavigate from '@/enterprise/hooks/useProtectedNavigate';
import { UserActions } from '@/enterprise/types';
import useSyncRuns from '@/hooks/syncs/useSyncRuns';
import { SyncRunsColumns } from './SyncRunsColumns';
import DataTable from '@/components/DataTable';
import SyncRunEmptyImage from '@/assets/images/empty-state-illustration.svg';
import { Row } from '@tanstack/react-table';
import { SyncRunsResponse } from '../types';
>>>>>>> 966eb997 (fix(CE): fixed sync runs on click function)
import RowsNotFound from '@/components/DataTable/RowsNotFound';

const SyncRuns = () => {
const activeWorkspaceId = useStore((state) => state.workspaceId);

const { syncId } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
Expand All @@ -33,42 +25,15 @@ const SyncRuns = () => {
setSearchParams({ page: currentPage.toString() });
}, [currentPage, setSearchParams]);

const { data, isLoading } = useQuery({
queryKey: ['activate', 'sync-runs', syncId, 'page-' + currentPage],
queryFn: () => getSyncRunsBySyncId(syncId as string, currentPage.toString()),
refetchOnMount: true,
refetchOnWindowFocus: false,
});
const { data, isLoading } = useSyncRuns(syncId as string, currentPage, activeWorkspaceId);

<<<<<<< HEAD
const handleOnSyncClick = (row: Record<'id', string>) => {
navigate(`run/${row.id}`);
=======
const handleOnSyncClick = (row: Row<SyncRunsResponse>) => {
navigate({ to: `run/${row.original.id}`, location: 'sync_record', action: UserActions.Read });
>>>>>>> 966eb997 (fix(CE): fixed sync runs on click function)
navigate(`run/${row.original.id}`);
};

const syncList = data?.data;

const tableData = useMemo(() => {
const rows = (syncList ?? []).map((data) => {
return SYNC_RUNS_COLUMNS.reduce(
(acc, { key }) => ({
...acc,
[key]: <TableItem field={key} data={data} />,
id: data.id,
}),
{},
);
});

return {
columns: SYNC_RUNS_COLUMNS,
data: rows,
error: '',
};
}, [data]);
const allColumns = useMemo(() => [...SyncRunsColumns], [SyncRunsColumns]);

const handleNextPage = () => {
setCurrentPage((prevPage) => Math.min(prevPage + 1));
Expand All @@ -84,7 +49,11 @@ const SyncRuns = () => {
<Loader />
) : (
<Box>
<Table data={tableData} onRowClick={handleOnSyncClick} />
{data?.data?.length === 0 || !data?.data ? (
<RowsNotFound />
) : (
<DataTable data={data?.data} columns={allColumns} onRowClick={handleOnSyncClick} />
)}
<Box display='flex' flexDirection='row-reverse' pt='10px'>
<Pagination
currentPage={currentPage}
Expand Down
Loading

0 comments on commit c840e86

Please sign in to comment.