fear: change requests to RTK query
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
This commit is contained in:
parent
ad1f948641
commit
a00aaff29d
@ -1,20 +1,52 @@
|
|||||||
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
|
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
|
||||||
import { getConfigValue } from '@brojs/cli';
|
import { getConfigValue } from '@brojs/cli';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
import { Master } from '../../models/api/master';
|
import { Master } from '../../models/api/master';
|
||||||
|
import { OrderProps } from '../../components/OrderItem/OrderItem';
|
||||||
|
|
||||||
import { extractBodyFromResponse } from './utils';
|
import { extractBodyFromResponse } from './utils';
|
||||||
|
|
||||||
|
export type UpdateMasterPayload = Required<Pick<Master, 'id'>> &
|
||||||
|
Partial<Omit<Master, 'id'>>;
|
||||||
|
|
||||||
|
type UpdateOrderProps = Required<Pick<OrderProps, 'id'>> &
|
||||||
|
Partial<Pick<OrderProps, 'status' | 'notes'>> & {
|
||||||
|
master?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export const api = createApi({
|
export const api = createApi({
|
||||||
reducerPath: 'api',
|
reducerPath: 'api',
|
||||||
baseQuery: fetchBaseQuery({ baseUrl: getConfigValue('dry-wash.api') }),
|
baseQuery: fetchBaseQuery({ baseUrl: getConfigValue('dry-wash.api') }),
|
||||||
tagTypes: ['Masters'],
|
tagTypes: ['Masters', 'Orders'],
|
||||||
endpoints: (builder) => ({
|
endpoints: (builder) => ({
|
||||||
getMasters: builder.query<Master[], void>({
|
getMasters: builder.query<Master[], void>({
|
||||||
query: () => ({ url: '/arm/masters' }),
|
query: () => ({ url: '/arm/masters' }),
|
||||||
transformResponse: extractBodyFromResponse<Master[]>,
|
transformResponse: extractBodyFromResponse<Master[]>,
|
||||||
providesTags: ['Masters'],
|
providesTags: ['Masters'],
|
||||||
}),
|
}),
|
||||||
|
updateOrders: builder.mutation<void, UpdateOrderProps>({
|
||||||
|
query: ({ id, status, notes, master }) => ({
|
||||||
|
url: `/order/${id}`,
|
||||||
|
method: 'PATCH',
|
||||||
|
body: { status, notes, master },
|
||||||
|
}),
|
||||||
|
invalidatesTags: ['Orders'],
|
||||||
|
}),
|
||||||
|
getOrders: builder.query<OrderProps[], { date: Date }>({
|
||||||
|
query: ({ date }) => {
|
||||||
|
const startDate = dayjs(date).startOf('day').toISOString();
|
||||||
|
const endDate = dayjs(date).endOf('day').toISOString();
|
||||||
|
return {
|
||||||
|
url: '/arm/orders',
|
||||||
|
method: 'POST',
|
||||||
|
body: { startDate, endDate },
|
||||||
|
};
|
||||||
|
},
|
||||||
|
transformResponse: extractBodyFromResponse<OrderProps[]>,
|
||||||
|
providesTags: ['Orders'],
|
||||||
|
}),
|
||||||
|
|
||||||
addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
|
addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
|
||||||
query: (master) => ({
|
query: (master) => ({
|
||||||
url: '/arm/masters',
|
url: '/arm/masters',
|
||||||
@ -23,5 +55,29 @@ export const api = createApi({
|
|||||||
}),
|
}),
|
||||||
invalidatesTags: ['Masters'],
|
invalidatesTags: ['Masters'],
|
||||||
}),
|
}),
|
||||||
|
deleteMaster: builder.mutation<void, { id: string }>({
|
||||||
|
query: ({ id }) => ({
|
||||||
|
url: `/arm/masters/${id}`,
|
||||||
|
method: 'DELETE',
|
||||||
|
}),
|
||||||
|
invalidatesTags: ['Masters'],
|
||||||
|
}),
|
||||||
|
updateMaster: builder.mutation<void, UpdateMasterPayload>({
|
||||||
|
query: ({ id, name, phone }) => ({
|
||||||
|
url: `/arm/masters/${id}`,
|
||||||
|
method: 'PATCH',
|
||||||
|
body: { name, phone },
|
||||||
|
}),
|
||||||
|
invalidatesTags: ['Masters'],
|
||||||
|
}),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const {
|
||||||
|
useGetMastersQuery,
|
||||||
|
useAddMasterMutation,
|
||||||
|
useDeleteMasterMutation,
|
||||||
|
useUpdateMasterMutation,
|
||||||
|
useGetOrdersQuery,
|
||||||
|
useUpdateOrdersMutation,
|
||||||
|
} = api;
|
||||||
|
@ -12,4 +12,4 @@ export const extractErrorMessageFromResponse = ({ data }: FetchBaseQueryError) =
|
|||||||
if (typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
|
if (typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
|
||||||
return data.message;
|
return data.message;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
139
src/api/arm.ts
139
src/api/arm.ts
@ -1,139 +0,0 @@
|
|||||||
import { getConfigValue } from '@brojs/cli';
|
|
||||||
import dayjs from 'dayjs';
|
|
||||||
|
|
||||||
enum ArmEndpoints {
|
|
||||||
ORDERS = '/arm/orders',
|
|
||||||
MASTERS = '/arm/masters',
|
|
||||||
}
|
|
||||||
|
|
||||||
const armService = () => {
|
|
||||||
const endpoint = getConfigValue('dry-wash.api');
|
|
||||||
|
|
||||||
const fetchOrders = async ({ date }: { date: Date }) => {
|
|
||||||
const startDate = dayjs(date).startOf('day').toISOString();
|
|
||||||
const endDate = dayjs(date).endOf('day').toISOString();
|
|
||||||
|
|
||||||
const response = await fetch(`${endpoint}${ArmEndpoints.ORDERS}`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ startDate, endDate }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch orders: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchMasters = async () => {
|
|
||||||
const response = await fetch(`${endpoint}${ArmEndpoints.MASTERS}`);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch masters: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const addMaster = async ({
|
|
||||||
name,
|
|
||||||
phone,
|
|
||||||
}: {
|
|
||||||
name: string;
|
|
||||||
phone: string;
|
|
||||||
}) => {
|
|
||||||
const response = await fetch(`${endpoint}${ArmEndpoints.MASTERS}`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ name, phone }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch masters: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const deleteMaster = async ({ id }: { id: string }) => {
|
|
||||||
const response = await fetch(`${endpoint}${ArmEndpoints.MASTERS}/${id}`, {
|
|
||||||
method: 'DELETE',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch masters: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateOrders = async ({
|
|
||||||
id,
|
|
||||||
status,
|
|
||||||
notes,
|
|
||||||
masterId,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
status?: string;
|
|
||||||
notes?: string;
|
|
||||||
masterId?: string;
|
|
||||||
}) => {
|
|
||||||
const body = JSON.stringify({ status, notes, masterId });
|
|
||||||
|
|
||||||
const response = await fetch(`${endpoint}/order/${id}`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch update masters: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateMaster = async ({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
phone,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
name?: string;
|
|
||||||
phone?: string;
|
|
||||||
}) => {
|
|
||||||
const body = JSON.stringify({ name, phone });
|
|
||||||
|
|
||||||
const response = await fetch(`${endpoint}${ArmEndpoints.MASTERS}/${id}`, {
|
|
||||||
method: 'PATCH',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch update masters: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
fetchOrders,
|
|
||||||
fetchMasters,
|
|
||||||
addMaster,
|
|
||||||
deleteMaster,
|
|
||||||
updateMaster,
|
|
||||||
updateOrders,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
export { armService, ArmEndpoints };
|
|
@ -1,4 +1,4 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Editable,
|
Editable,
|
||||||
EditableInput,
|
EditableInput,
|
||||||
@ -14,22 +14,18 @@ import {
|
|||||||
import { CheckIcon, CloseIcon, EditIcon } from '@chakra-ui/icons';
|
import { CheckIcon, CloseIcon, EditIcon } from '@chakra-ui/icons';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
import { useUpdateMasterMutation } from '../../__data__/service/api';
|
||||||
|
|
||||||
interface EditableWrapperProps {
|
interface EditableWrapperProps {
|
||||||
value: string;
|
value: string;
|
||||||
onSubmit: ({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
phone,
|
|
||||||
}: {
|
|
||||||
id: string;
|
|
||||||
name?: string;
|
|
||||||
phone?: string;
|
|
||||||
}) => Promise<unknown>;
|
|
||||||
as: 'phone' | 'name';
|
as: 'phone' | 'name';
|
||||||
id: string;
|
id: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
|
const EditableWrapper = ({ value, as, id }: EditableWrapperProps) => {
|
||||||
|
const [updateMaster, { isError, isSuccess, error }] =
|
||||||
|
useUpdateMasterMutation();
|
||||||
|
|
||||||
const { t } = useTranslation('~', {
|
const { t } = useTranslation('~', {
|
||||||
keyPrefix: 'dry-wash.arm.master.editable',
|
keyPrefix: 'dry-wash.arm.master.editable',
|
||||||
});
|
});
|
||||||
@ -40,11 +36,13 @@ const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
|
|||||||
const handleSubmit = async (newValue: string) => {
|
const handleSubmit = async (newValue: string) => {
|
||||||
if (currentValue === newValue) return;
|
if (currentValue === newValue) return;
|
||||||
|
|
||||||
try {
|
await updateMaster({ id, [as]: newValue });
|
||||||
await onSubmit({ id, [as]: newValue });
|
|
||||||
|
|
||||||
setCurrentValue(newValue);
|
setCurrentValue(newValue);
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isSuccess) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Успешно!',
|
title: 'Успешно!',
|
||||||
description: 'Данные обновлены.',
|
description: 'Данные обновлены.',
|
||||||
@ -53,7 +51,11 @@ const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
|
|||||||
isClosable: true,
|
isClosable: true,
|
||||||
position: 'top-right',
|
position: 'top-right',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
}
|
||||||
|
}, [isSuccess]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isError) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Ошибка!',
|
title: 'Ошибка!',
|
||||||
description: 'Не удалось обновить данные.',
|
description: 'Не удалось обновить данные.',
|
||||||
@ -64,7 +66,7 @@ const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
|
|||||||
});
|
});
|
||||||
console.error('Ошибка при обновлении данных:', error);
|
console.error('Ошибка при обновлении данных:', error);
|
||||||
}
|
}
|
||||||
};
|
}, [isError, error]);
|
||||||
|
|
||||||
function EditableControls() {
|
function EditableControls() {
|
||||||
const {
|
const {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Menu,
|
Menu,
|
||||||
MenuButton,
|
MenuButton,
|
||||||
@ -10,7 +10,7 @@ import {
|
|||||||
import { EditIcon } from '@chakra-ui/icons';
|
import { EditIcon } from '@chakra-ui/icons';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { armService } from '../../api/arm';
|
import { useDeleteMasterMutation } from '../../__data__/service/api';
|
||||||
|
|
||||||
interface MasterActionsMenu {
|
interface MasterActionsMenu {
|
||||||
id: string;
|
id: string;
|
||||||
@ -21,12 +21,17 @@ const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
|
|||||||
keyPrefix: 'dry-wash.arm.master.table.actionsMenu',
|
keyPrefix: 'dry-wash.arm.master.table.actionsMenu',
|
||||||
});
|
});
|
||||||
|
|
||||||
const { deleteMaster } = armService();
|
const [deleteMaster, { isSuccess, isError, error, isLoading }] =
|
||||||
|
useDeleteMasterMutation();
|
||||||
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
const handleClickDelete = async () => {
|
const handleClickDelete = async () => {
|
||||||
try {
|
await deleteMaster({ id });
|
||||||
await deleteMaster({ id });
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isSuccess) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Мастер удалён.',
|
title: 'Мастер удалён.',
|
||||||
description: `Мастер с ID "${id}" успешно удалён.`,
|
description: `Мастер с ID "${id}" успешно удалён.`,
|
||||||
@ -35,7 +40,11 @@ const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
|
|||||||
isClosable: true,
|
isClosable: true,
|
||||||
position: 'top-right',
|
position: 'top-right',
|
||||||
});
|
});
|
||||||
} catch (error) {
|
}
|
||||||
|
}, [isSuccess]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isError) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Ошибка удаления мастера.',
|
title: 'Ошибка удаления мастера.',
|
||||||
description: 'Не удалось удалить мастера. Попробуйте ещё раз.',
|
description: 'Не удалось удалить мастера. Попробуйте ещё раз.',
|
||||||
@ -46,13 +55,15 @@ const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
|
|||||||
});
|
});
|
||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
};
|
}, [isError]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Menu>
|
<Menu>
|
||||||
<MenuButton icon={<EditIcon />} as={IconButton} variant='outline' />
|
<MenuButton icon={<EditIcon />} as={IconButton} variant='outline' />
|
||||||
<MenuList>
|
<MenuList>
|
||||||
<MenuItem onClick={handleClickDelete}>{t('delete')}</MenuItem>
|
<MenuItem onClick={handleClickDelete} isDisabled={isLoading}>
|
||||||
|
{t('delete')}
|
||||||
|
</MenuItem>
|
||||||
</MenuList>
|
</MenuList>
|
||||||
</Menu>
|
</Menu>
|
||||||
);
|
);
|
||||||
|
@ -5,10 +5,8 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import MasterActionsMenu from '../MasterActionsMenu';
|
import MasterActionsMenu from '../MasterActionsMenu';
|
||||||
import { getTimeSlot } from '../../lib';
|
import { getTimeSlot } from '../../lib';
|
||||||
import EditableWrapper from '../Editable/Editable';
|
import EditableWrapper from '../Editable/Editable';
|
||||||
import { armService } from '../../api/arm';
|
|
||||||
|
|
||||||
const MasterItem = ({ name, phone, id, schedule }) => {
|
const MasterItem = ({ name, phone, id, schedule }) => {
|
||||||
const { updateMaster } = armService();
|
|
||||||
const { t } = useTranslation('~', {
|
const { t } = useTranslation('~', {
|
||||||
keyPrefix: 'dry-wash.arm.master',
|
keyPrefix: 'dry-wash.arm.master',
|
||||||
});
|
});
|
||||||
@ -16,12 +14,7 @@ const MasterItem = ({ name, phone, id, schedule }) => {
|
|||||||
return (
|
return (
|
||||||
<Tr>
|
<Tr>
|
||||||
<Td>
|
<Td>
|
||||||
<EditableWrapper
|
<EditableWrapper id={id} as={'name'} value={name} />
|
||||||
id={id}
|
|
||||||
as={'name'}
|
|
||||||
value={name}
|
|
||||||
onSubmit={updateMaster}
|
|
||||||
/>
|
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
{schedule?.length > 0 ? (
|
{schedule?.length > 0 ? (
|
||||||
@ -37,12 +30,7 @@ const MasterItem = ({ name, phone, id, schedule }) => {
|
|||||||
)}
|
)}
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
<EditableWrapper
|
<EditableWrapper id={id} as={'phone'} value={phone} />
|
||||||
id={id}
|
|
||||||
as={'phone'}
|
|
||||||
value={phone}
|
|
||||||
onSubmit={updateMaster}
|
|
||||||
/>
|
|
||||||
</Td>
|
</Td>
|
||||||
<Td>
|
<Td>
|
||||||
<MasterActionsMenu id={id} />
|
<MasterActionsMenu id={id} />
|
||||||
|
@ -19,7 +19,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
|
|
||||||
import MasterItem from '../MasterItem';
|
import MasterItem from '../MasterItem';
|
||||||
import MasterDrawer from '../MasterDrawer';
|
import MasterDrawer from '../MasterDrawer';
|
||||||
import { api } from '../../__data__/service/api';
|
import { useGetMastersQuery } from '../../__data__/service/api';
|
||||||
|
|
||||||
const TABLE_HEADERS = [
|
const TABLE_HEADERS = [
|
||||||
'name' as const,
|
'name' as const,
|
||||||
@ -35,12 +35,7 @@ const Masters = () => {
|
|||||||
keyPrefix: 'dry-wash.arm.master',
|
keyPrefix: 'dry-wash.arm.master',
|
||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const { data: masters, error, isLoading, isSuccess } = useGetMastersQuery();
|
||||||
data: masters,
|
|
||||||
error,
|
|
||||||
isLoading,
|
|
||||||
isSuccess,
|
|
||||||
} = api.useGetMastersQuery();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (error) {
|
if (error) {
|
||||||
|
@ -5,7 +5,7 @@ import dayjs from 'dayjs';
|
|||||||
|
|
||||||
import { getTimeSlot } from '../../lib';
|
import { getTimeSlot } from '../../lib';
|
||||||
import { Master } from '../../models/api/master';
|
import { Master } from '../../models/api/master';
|
||||||
import { armService } from '../../api/arm';
|
import { useUpdateOrdersMutation } from '../../__data__/service/api';
|
||||||
|
|
||||||
const statuses = [
|
const statuses = [
|
||||||
'pending' as const,
|
'pending' as const,
|
||||||
@ -54,8 +54,7 @@ const OrderItem = ({
|
|||||||
allMasters,
|
allMasters,
|
||||||
id,
|
id,
|
||||||
}: OrderProps) => {
|
}: OrderProps) => {
|
||||||
const { updateOrders } = armService();
|
const [updateOrders] = useUpdateOrdersMutation();
|
||||||
|
|
||||||
const { t } = useTranslation('~', {
|
const { t } = useTranslation('~', {
|
||||||
keyPrefix: 'dry-wash.arm.order',
|
keyPrefix: 'dry-wash.arm.order',
|
||||||
});
|
});
|
||||||
@ -72,16 +71,16 @@ const OrderItem = ({
|
|||||||
|
|
||||||
if (selectedMaster) {
|
if (selectedMaster) {
|
||||||
setMaster(masterName);
|
setMaster(masterName);
|
||||||
updateOrders({ id, masterId: selectedMaster.id });
|
updateOrders({ id, master: selectedMaster.id });
|
||||||
} else {
|
} else {
|
||||||
console.error('Master not found');
|
console.error('Master not found');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
|
const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
|
||||||
const status = e.target.value;
|
const status = e.target.value as OrderProps['status'];
|
||||||
updateOrders({ id, status });
|
updateOrders({ id, status });
|
||||||
setStatus(e.target.value as OrderProps['status']);
|
setStatus(status);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -17,9 +17,11 @@ import dayjs from 'dayjs';
|
|||||||
|
|
||||||
import OrderItem from '../OrderItem';
|
import OrderItem from '../OrderItem';
|
||||||
import { OrderProps } from '../OrderItem/OrderItem';
|
import { OrderProps } from '../OrderItem/OrderItem';
|
||||||
import { armService } from '../../api/arm';
|
|
||||||
import DateNavigator from '../DateNavigator';
|
import DateNavigator from '../DateNavigator';
|
||||||
import { Master } from '../../models/api/master';
|
import {
|
||||||
|
useGetMastersQuery,
|
||||||
|
useGetOrdersQuery,
|
||||||
|
} from '../../__data__/service/api';
|
||||||
|
|
||||||
const TABLE_HEADERS = [
|
const TABLE_HEADERS = [
|
||||||
'carNumber' as const,
|
'carNumber' as const,
|
||||||
@ -34,47 +36,41 @@ const Orders = () => {
|
|||||||
const { t } = useTranslation('~', {
|
const { t } = useTranslation('~', {
|
||||||
keyPrefix: 'dry-wash.arm.order',
|
keyPrefix: 'dry-wash.arm.order',
|
||||||
});
|
});
|
||||||
|
|
||||||
const { fetchOrders } = armService();
|
|
||||||
const { fetchMasters } = armService();
|
|
||||||
|
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
const [orders, setOrders] = useState<OrderProps[]>([]);
|
|
||||||
const [allMasters, setAllMasters] = useState<Master[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [currentDate, setCurrentDate] = useState(new Date());
|
const [currentDate, setCurrentDate] = useState(new Date());
|
||||||
|
const {
|
||||||
|
data: orders,
|
||||||
|
isLoading: isOrdersLoading,
|
||||||
|
isSuccess: isOrdersSuccess,
|
||||||
|
isError: isOrdersError,
|
||||||
|
error: ordersError,
|
||||||
|
} = useGetOrdersQuery({ date: currentDate });
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: masters,
|
||||||
|
isLoading: isMastersLoading,
|
||||||
|
isSuccess: isMastersSuccess,
|
||||||
|
isError: isMastersError,
|
||||||
|
error: mastersError,
|
||||||
|
} = useGetMastersQuery();
|
||||||
|
|
||||||
|
const isLoading = isOrdersLoading || isMastersLoading;
|
||||||
|
const isSuccess = isOrdersSuccess && isMastersSuccess;
|
||||||
|
const isError = isOrdersError || isMastersError;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const loadData = async () => {
|
if (isError) {
|
||||||
setLoading(true);
|
toast({
|
||||||
setError(null);
|
title: t('error.title'),
|
||||||
|
// description: errorMessage,
|
||||||
try {
|
status: 'error',
|
||||||
const [ordersData, mastersData] = await Promise.all([
|
duration: 5000,
|
||||||
fetchOrders({ date: currentDate }),
|
isClosable: true,
|
||||||
fetchMasters(),
|
position: 'bottom-right',
|
||||||
]);
|
});
|
||||||
|
}
|
||||||
setOrders(ordersData.body);
|
}, [isError, ordersError, mastersError, toast, t]);
|
||||||
setAllMasters(mastersData.body);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err.message);
|
|
||||||
toast({
|
|
||||||
title: t('error.title'),
|
|
||||||
status: 'error',
|
|
||||||
duration: 5000,
|
|
||||||
isClosable: true,
|
|
||||||
position: 'bottom-right',
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
loadData();
|
|
||||||
}, [currentDate, toast, t]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box p='8'>
|
<Box p='8'>
|
||||||
@ -103,25 +99,24 @@ const Orders = () => {
|
|||||||
</Tr>
|
</Tr>
|
||||||
</Thead>
|
</Thead>
|
||||||
<Tbody>
|
<Tbody>
|
||||||
{loading && (
|
{isLoading && (
|
||||||
<Tr>
|
<Tr>
|
||||||
<Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
|
<Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
|
||||||
<Spinner size='lg' />
|
<Spinner size='lg' />
|
||||||
</Td>
|
</Td>
|
||||||
</Tr>
|
</Tr>
|
||||||
)}
|
)}
|
||||||
{!loading && orders.length === 0 && !error && (
|
{isSuccess && orders.length === 0 && (
|
||||||
<Tr>
|
<Tr>
|
||||||
<Td colSpan={TABLE_HEADERS.length}>
|
<Td colSpan={TABLE_HEADERS.length}>
|
||||||
<Text>{t('table.empty')}</Text>
|
<Text>{t('table.empty')}</Text>
|
||||||
</Td>
|
</Td>
|
||||||
</Tr>
|
</Tr>
|
||||||
)}
|
)}
|
||||||
{!loading &&
|
{isSuccess &&
|
||||||
!error &&
|
|
||||||
orders.map((order, index) => (
|
orders.map((order, index) => (
|
||||||
<OrderItem
|
<OrderItem
|
||||||
allMasters={allMasters}
|
allMasters={masters}
|
||||||
key={index}
|
key={index}
|
||||||
{...order}
|
{...order}
|
||||||
status={order.status as OrderProps['status']}
|
status={order.status as OrderProps['status']}
|
||||||
|
@ -10,4 +10,4 @@ type ErrorResponse = {
|
|||||||
message: ErrorMessage;
|
message: ErrorMessage;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;
|
export type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;
|
||||||
|
@ -1,2 +1,2 @@
|
|||||||
export * from './common';
|
export * from './common';
|
||||||
export * from './order';
|
export * from './order';
|
||||||
|
@ -53,7 +53,7 @@ router.delete('/arm/masters/:id', (req, res) => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.patch('/orders/:id', (req, res) => {
|
router.patch('/order/:id', (req, res) => {
|
||||||
res
|
res
|
||||||
.status(/error/.test(STUBS.orders) ? 500 : 200)
|
.status(/error/.test(STUBS.orders) ? 500 : 200)
|
||||||
.send(
|
.send(
|
||||||
|
Loading…
Reference in New Issue
Block a user