Skip to content

Commit

Permalink
feat(client): add ability to remove record in history compact list
Browse files Browse the repository at this point in the history
  • Loading branch information
Jozwiaczek committed Sep 8, 2021
1 parent 41b4ce4 commit d4b66c6
Show file tree
Hide file tree
Showing 11 changed files with 62 additions and 43 deletions.
4 changes: 2 additions & 2 deletions packages/client/src/elements/lists/CardList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useHistory } from 'react-router-dom';

import { routes } from '../../../constants';
import { EditIcon, FiltersIcon } from '../../../icons';
import { ApiList } from '../../../interfaces/api.types';
import { ApiListResponse } from '../../../interfaces/api.types';
import { ThemeType } from '../../../theme/Theme';
import { BaseFieldProps, BaseRecordField } from '../../fields/Fields.types';
import {
Expand All @@ -22,7 +22,7 @@ import {
import { CardListProps } from './CardList.types';

const CardList = ({ children, resource, actionButton }: CardListProps) => {
const queryResult = useQuery<ApiList<BaseRecordField>>(`/${resource}`);
const queryResult = useQuery<ApiListResponse<BaseRecordField>>(`/${resource}`);
const records = queryResult.data?.data;
const history = useHistory();
const { t } = useTranslation();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import styled, { css } from 'styled-components';

import { IconButton } from '../../buttons';
import Card from '../../Card';

export const StyledCard = styled(Card)<{ isBulkActionsOpen: boolean }>`
Expand All @@ -17,7 +16,6 @@ export const StyledCard = styled(Card)<{ isBulkActionsOpen: boolean }>`
overflow-y: auto;
padding: 0;
transition: border-radius 150ms;
width: 100%;
th {
Expand Down Expand Up @@ -139,11 +137,3 @@ export const BulkCancelWrapper = styled.div`
display: flex;
height: 100%;
`;

export const DeleteButton = styled(IconButton)`
border-radius: ${({ theme }) => theme.sizes.borderRadius};
height: 36px;
svg {
margin-right: 10px;
}
`;
28 changes: 13 additions & 15 deletions packages/client/src/elements/lists/DetailedList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { useMutation, useQuery } from 'react-query';
import { CSSProperties, useTheme } from 'styled-components';

import { useAxios, useSnackbar } from '../../../hooks';
import { ApiList } from '../../../interfaces/api.types';
import { getLabelFromSource } from '../../../utils';
import { ApiListResponse } from '../../../interfaces/api.types';
import { getLabelFromSource, onlyOnDevEnv } from '../../../utils';
import { CloseButton, DeleteHoverButton } from '../../buttons';
import { BaseFieldProps, BaseRecordField } from '../../fields/Fields.types';
import { Checkbox } from '../../inputs';
Expand Down Expand Up @@ -45,25 +45,23 @@ const DetailedList = ({
}: DetailedListProps) => {
const theme = useTheme();
const axios = useAxios();
const { data: queryResult, refetch } = useQuery<ApiList<BaseRecordField>>(`/${resource}`);
const { data: queryResult, refetch } = useQuery<ApiListResponse<BaseRecordField>>(`/${resource}`);
const [selectedRows, setSelectedRows] = useState<Array<string>>([]);
const [perPage, setPerPage] = useState<PerPage>(10);
const [currentPage, setCurrentPage] = useState<number>(1);
const snackbar = useSnackbar();
const { t } = useTranslation();

const removeMany = async (ids: Array<string>) => {
await axios
.post(`/${resource}/removeMany`, { ids })
.catch((err) => {
snackbar({ message: t('lists.detailedList.removeManyError'), severity: 'error' });
throw err;
})
.then(async () => {
await refetch();
});
try {
await axios.post(`/${resource}/removeMany`, { ids });
await refetch();
} catch (error) {
onlyOnDevEnv(() => console.error(error));
snackbar({ message: t('lists.general.removeError'), severity: 'error' });
}
};
const deleteMutation = useMutation(removeMany);
const removeManyMutation = useMutation(removeMany);

const totalRecords = useMemo((): number => {
if (queryResult) {
Expand Down Expand Up @@ -132,9 +130,9 @@ const DetailedList = ({
const isBulkActionsOpen = Boolean(selectedRows.length);

const removeSelectedItems = useCallback(() => {
deleteMutation.mutate(selectedRows);
removeManyMutation.mutate(selectedRows);
setSelectedRows([]);
}, [deleteMutation, selectedRows]);
}, [removeManyMutation, selectedRows]);

const getHeaderLabel = (source: string, label?: string, noTranslation?: boolean) => {
if (noTranslation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { SwipingRecord } from './HistoryCompactList.types';
const HistoryCompactList = () => {
const { t } = useTranslation();
const formatDate = useFormatDate();
const history = useHistoryCompactListData();
const { history, deleteRecord } = useHistoryCompactListData();
const isCurrentUserAdmin = useIsCurrentUserAdmin();
const getEventLabel = useHistoryEventLabel(isCurrentUserAdmin);
const [swipingRecord, setSwipingRecord] = useState<undefined | SwipingRecord>();
Expand Down Expand Up @@ -56,7 +56,7 @@ const HistoryCompactList = () => {
{
order: 1,
component: <TrashIcon />,
onPress: () => console.log('delete history record'),
onPress: () => deleteRecord.mutate(id),
background: 'red',
borderRadius: '12px 0 0 12px',
},
Expand Down
35 changes: 27 additions & 8 deletions packages/client/src/hooks/useHistoryCompactListData/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
import { useMutation, useQuery } from 'react-query';

import { ApiHistoryRecord, ApiList } from '../../interfaces/api.types';
import { onlyOnDevEnv } from '../../utils';
import { useAxios, useSnackbar } from '../index';
import useFormatDate from '../useFormatDate';
import {
ApiHistoryRecords,
ApiHistoryRecordsResponse,
UseHistoryCompactListData,
} from './useHistoryCompactListData.types';
import {
addHistoryRecordByLabelToMap,
getPastDate,
isSameDay,
} from './useHistoryCompactListData.utils';

const useHistoryCompactListData = (): Array<[string, Array<ApiHistoryRecord>]> => {
const useHistoryCompactListData = (): UseHistoryCompactListData => {
const formatDate = useFormatDate();
const { t } = useTranslation();
const { data } = useQuery<ApiList<ApiHistoryRecord>>('/history');
const axios = useAxios();
const showSnackbar = useSnackbar();
const { data, refetch } = useQuery<ApiHistoryRecordsResponse>('/history');
const history = data?.data;

const currentDate = new Date();
const removeRecord = async (id: string) => {
try {
await axios.delete(`/history/${id}`);
await refetch();
} catch (error) {
onlyOnDevEnv(() => console.error(error));
showSnackbar({ message: t('lists.general.removeError'), severity: 'error' });
}
};

const deleteRecordMutation = useMutation(removeRecord);

const currentDate = new Date();
if (!history?.length) {
return [];
return { history: [], deleteRecord: deleteRecordMutation };
}

const splitByDateHistoryMap = history.reduce((prev, historyRecord) => {
Expand All @@ -32,9 +51,9 @@ const useHistoryCompactListData = (): Array<[string, Array<ApiHistoryRecord>]> =

const formattedDate = formatDate(historyRecord.createdAt, { dateStyle: 'short' });
return addHistoryRecordByLabelToMap(formattedDate, prev, historyRecord);
}, new Map<string, Array<ApiHistoryRecord>>());
}, new Map<string, ApiHistoryRecords>());

return [...splitByDateHistoryMap];
return { history: [...splitByDateHistoryMap], deleteRecord: deleteRecordMutation };
};

export default useHistoryCompactListData;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { UseMutationResult } from 'react-query';

import { ApiHistoryRecord, ApiListResponse } from '../../interfaces/api.types';

type ApiHistoryRecords = Array<ApiHistoryRecord>;
type ApiHistoryRecordsResponse = ApiListResponse<ApiHistoryRecord>;

interface UseHistoryCompactListData {
history: Array<[string, ApiHistoryRecords]>;
deleteRecord: UseMutationResult<void, unknown, string, unknown>;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiHistoryRecord } from '../../interfaces/api.types';
import { ApiHistoryRecords } from './useHistoryCompactListData.types';

export const isSameDay = (d1: Date | string, d2: Date | string): boolean => {
const date1 = new Date(d1);
Expand All @@ -18,13 +19,13 @@ export const getPastDate = (pastDays: number) => {

export const addHistoryRecordByLabelToMap = (
label: string,
array: Map<string, Array<ApiHistoryRecord>>,
array: Map<string, ApiHistoryRecords>,
recordToAdd: ApiHistoryRecord,
) => {
const arrayCopy = array;

if (arrayCopy.has(label)) {
const todayHistoryRecords = arrayCopy.get(label) as Array<ApiHistoryRecord>;
const todayHistoryRecords = arrayCopy.get(label) as ApiHistoryRecords;
arrayCopy.set(label, [...todayHistoryRecords, recordToAdd]);
return arrayCopy;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/i18n/resources/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const en = {
lists: {
general: {
noData: 'No data',
removeError: 'Something went wrong during the delete operation. Try again later.',
},
detailedList: {
items: 'items',
Expand All @@ -47,7 +48,6 @@ const en = {
ofTotal: 'of',
next: 'next',
prev: 'prev',
removeManyError: 'Something went wrong during the delete operation!',
},
},
form: {
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/i18n/resources/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const pl: TranslationStructure = {
lists: {
general: {
noData: 'Brak danych',
removeError: 'Coś poszło nie tak podczas operacji usuwania. Spróbuj ponownie później.',
},
detailedList: {
items: 'wierszy',
Expand All @@ -49,7 +50,6 @@ const pl: TranslationStructure = {
ofTotal: 'z',
next: 'następny',
prev: 'poprzedni',
removeManyError: 'Coś poszło nie tak podczas operacji usuwania!',
},
},
form: {
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/interfaces/api.types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ interface ApiInvitation extends BaseApiResource {
updatedBy?: ApiUser;
}

interface ApiList<T> {
interface ApiListResponse<T> {
data: Array<T>;
total: number;
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const Wrapper = styled.div`
export const DesktopListContainer = styled.div`
height: 100%;
overflow-x: auto;
padding-top: 40px;
padding-top: 60px;
`;

export const MobileListContainer = styled.div`
Expand Down

0 comments on commit d4b66c6

Please sign in to comment.