Compare commits

..

No commits in common. "main" and "feature/playwright" have entirely different histories.

37 changed files with 590 additions and 734 deletions

View File

@ -1,9 +0,0 @@
import localeRu from '../locales/ru.json';
module.exports = {
useTranslation: (_, { keyPrefix }) => {
return {
t: (key: string) => localeRu[`${keyPrefix}.${key}`],
};
}
};

View File

@ -9,11 +9,9 @@ module.exports = {
clearMocks: true,
moduleNameMapper: {
'\\.(svg|webp)$': '<rootDir>/__mocks__/file',
'react-i18next': '<rootDir>/__mocks__/react-i18next',
},
testEnvironmentOptions: {
customExportConditions: [''],
},
testEnvironment: 'jest-fixed-jsdom',
testPathIgnorePatterns: ['/node_modules/', '<rootDir>/e2e'],
};

View File

@ -39,7 +39,6 @@
"dry-wash.order-create.car-body-select.options.sports-car" : "Sports-car",
"dry-wash.order-create.car-body-select.options.other": "Other",
"dry-wash.order-create.form.submit-button.label": "Submit",
"dry-wash.order-create.order-creation-title": "Creating order ...",
"dry-wash.order-create.create-order-query.success.title": "The order is successfully created",
"dry-wash.order-create.create-order-query.error.title": "Failed to create an order",
"dry-wash.order-view.title": "Your order",

View File

@ -25,16 +25,10 @@
"dry-wash.arm.master.table.header.phone": "Телефон",
"dry-wash.arm.master.table.header.actions": "Действия",
"dry-wash.arm.master.table.actionsMenu.delete": "Удалить мастера",
"dry-wash.arm.master.table.actionsMenu.toast.success": "Мастер удалён",
"dry-wash.arm.master.table.actionsMenu.toast.error.title": "Ошибка!",
"dry-wash.arm.master.table.actionsMenu.toast.error.description": "Не удалось удалить мастера. Попробуйте ещё раз.",
"dry-wash.arm.master.schedule.empty": "Свободен",
"dry-wash.arm.master.editable.aria.cancel": "Отменить изменения",
"dry-wash.arm.master.editable.aria.save": "Сохранить изменения",
"dry-wash.arm.master.editable.aria.edit": "Редактировать",
"dry-wash.arm.master.editable.toast.success": "Успешно!",
"dry-wash.arm.master.editable.toast.error.description": "Не удалось обновить данные",
"dry-wash.arm.master.editable.toast.error.title": "Ошибка!",
"dry-wash.arm.master.drawer.title": "Добавить нового мастера",
"dry-wash.arm.master.drawer.inputName.label": "ФИО",
"dry-wash.arm.master.drawer.inputName.placeholder": "Введите ФИО",
@ -94,7 +88,6 @@
"dry-wash.order-create.car-body-select.options.sports-car": "Спорткар",
"dry-wash.order-create.car-body-select.options.other": "Другой",
"dry-wash.order-create.form.submit-button.label": "Отправить",
"dry-wash.order-create.order-creation-title": "Создаем заказ ...",
"dry-wash.order-create.create-order-query.success.title": "Заказ успешно создан",
"dry-wash.order-create.create-order-query.error.title": "Не удалось создать заказ",
"dry-wash.order-view.title": "Ваш заказ",

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "dry-wash",
"version": "0.7.2",
"version": "0.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dry-wash",
"version": "0.7.2",
"version": "0.5.0",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.26.7",

View File

@ -1,6 +1,6 @@
{
"name": "dry-wash",
"version": "0.7.2",
"version": "0.5.0",
"description": "<a id=\"readme-top\"></a>",
"main": "./src/index.tsx",
"scripts": {

View File

@ -1,53 +1,20 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { getConfigValue } from '@brojs/cli';
import dayjs from 'dayjs';
import { Master, OrderArm } from '../../models/api';
import { Master } from '../../models/api/master';
import { extractBodyFromResponse } from './utils';
export type UpdateMasterPayload = Required<Pick<Master, 'id'>> &
Partial<Omit<Master, 'id'>>;
type UpdateOrderProps = Required<Pick<OrderArm, 'id'>> &
Partial<Pick<OrderArm, 'status' | 'notes'>> & {
master?: string;
};
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({
baseUrl: new URL(getConfigValue('dry-wash.api'), location.origin).href,
}),
tagTypes: ['Masters', 'Orders'],
baseQuery: fetchBaseQuery({ baseUrl: getConfigValue('dry-wash.api') }),
tagTypes: ['Masters'],
endpoints: (builder) => ({
getMasters: builder.query<Master[], void>({
query: () => ({ url: '/arm/masters' }),
transformResponse: extractBodyFromResponse<Master[]>,
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<OrderArm[], { 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<OrderArm[]>,
providesTags: ['Orders'],
}),
addMaster: builder.mutation<void, Pick<Master, 'name' | 'phone'>>({
query: (master) => ({
url: '/arm/masters',
@ -56,29 +23,5 @@ export const api = createApi({
}),
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;

View File

@ -1,23 +1,14 @@
import { GetOrder, CreateOrder } from "../../models/api";
import { GetOrder } from "../../models/api";
import { api } from "./api";
import { extractBodyFromResponse, extractErrorMessageFromResponse } from "./utils";
export const landingApi = api.injectEndpoints({
endpoints: ({ mutation, query }) => ({
endpoints: ({ query }) => ({
getOrder: query<GetOrder.Response, GetOrder.Params>({
query: ({ orderId }) => `/order/${orderId}`,
transformResponse: extractBodyFromResponse<GetOrder.Response>,
transformErrorResponse: extractErrorMessageFromResponse,
}),
createOrder: mutation<CreateOrder.Response, CreateOrder.Params>({
query: ({ body }) => ({
url: `/order/create`,
body,
method: 'POST'
}),
transformResponse: extractBodyFromResponse<CreateOrder.Response>,
transformErrorResponse: extractErrorMessageFromResponse,
}),
})
})
});

139
src/api/arm.ts Normal file
View File

@ -0,0 +1,139 @@
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
src/api/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './landing';

65
src/api/landing.tsx Normal file
View File

@ -0,0 +1,65 @@
import { getConfigValue } from '@brojs/cli';
import { useState } from 'react';
import { CreateOrder } from '../models/api';
import { QueryState, Trigger } from './types';
enum LandingEndpoints {
ORDER_CREATE = '/order/create',
}
const endpoint = getConfigValue('dry-wash.api');
const useCreateOrderMutation = <D extends CreateOrder.Response>(): [
Trigger<CreateOrder.Params, QueryState<D>['data']>,
QueryState<D>,
] => {
const [isLoading, setIsLoading] = useState<QueryState<D>['isLoading']>(false);
const [isSuccess, setIsSuccess] = useState<QueryState<D>['isSuccess']>();
const [data, setData] = useState<QueryState<D>['data']>();
const [isError, setIsError] = useState<QueryState<D>['isError']>();
const [error, setError] = useState<QueryState<D>['error']>();
const createOrder = async ({ body }: CreateOrder.Params) => {
setIsLoading(true);
try {
const response = await fetch(
`${endpoint}${LandingEndpoints.ORDER_CREATE}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
},
);
if (!response.ok) {
const errorResponseObject =
(await response.json()) as QueryState<D>['error'];
setIsError(true);
setError(errorResponseObject);
throw errorResponseObject;
}
const dataResponseObject =
(await response.json()) as QueryState<D>['data'];
setIsSuccess(true);
setData(dataResponseObject);
return dataResponseObject;
} catch (error) {
setIsError(true);
setError(error);
throw error;
} finally {
setIsLoading(false);
}
};
return [createOrder, { isLoading, isSuccess, data, isError, error }];
};
export { useCreateOrderMutation };

22
src/api/types.ts Normal file
View File

@ -0,0 +1,22 @@
export type QueryData<D> = {
success: true;
body: D;
};
export type QueryErrorData = {
success: false;
error: string;
};
export type QueryState<D> = {
isLoading: boolean;
isSuccess: boolean;
data: QueryData<D>;
isError: boolean;
error: {
status: number;
data: QueryErrorData;
};
};
export type Trigger<P, D> = (params: P) => Promise<D>;

View File

@ -1 +0,0 @@
export { default as OrderCreationAnimation } from './order-creation.json';

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useState } from 'react';
import {
Editable,
EditableInput,
@ -9,51 +9,63 @@ import {
useEditableControls,
ButtonGroup,
Stack,
useToast,
} from '@chakra-ui/react';
import { CheckIcon, CloseIcon, EditIcon } from '@chakra-ui/icons';
import { useTranslation } from 'react-i18next';
import { useUpdateMasterMutation } from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
interface EditableWrapperProps {
value: string;
fieldName: 'phone' | 'name';
onSubmit: ({
id,
name,
phone,
}: {
id: string;
name?: string;
phone?: string;
}) => Promise<unknown>;
as: 'phone' | 'name';
id: string;
}
const EditableWrapper = ({ value, fieldName, id }: EditableWrapperProps) => {
const [updateMaster, { isError, isSuccess, error }] =
useUpdateMasterMutation();
const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master.editable',
});
const showToast = useShowToast();
const toast = useToast();
const [currentValue, setCurrentValue] = useState<string>(value);
const handleSubmit = async (newValue: string) => {
if (currentValue === newValue) return;
await updateMaster({ id, [fieldName]: newValue });
try {
await onSubmit({ id, [as]: newValue });
setCurrentValue(newValue);
setCurrentValue(newValue);
toast({
title: 'Успешно!',
description: 'Данные обновлены.',
status: 'success',
duration: 2000,
isClosable: true,
position: 'top-right',
});
} catch (error) {
toast({
title: 'Ошибка!',
description: 'Не удалось обновить данные.',
status: 'error',
duration: 2000,
isClosable: true,
position: 'top-right',
});
console.error('Ошибка при обновлении данных:', error);
}
};
useEffect(() => {
if (isSuccess) {
showToast(t('toast.success'), 'success');
}
}, [isSuccess]);
useEffect(() => {
if (isError) {
showToast(t('toast.error.title'), 'error', t('toast.error.description'));
console.error(t('toast.error.description'), error);
}
}, [isError, error]);
function EditableControls() {
const {
isEditing,

View File

@ -1,16 +1,16 @@
import React, { useEffect } from 'react';
import React from 'react';
import {
Menu,
MenuButton,
MenuList,
MenuItem,
IconButton,
useToast,
} from '@chakra-ui/react';
import { EditIcon } from '@chakra-ui/icons';
import { useTranslation } from 'react-i18next';
import { useDeleteMasterMutation } from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
import { armService } from '../../api/arm';
interface MasterActionsMenu {
id: string;
@ -21,35 +21,38 @@ const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
keyPrefix: 'dry-wash.arm.master.table.actionsMenu',
});
const [deleteMaster, { isSuccess, isError, error, isLoading }] =
useDeleteMasterMutation();
const showToast = useShowToast();
const { deleteMaster } = armService();
const toast = useToast();
const handleClickDelete = async () => {
await deleteMaster({ id });
};
useEffect(() => {
if (isSuccess) {
showToast(t('toast.success'), 'success');
}
}, [isSuccess]);
useEffect(() => {
if (isError) {
showToast(t('toast.error.title'), 'error', t('toast.error.description'));
try {
await deleteMaster({ id });
toast({
title: 'Мастер удалён.',
description: `Мастер с ID "${id}" успешно удалён.`,
status: 'success',
duration: 5000,
isClosable: true,
position: 'top-right',
});
} catch (error) {
toast({
title: 'Ошибка удаления мастера.',
description: 'Не удалось удалить мастера. Попробуйте ещё раз.',
status: 'error',
duration: 5000,
isClosable: true,
position: 'top-right',
});
console.error(error);
}
}, [isError]);
};
return (
<Menu>
<MenuButton icon={<EditIcon />} as={IconButton} variant='outline' />
<MenuList>
<MenuItem onClick={handleClickDelete} isDisabled={isLoading}>
{t('delete')}
</MenuItem>
<MenuItem onClick={handleClickDelete}>{t('delete')}</MenuItem>
</MenuList>
</Menu>
);

View File

@ -12,6 +12,7 @@ import {
DrawerFooter,
DrawerHeader,
DrawerOverlay,
useToast,
InputGroup,
InputLeftElement,
FormErrorMessage,
@ -19,9 +20,9 @@ import {
import { useTranslation } from 'react-i18next';
import { PhoneIcon } from '@chakra-ui/icons';
import { useAddMasterMutation } from '../../__data__/service/api';
import { api } from '../../__data__/service/api';
import showToast from '../../helpers/showToast';
import { DrawerInputs } from '../../models/arm/form';
import useShowToast from '../../hooks/useShowToast';
interface MasterDrawerProps {
isOpen: boolean;
@ -49,19 +50,28 @@ const MasterDrawer = ({ isOpen, onClose }: MasterDrawerProps) => {
const isEmptyFields = trimMaster.name === '' || trimMaster.phone === '';
if (isEmptyFields) {
showToast(t('toast.error.base'), 'error', t('toast.error.empty-fields'));
showToast({
toast,
title: t('toast.error.base'),
description: t('toast.error.empty-fields'),
status: 'error',
});
return;
}
await addMaster(trimMaster);
};
const [addMaster, { error, isSuccess }] = useAddMasterMutation();
const showToast = useShowToast();
const [addMaster, { error, isSuccess }] = api.useAddMasterMutation();
const toast = useToast();
useEffect(() => {
if (isSuccess) {
showToast(t('toast.create-master'), 'success');
showToast({
toast,
title: t('toast.create-master'),
status: 'success',
});
reset();
onClose();
}
@ -69,11 +79,12 @@ const MasterDrawer = ({ isOpen, onClose }: MasterDrawerProps) => {
useEffect(() => {
if (error) {
showToast(
t('toast.error.create-master'),
'error',
t('toast.error.create-master-details'),
);
showToast({
toast,
title: t('toast.error.create-master'),
description: t('toast.error.create-master-details'),
status: 'error',
});
console.error(error);
}
}, [error]);

View File

@ -5,8 +5,10 @@ import { useTranslation } from 'react-i18next';
import MasterActionsMenu from '../MasterActionsMenu';
import { getTimeSlot } from '../../lib';
import EditableWrapper from '../Editable/Editable';
import { armService } from '../../api/arm';
const MasterItem = ({ name, phone, id, schedule }) => {
const { updateMaster } = armService();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master',
});
@ -14,7 +16,12 @@ const MasterItem = ({ name, phone, id, schedule }) => {
return (
<Tr>
<Td>
<EditableWrapper id={id} fieldName={'name'} value={name} />
<EditableWrapper
id={id}
as={'name'}
value={name}
onSubmit={updateMaster}
/>
</Td>
<Td>
{schedule?.length > 0 ? (
@ -30,7 +37,12 @@ const MasterItem = ({ name, phone, id, schedule }) => {
)}
</Td>
<Td>
<EditableWrapper id={id} fieldName={'phone'} value={phone} />
<EditableWrapper
id={id}
as={'phone'}
value={phone}
onSubmit={updateMaster}
/>
</Td>
<Td>
<MasterActionsMenu id={id} />

View File

@ -10,6 +10,7 @@ import {
Button,
useDisclosure,
Flex,
useToast,
Td,
Text,
Spinner,
@ -18,8 +19,7 @@ import { useTranslation } from 'react-i18next';
import MasterItem from '../MasterItem';
import MasterDrawer from '../MasterDrawer';
import { useGetMastersQuery } from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
import { api } from '../../__data__/service/api';
const TABLE_HEADERS = [
'name' as const,
@ -30,17 +30,26 @@ const TABLE_HEADERS = [
const Masters = () => {
const { isOpen, onOpen, onClose } = useDisclosure();
const showToast = useShowToast();
const toast = useToast();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master',
});
const { data: masters, error, isLoading, isSuccess } = useGetMastersQuery();
const {
data: masters,
error,
isLoading,
isSuccess,
} = api.useGetMastersQuery();
useEffect(() => {
if (error) {
showToast(t('error.title'), 'error');
toast({
title: t('error.title'),
status: 'error',
isClosable: true,
position: 'bottom-right',
});
}
}, [error]);

View File

@ -4,8 +4,35 @@ import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { getTimeSlot } from '../../lib';
import { useUpdateOrdersMutation } from '../../__data__/service/api';
import { OrderArm, Status, statuses } from '../../models/api';
import { Master } from '../../models/api/master';
import { armService } from '../../api/arm';
const statuses = [
'pending' as const,
'progress' as const,
'working' as const,
'canceled' as const,
'complete' as const,
];
type GetArrItemType<ArrType> =
ArrType extends Array<infer ItemType> ? ItemType : never;
export type OrderProps = {
carNumber?: string;
startWashTime?: string;
endWashTime?: string;
orderDate?: string;
status?: GetArrItemType<typeof statuses>;
phone?: string;
location?: string;
master: Master;
notes: '';
allMasters: Master[];
id: string;
};
type Status = (typeof statuses)[number];
const statusColors: Record<Status, string> = {
pending: 'yellow.100',
@ -26,8 +53,9 @@ const OrderItem = ({
master,
allMasters,
id,
}: OrderArm) => {
const [updateOrders] = useUpdateOrdersMutation();
}: OrderProps) => {
const { updateOrders } = armService();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.order',
});
@ -44,16 +72,16 @@ const OrderItem = ({
if (selectedMaster) {
setMaster(masterName);
updateOrders({ id, master: selectedMaster.id });
updateOrders({ id, masterId: selectedMaster.id });
} else {
console.error('Master not found');
}
};
const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
const status = e.target.value as OrderArm['status'];
const status = e.target.value;
updateOrders({ id, status });
setStatus(status);
setStatus(e.target.value as OrderProps['status']);
};
return (

View File

@ -10,18 +10,16 @@ import {
Spinner,
Text,
Td,
useToast,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import OrderItem from '../OrderItem';
import { OrderProps } from '../OrderItem/OrderItem';
import { armService } from '../../api/arm';
import DateNavigator from '../DateNavigator';
import {
useGetMastersQuery,
useGetOrdersQuery,
} from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
import { Master } from '../../models/api/master';
const TABLE_HEADERS = [
'carNumber' as const,
@ -36,34 +34,47 @@ const Orders = () => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.order',
});
const showToast = useShowToast();
const { fetchOrders } = armService();
const { fetchMasters } = armService();
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 {
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(() => {
if (isError) {
showToast(t('error.title'), 'error');
}
}, [isError, ordersError, mastersError, t]);
const loadData = async () => {
setLoading(true);
setError(null);
try {
const [ordersData, mastersData] = await Promise.all([
fetchOrders({ date: currentDate }),
fetchMasters(),
]);
setOrders(ordersData.body);
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 (
<Box p='8'>
@ -92,24 +103,25 @@ const Orders = () => {
</Tr>
</Thead>
<Tbody>
{isLoading && (
{loading && (
<Tr>
<Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
<Spinner size='lg' />
</Td>
</Tr>
)}
{isSuccess && orders.length === 0 && (
{!loading && orders.length === 0 && !error && (
<Tr>
<Td colSpan={TABLE_HEADERS.length}>
<Text>{t('table.empty')}</Text>
</Td>
</Tr>
)}
{isSuccess &&
{!loading &&
!error &&
orders.map((order, index) => (
<OrderItem
allMasters={masters}
allMasters={allMasters}
key={index}
{...order}
status={order.status as OrderProps['status']}

21
src/helpers/showToast.ts Normal file
View File

@ -0,0 +1,21 @@
import { UseToastOptions } from '@chakra-ui/react';
interface ShowToast {
toast: (options: UseToastOptions) => void;
title: string;
description?: string;
status: 'info' | 'warning' | 'success' | 'error';
}
const showToast = ({ toast, title, description, status }: ShowToast) => {
toast({
title,
description,
status,
duration: 5000,
isClosable: true,
position: 'top-right',
});
};
export default showToast;

View File

@ -1,28 +0,0 @@
import { useToast } from '@chakra-ui/react';
import { useCallback } from 'react';
const useShowToast = () => {
const toast = useToast();
const showToast = useCallback(
(
title: string,
status: 'info' | 'warning' | 'success' | 'error',
description?: string,
) => {
toast({
title,
description,
status,
duration: 5000,
isClosable: true,
position: 'top-right',
});
},
[toast],
);
return showToast;
};
export default useShowToast;

View File

@ -5,8 +5,6 @@ type SuccessResponse<Body> = {
export type ErrorMessage = string;
export const isErrorMessage = (error: unknown): error is ErrorMessage => typeof error === 'string';
type ErrorResponse = {
success: false;
message: ErrorMessage;

View File

@ -1,3 +1,2 @@
export * from './common';
export * from './order';
export * from './master';

View File

@ -1,49 +1,21 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { Order } from '../landing';
import { Order } from "../landing";
import { ErrorMessage } from './common';
import { Master } from './master';
import { ErrorMessage } from "./common";
export namespace GetOrder {
export type Response = Order.View;
export type Params = {
orderId: Order.Id;
orderId: Order.Id
};
export type Error = ErrorMessage;
}
export namespace CreateOrder {
export type Response = {
id: Order.Id;
id: Order.Id
};
export type Params = {
body: Order.Create;
body: Order.Create
};
}
type GetArrItemType<ArrType> =
ArrType extends Array<infer ItemType> ? ItemType : never;
export const statuses = [
'pending' as const,
'progress' as const,
'working' as const,
'canceled' as const,
'complete' as const,
];
export type Status = (typeof statuses)[number];
export type OrderArm = {
carNumber?: string;
startWashTime?: string;
endWashTime?: string;
orderDate?: string;
status?: GetArrItemType<typeof statuses>;
phone?: string;
location?: string;
master: Master;
notes: '';
allMasters: Master[];
id: string;
};

View File

@ -6,58 +6,58 @@ exports[`Arm Page render 1`] = `
class="css-1yeiifd"
>
<div
class="css-13owfwq"
class="css-1fp6kaj"
>
<h2
class="chakra-heading css-173d1bl"
class="chakra-heading css-9q1d0h"
>
Сухой мастер
title
</h2>
<div
class="chakra-stack css-1cggwyz"
class="chakra-stack css-1oen434"
>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
<a
class="chakra-button css-1kg18wp"
class="chakra-button css-uxt1e8"
href="/auth/login"
>
Заказы
orders
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
<a
class="chakra-button css-1kg18wp"
class="chakra-button css-uxt1e8"
href="/auth/login"
>
Мастера
master
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
</div>
</div>
<div
class="css-jiwy8d"
class="css-sy55x5"
>
<div
class="css-1glkkdp"
class="css-hpgf8j"
>
<h2
class="chakra-heading css-1xer3cv"
class="chakra-heading css-r7q7qr"
>
Заказы
title
</h2>
<div
class="css-1u3smh"
class="css-1me9tx"
>
<button
class="chakra-button css-ez23ye"
class="chakra-button css-4xx2wk"
type="button"
>
<svg
@ -72,12 +72,12 @@ exports[`Arm Page render 1`] = `
</svg>
</button>
<p
class="chakra-text css-52ukzg"
class="chakra-text css-1bntq7d"
>
09.02.2025
2/2/2025
</p>
<button
class="chakra-button css-ez23ye"
class="chakra-button css-4xx2wk"
type="button"
>
<svg
@ -93,7 +93,7 @@ exports[`Arm Page render 1`] = `
</button>
</div>
<table
class="chakra-table css-5605sr"
class="chakra-table css-0"
>
<thead
class="css-0"
@ -102,34 +102,34 @@ exports[`Arm Page render 1`] = `
class="css-0"
>
<th
class="css-1szkfps"
class="css-0"
>
Номер машины
table.header.carNumber
</th>
<th
class="css-1szkfps"
class="css-0"
>
Дата заказа
table.header.orderDate
</th>
<th
class="css-1szkfps"
class="css-0"
>
Статус
table.header.status
</th>
<th
class="css-1szkfps"
class="css-0"
>
Мастер
table.header.masters
</th>
<th
class="css-1szkfps"
class="css-0"
>
Телефон
table.header.telephone
</th>
<th
class="css-1szkfps"
class="css-0"
>
Расположение
table.header.location
</th>
</tr>
</thead>
@ -140,11 +140,11 @@ exports[`Arm Page render 1`] = `
class="css-0"
>
<td
class="css-1v9gmks"
class="css-12rlgei"
colspan="6"
>
<div
class="chakra-spinner css-1j92705"
class="chakra-spinner css-1y7joxr"
>
<span
class="css-8b45rq"
@ -159,10 +159,6 @@ exports[`Arm Page render 1`] = `
</div>
</div>
</div>
<span
hidden=""
id="__chakra_env"
/>
</div>
`;
@ -172,58 +168,58 @@ exports[`Arm Page render 2`] = `
class="css-1yeiifd"
>
<div
class="css-13owfwq"
class="css-1fp6kaj"
>
<h2
class="chakra-heading css-173d1bl"
class="chakra-heading css-9q1d0h"
>
Сухой мастер
title
</h2>
<div
class="chakra-stack css-1cggwyz"
class="chakra-stack css-1oen434"
>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
<a
class="chakra-button css-1kg18wp"
class="chakra-button css-uxt1e8"
href="/auth/login"
>
Заказы
orders
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
<a
class="chakra-button css-1kg18wp"
class="chakra-button css-uxt1e8"
href="/auth/login"
>
Мастера
master
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
class="chakra-divider css-1upb9tn"
/>
</div>
</div>
<div
class="css-jiwy8d"
class="css-sy55x5"
>
<div
class="css-1glkkdp"
class="css-hpgf8j"
>
<h2
class="chakra-heading css-1xer3cv"
class="chakra-heading css-r7q7qr"
>
Заказы
title
</h2>
<div
class="css-1u3smh"
class="css-1me9tx"
>
<button
class="chakra-button css-ez23ye"
class="chakra-button css-4xx2wk"
type="button"
>
<svg
@ -238,12 +234,12 @@ exports[`Arm Page render 2`] = `
</svg>
</button>
<p
class="chakra-text css-52ukzg"
class="chakra-text css-1bntq7d"
>
09.02.2025
2/2/2025
</p>
<button
class="chakra-button css-ez23ye"
class="chakra-button css-4xx2wk"
type="button"
>
<svg
@ -259,7 +255,7 @@ exports[`Arm Page render 2`] = `
</button>
</div>
<table
class="chakra-table css-5605sr"
class="chakra-table css-0"
>
<thead
class="css-0"
@ -268,34 +264,34 @@ exports[`Arm Page render 2`] = `
class="css-0"
>
<th
class="css-1szkfps"
class="css-0"
>
Номер машины
table.header.carNumber
</th>
<th
class="css-1szkfps"
class="css-0"
>
Дата заказа
table.header.orderDate
</th>
<th
class="css-1szkfps"
class="css-0"
>
Статус
table.header.status
</th>
<th
class="css-1szkfps"
class="css-0"
>
Мастер
table.header.masters
</th>
<th
class="css-1szkfps"
class="css-0"
>
Телефон
table.header.telephone
</th>
<th
class="css-1szkfps"
class="css-0"
>
Расположение
table.header.location
</th>
</tr>
</thead>
@ -306,288 +302,24 @@ exports[`Arm Page render 2`] = `
class="css-0"
>
<td
class="css-zgoslk"
>
A123BC
</td>
<td
class="css-zgoslk"
>
24.11.2024
<br />
</td>
<td
class="css-zgoslk"
class="css-12rlgei"
colspan="6"
>
<div
class="chakra-select__wrapper css-42b2qy"
class="chakra-spinner css-1y7joxr"
>
<select
class="chakra-select css-11j19cx"
<span
class="css-8b45rq"
>
<option
value=""
>
Выберите статус
</option>
<option
value="pending"
>
В ожидании
</option>
<option
value="progress"
>
Выполняется
</option>
<option
value="working"
>
В работе
</option>
<option
value="canceled"
>
Отменено
</option>
<option
value="complete"
>
Завершено
</option>
</select>
<div
class="chakra-select__icon-wrapper css-iohxn1"
>
<svg
aria-hidden="true"
class="chakra-select__icon"
focusable="false"
role="presentation"
style="width: 1em; height: 1em; color: currentColor;"
viewBox="0 0 24 24"
>
<path
d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"
fill="currentColor"
/>
</svg>
</div>
Loading...
</span>
</div>
</td>
<td
class="css-zgoslk"
>
<div
class="chakra-select__wrapper css-42b2qy"
>
<select
class="chakra-select css-161pkch"
>
<option
value=""
>
Выберите мастера
</option>
<option
value="Иван Иванов"
>
Иван Иванов
</option>
<option
value="Олег Макаров"
>
Олег Макаров
</option>
<option
value="Иван Галкин"
>
Иван Галкин
</option>
</select>
<div
class="chakra-select__icon-wrapper css-iohxn1"
>
<svg
aria-hidden="true"
class="chakra-select__icon"
focusable="false"
role="presentation"
style="width: 1em; height: 1em; color: currentColor;"
viewBox="0 0 24 24"
>
<path
d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"
fill="currentColor"
/>
</svg>
</div>
</div>
</td>
<td
class="css-zgoslk"
>
<a
class="chakra-link css-spn4bz"
href="tel:"
>
79001234563
</a>
</td>
<td
class="css-zgoslk"
>
Казань, ул. Баумана, 1
</td>
</tr>
<tr
class="css-0"
>
<td
class="css-zgoslk"
>
A245BC
</td>
<td
class="css-zgoslk"
>
24.11.2024
<br />
</td>
<td
class="css-zgoslk"
>
<div
class="chakra-select__wrapper css-42b2qy"
>
<select
class="chakra-select css-lvra4l"
>
<option
value=""
>
Выберите статус
</option>
<option
value="pending"
>
В ожидании
</option>
<option
value="progress"
>
Выполняется
</option>
<option
value="working"
>
В работе
</option>
<option
value="canceled"
>
Отменено
</option>
<option
value="complete"
>
Завершено
</option>
</select>
<div
class="chakra-select__icon-wrapper css-iohxn1"
>
<svg
aria-hidden="true"
class="chakra-select__icon"
focusable="false"
role="presentation"
style="width: 1em; height: 1em; color: currentColor;"
viewBox="0 0 24 24"
>
<path
d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"
fill="currentColor"
/>
</svg>
</div>
</div>
</td>
<td
class="css-zgoslk"
>
<div
class="chakra-select__wrapper css-42b2qy"
>
<select
class="chakra-select css-161pkch"
>
<option
value=""
>
Выберите мастера
</option>
<option
value="Иван Иванов"
>
Иван Иванов
</option>
<option
value="Олег Макаров"
>
Олег Макаров
</option>
<option
value="Иван Галкин"
>
Иван Галкин
</option>
</select>
<div
class="chakra-select__icon-wrapper css-iohxn1"
>
<svg
aria-hidden="true"
class="chakra-select__icon"
focusable="false"
role="presentation"
style="width: 1em; height: 1em; color: currentColor;"
viewBox="0 0 24 24"
>
<path
d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"
fill="currentColor"
/>
</svg>
</div>
</div>
</td>
<td
class="css-zgoslk"
>
<a
class="chakra-link css-spn4bz"
href="tel:"
>
79001234567
</a>
</td>
<td
class="css-zgoslk"
>
Казань, ул. Баумана, 43
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<span
hidden=""
id="__chakra_env"
/>
</div>
`;

View File

@ -12,11 +12,7 @@ import { render, screen, waitFor } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { BrowserRouter } from 'react-router-dom';
import { ChakraProvider, theme as chakraTheme } from '@chakra-ui/react';
import { Provider } from 'react-redux';
import ErrorBoundary from '../../components/ErrorBoundary';
import { store } from '../../__data__/store';
import Page from '../arm';
const server = setupServer(
@ -91,6 +87,17 @@ const server = setupServer(
}),
);
jest.mock('react-i18next', () => {
return {
useTranslation: () => {
return {
t: (key: never) => `${key}`,
i18n: {},
};
},
};
});
jest.mock('@brojs/cli', () => {
return {
getNavigationValue: () => '/auth/login',
@ -109,15 +116,9 @@ describe('Arm Page', () => {
});
const { container } = render(
<Provider store={store}>
<ChakraProvider theme={chakraTheme}>
<ErrorBoundary>
<BrowserRouter>
<Page mockUser={{ name: 'ilnaz' }} />
</BrowserRouter>
</ErrorBoundary>
</ChakraProvider>
</Provider>,
<BrowserRouter>
<Page mockUser={{ name: 'ilnaz' }} />
</BrowserRouter>,
);
expect(container).toMatchSnapshot();

View File

@ -1,13 +1,7 @@
import dayjs from "dayjs";
import { useToast } from "@chakra-ui/react";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Order } from "../../models/landing";
import { OrderFormValues } from "../../components/order-form";
import { isErrorMessage } from "../../models/api";
import { URLs } from '../../__data__/urls';
const removeAllSpaces = (str: string) => str.replace(/\s+/g, '');
@ -33,39 +27,3 @@ export const formatFormValues = ({ phone, carNumber, carBody, carColor, carLocat
}
};
};
export const useHandleCreateOrderMutationResponse = (query: {
isSuccess: boolean;
data?: {
id: Parameters<typeof URLs.orderView.getUrl>[0];
};
isError: boolean;
error?: unknown;
}) => {
const toast = useToast();
const navigate = useNavigate();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.create-order-query',
});
useEffect(() => {
if (query.isError) {
toast({
status: 'error',
title: t('error.title'),
description: isErrorMessage(query.error) ? query.error : undefined,
});
}
}, [query.isError]);
useEffect(() => {
if (query.isSuccess) {
const orderId = query.data.id;
navigate({ pathname: URLs.orderView.getUrl(orderId) });
toast({
status: 'success',
title: t('success.title'),
});
}
}, [query.isSuccess]);
};

View File

@ -1,29 +1,41 @@
import React, { FC } from 'react';
import { useTranslation } from 'react-i18next';
import { Container, Heading, VStack } from '@chakra-ui/react';
import { Player as LottiePlayer } from '@lottiefiles/react-lottie-player';
import { Container, Heading, useToast, VStack } from '@chakra-ui/react';
import { useNavigate } from 'react-router-dom';
import { withLandingThemeProvider } from '../../containers';
import { OrderForm, OrderFormProps } from '../../components/order-form';
import { landingApi } from '../../__data__/service/landing.api';
import { OrderCreationAnimation } from '../../assets/animation';
import { useCreateOrderMutation } from '../../api';
import { URLs } from '../../__data__/urls';
import {
formatFormValues,
useHandleCreateOrderMutationResponse,
} from './helper';
import { formatFormValues } from './helper';
const Page: FC = () => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create',
});
const [createOrder, createOrderMutation] =
landingApi.useCreateOrderMutation();
useHandleCreateOrderMutationResponse(createOrderMutation);
const [createOrder, createOrderMutation] = useCreateOrderMutation();
const toast = useToast();
const navigate = useNavigate();
const onOrderFormSubmit: OrderFormProps['onSubmit'] = (values) => {
createOrder({ body: formatFormValues(values) });
createOrder({ body: formatFormValues(values) })
.then(({ body: { id: orderId } }) => {
navigate({ pathname: URLs.orderView.getUrl(orderId) });
toast({
status: 'success',
title: t('create-order-query.success.title'),
});
})
.catch(({ error: errorMessage }) => {
toast({
status: 'error',
title: t('create-order-query.error.title'),
description: errorMessage,
});
});
};
return (
@ -36,24 +48,13 @@ const Page: FC = () => {
centerContent
>
<VStack w='full' h='full' alignItems='stretch' flexGrow={1}>
{createOrderMutation.isUninitialized ? (
<>
<Heading textAlign='center' mt={4}>
{t('title')}
</Heading>
<OrderForm
onSubmit={onOrderFormSubmit}
loading={createOrderMutation.isLoading}
/>
</>
) : (
<>
<LottiePlayer autoplay loop src={OrderCreationAnimation} />
<Heading textAlign='center' mt={4}>
{t('order-creation-title')}
</Heading>
</>
)}
<Heading textAlign='center' mt={4}>
{t('title')}
</Heading>
<OrderForm
onSubmit={onOrderFormSubmit}
loading={createOrderMutation.isLoading}
/>
</VStack>
</Container>
);

View File

@ -19,7 +19,7 @@ import {
import { OrderDetails } from '../../components/order-view';
import { Order } from '../../models/landing';
import { landingApi } from '../../__data__/service/landing.api';
import { isErrorMessage } from '../../models/api';
import { ErrorMessage } from '../../models/api';
import { FEATURE } from '../../__data__/features';
const Page: FC = () => {
@ -45,7 +45,7 @@ const Page: FC = () => {
}
: undefined,
);
const errorMessage = isErrorMessage(error) ? error : undefined;
const errorMessage = error as ErrorMessage;
return (
<LandingThemeProvider>
@ -91,9 +91,7 @@ const Page: FC = () => {
<AlertTitle>
{t('get-order-query.error.title')}
</AlertTitle>
{errorMessage && (
<AlertDescription>{errorMessage}</AlertDescription>
)}
<AlertDescription>{errorMessage}</AlertDescription>
</Box>
</Alert>
)}

View File

@ -2,7 +2,7 @@
/* eslint-disable @typescript-eslint/no-require-imports */
const router = require('express').Router();
const STUBS = { masters: 'success', orders: 'success', orderCreate: 'success', orderView: 'success-pending' };
const STUBS = { masters: 'success', orders: 'success', orderView: 'success-pending' };
router.get('/set/:name/:value', (req, res) => {
const { name, value } = req.params;
@ -27,11 +27,6 @@ router.get('/', (req, res) => {
${generateRadioInput('orders', 'empty')}
</fieldset>
<fieldset>
<legend>Лендинг - Сделать заказ</legend>
${generateRadioInput('orderCreate', 'success')}
${generateRadioInput('orderCreate', 'error')}
</fieldset>
<fieldset>
<legend>Лендинг - Детали заказа</legend>
${generateRadioInput('orderView', 'success-pending')}
${generateRadioInput('orderView', 'success-working')}

View File

@ -53,7 +53,7 @@ router.delete('/arm/masters/:id', (req, res) => {
);
});
router.patch('/order/:id', (req, res) => {
router.patch('/orders/:id', (req, res) => {
res
.status(/error/.test(STUBS.orders) ? 500 : 200)
.send(
@ -87,15 +87,7 @@ router.get('/order/:orderId', ({ params }, res) => {
});
router.post('/order/create', (req, res) => {
const stubName = STUBS.orderCreate;
res
.status(/error/.test(stubName) ? 500 : 200)
.send(
/^error$/.test(stubName)
? commonError
: require(`../json/landing-order-create/${stubName}.json`),
);
res.status(200).send({ success: true, body: { ok: true } });
});
router.use('/admin', require('./admin'));

View File

@ -1,4 +0,0 @@
{
"success": false,
"message": "Не удалось создать заказ"
}

View File

@ -1,6 +0,0 @@
{
"success": true,
"body": {
"id": "id1"
}
}