Compare commits

...

19 Commits

Author SHA1 Message Date
RustamRu
351420bc62 0.9.1
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-23 12:37:44 +03:00
RustamRu
61b042eee6 fix: image input accept, i18n (#88)
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-23 12:37:04 +03:00
RustamRu
ac006267a2 0.9.0
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-23 12:11:20 +03:00
RustamRu
63d9d069c0 feat: add car image feature
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-23 12:08:50 +03:00
c83ebf02bc Merge pull request 'feature/upload-car-image' (#90) from feature/upload-car-image into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #90
2025-02-23 12:02:39 +03:00
RustamRu
1968df7bb3 fix: getOrder test (#88)
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
2025-02-23 11:58:56 +03:00
RustamRu
811e0e3f24 Merge remote-tracking branch 'origin/main' into feature/upload-car-image
Some checks failed
it-academy/dry-wash-pl/pipeline/pr-main There was a failure building this commit
2025-02-23 11:47:04 +03:00
a2ffd6f38f Merge pull request 'fix tests error' (#89) from debug into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #89
2025-02-23 11:32:09 +03:00
RustamRu
20017cad3c feat: upload car img form (#88)
Some checks failed
it-academy/dry-wash-pl/pipeline/head There was a failure building this commit
it-academy/dry-wash-pl/pipeline/pr-main There was a failure building this commit
2025-02-22 19:46:27 +03:00
RustamRu
de54ac6669 feat: api upload car img (#88) 2025-02-22 18:56:37 +03:00
RustamRu
eda869622e fix: error body message -> error (#88) 2025-02-22 18:56:20 +03:00
Primakov Alexandr Alexandrovich
7b3889aa02 run last one
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
2025-02-20 14:15:25 +03:00
Primakov Alexandr Alexandrovich
cee124fca5 other 2
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-20 14:10:46 +03:00
Primakov Alexandr Alexandrovich
b77eccc8e8 test: улучшены описания тестов страницы просмотра заказа
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
- Добавлены более информативные описания тестовых сценариев
- Улучшена читаемость тестов за счет детальных названий на русском языке
2025-02-20 14:04:32 +03:00
Primakov Alexandr Alexandrovich
ebfaa7ea8f orders page
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-20 14:00:34 +03:00
Primakov Alexandr Alexandrovich
0027cc09b1 masters test
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-20 13:55:05 +03:00
Primakov Alexandr Alexandrovich
dd612d662c debug
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-20 13:44:38 +03:00
Primakov Alexandr Alexandrovich
69251745fa try fix
Some checks failed
it-academy/dry-wash-pl/pipeline/head There was a failure building this commit
2025-02-20 13:32:39 +03:00
Primakov Alexandr Alexandrovich
253e3b3856 try skip one test
Some checks failed
it-academy/dry-wash-pl/pipeline/head There was a failure building this commit
2025-02-20 13:26:35 +03:00
35 changed files with 382 additions and 87 deletions

5
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"i18n-ally.localesPaths": [
"locales"
]
}

6
Jenkinsfile vendored
View File

@ -1,7 +1,7 @@
pipeline {
agent {
docker {
image 'node:20'
image 'node:22'
}
}
@ -30,8 +30,6 @@ pipeline {
}
}
stage('checks') {
parallel {
stage('eslint') {
steps {
sh 'npm run eslint'
@ -49,8 +47,6 @@ pipeline {
sh 'npm run build'
}
}
}
}
stage('clean-all') {
steps {

View File

@ -21,7 +21,16 @@ module.exports = {
features: {
'dry-wash': {
// add your features here in the format [featureName]: { value: string }
'order-view-status-polling': { value: '3000' }
"order-view-status-polling": {
"on": true,
"value": "3000",
"key": "order-view-status-polling"
},
"car-img-upload": {
"on": true,
"value": "true",
"key": "car-img-upload"
}
},
},
config: {

View File

@ -50,6 +50,12 @@
"dry-wash.order-view.details.location": "Where",
"dry-wash.order-view.details.datetime-range": "When",
"dry-wash.order-view.details.alert": "The operator will contact you about the payment at the specified phone number",
"dry-wash.order-view.upload-car-image.field.label": "Upload a photo of your car, and our service will quickly calculate the pre-order price!",
"dry-wash.order-view.upload-car-image.field.help": "Allowed formats: .jpg, .png. Maximum size: 5MB",
"dry-wash.order-view.upload-car-image.file-input.placeholder": "Upload a file",
"dry-wash.order-view.upload-car-image.file-input.button": "Upload",
"dry-wash.order-view.upload-car-image-query.success.title": "The car image is successfully uploaded",
"dry-wash.order-view.upload-car-image-query.error.title": "Failed to upload the car image",
"dry-wash.arm.master.add": "Add",
"dry-wash.arm.order.title": "Orders",
"dry-wash.arm.order.table.empty": "Table empty",

View File

@ -105,6 +105,12 @@
"dry-wash.order-view.details.location": "Где",
"dry-wash.order-view.details.datetime-range": "Когда",
"dry-wash.order-view.details.alert": "С вами свяжется оператор насчет оплаты по указанному номеру телефона",
"dry-wash.order-view.upload-car-image.field.label": "Загрузите фото вашего автомобиля, и наш сервис быстро рассчитает предварительную стоимость заказа!",
"dry-wash.order-view.upload-car-image.field.help": "Допустимые форматы: .jpg, .png. Максимальный размер: 5МБ",
"dry-wash.order-view.upload-car-image.file-input.placeholder": "Загрузите файл",
"dry-wash.order-view.upload-car-image.file-input.button": "Загрузить",
"dry-wash.order-view.upload-car-image-query.success.title": "Изображение автомобиля успешно загружено",
"dry-wash.order-view.upload-car-image-query.error.title": "Не удалось загрузить изображение автомобиля",
"dry-wash.notFound.title": "Страница не найдена",
"dry-wash.notFound.description": "К сожалению, запрашиваемая вами страница не существует.",
"dry-wash.notFound.button.back": "Вернуться на главную",

4
package-lock.json generated
View File

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

View File

@ -1,6 +1,6 @@
{
"name": "dry-wash",
"version": "0.8.0",
"version": "0.9.1",
"description": "<a id=\"readme-top\"></a>",
"main": "./src/index.tsx",
"scripts": {
@ -9,8 +9,8 @@
"build": "npm run clean && brojs build --dev",
"build:prod": "npm run clean && brojs build",
"clean": "rimraf dist",
"eslint": "npx eslint .",
"eslint:fix": "npx eslint . --fix",
"eslint": "npx eslint src",
"eslint:fix": "npx eslint src --fix",
"preversion": "npm run eslint"
},
"keywords": [],

View File

@ -11,5 +11,8 @@ export const FEATURE = {
return interval;
}
}
},
carImageUpload: {
isOn: Boolean(features?.['car-img-upload'])
}
};

View File

@ -1,4 +1,4 @@
import { GetOrder, CreateOrder } from "../../models/api";
import { GetOrder, CreateOrder, UploadCarImage } from "../../models/api";
import { api } from "./api";
import { extractBodyFromResponse, extractErrorMessageFromResponse } from "./utils";
@ -19,5 +19,13 @@ export const landingApi = api.injectEndpoints({
transformResponse: extractBodyFromResponse<CreateOrder.Response>,
transformErrorResponse: extractErrorMessageFromResponse,
}),
uploadCarImage: mutation<UploadCarImage.Response, UploadCarImage.Params>({
query: ({ orderId, body }) => ({
url: `/order/${orderId}/upload-car-img`,
body,
method: 'POST'
}),
transformErrorResponse: extractErrorMessageFromResponse,
}),
})
});

View File

@ -13,9 +13,10 @@ export const extractErrorMessageFromResponse = ({
}: FetchBaseQueryError) => {
if (
typeof data === 'object' &&
'message' in data &&
typeof data.message === 'string'
data !== null &&
'error' in data &&
typeof data.error === 'string'
) {
return data.message;
return data.error;
}
};

View File

@ -7,7 +7,9 @@ export const store = configureStore({
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
getDefaultMiddleware({
serializableCheck: false
}).concat(api.middleware),
});
export type RootState = ReturnType<typeof store.getState>;

View File

@ -28,7 +28,6 @@ class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
console.error('4545');
this.setState({ error, errorInfo });
}

View File

@ -24,6 +24,10 @@ jest.mock('@brojs/cli', () => {
describe('ErrorBoundary', () => {
it('должен отобразить запасной UI при ошибке', async () => {
// Подавляем вывод ошибки в консоль во время теста
const consoleSpy = jest.spyOn(console, 'error');
consoleSpy.mockImplementation(() => {});
const { container } = render(
<Provider store={store}>
<ErrorBoundary>
@ -39,7 +43,9 @@ describe('ErrorBoundary', () => {
);
expect(button).not.toBeNull();
expect(container).toMatchSnapshot();
// Восстанавливаем console.error после теста
consoleSpy.mockRestore();
});
});

View File

@ -0,0 +1,102 @@
import React, { FC, memo, useRef } from 'react';
import { Controller, useForm } from 'react-hook-form';
import {
Button,
FormControl,
FormErrorMessage,
FormHelperText,
FormLabel,
HStack,
Input,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { landingApi } from '../../../__data__/service/landing.api';
import { UploadCarImage } from '../../../models/api';
import { useHandleUploadCarImageResponse } from './helper';
type FormValues = {
carImg: File & {
fileName: string;
};
};
type CarImageFormProps = {
orderId: UploadCarImage.Params['orderId'];
};
export const CarImageForm: FC<CarImageFormProps> = memo(function CarImageForm({
orderId,
}) {
const {
handleSubmit,
control,
formState: { errors, isSubmitting },
} = useForm<FormValues>({ shouldFocusError: true });
const [uploadCarImage, uploadCarImageMutation] =
landingApi.useUploadCarImageMutation();
useHandleUploadCarImageResponse(uploadCarImageMutation);
const onSubmit = (formData: FormValues) => {
const body = new FormData();
body.append('file', formData.carImg);
uploadCarImage({ orderId, body });
};
const fileInputRef = useRef(null);
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-view.upload-car-image',
});
return (
<form>
<FormControl>
<FormLabel htmlFor='carImg'>{t('field.label')}</FormLabel>
<Controller
control={control}
name='carImg'
render={({ field: { value, onChange, ...field } }) => {
return (
<HStack gap={0}>
<Input
{...field}
ref={fileInputRef}
accept='image/png,image/jpeg'
value={value?.fileName}
onChange={(event) => {
onChange(event.target.files[0]);
handleSubmit(onSubmit)();
}}
type='file'
hidden
/>
<Input
placeholder={t('file-input.placeholder')}
value={value?.name || ''}
readOnly
borderRightRadius={0}
/>
<Button
onClick={() => {
fileInputRef.current.click();
}}
isLoading={isSubmitting || uploadCarImageMutation.isLoading}
colorScheme='primary'
paddingInline={8}
borderLeftRadius={0}
>
{t('file-input.button')}
</Button>
</HStack>
);
}}
/>
<FormErrorMessage>{errors.carImg?.message}</FormErrorMessage>
<FormHelperText>{t('field.help')}</FormHelperText>
</FormControl>
</form>
);
});

View File

@ -0,0 +1,35 @@
import { useEffect } from "react";
import { useToast } from "@chakra-ui/react";
import { useTranslation } from "react-i18next";
import { isErrorMessage } from "../../../models/api";
export const useHandleUploadCarImageResponse = (query: {
isSuccess: boolean;
isError: boolean;
error?: unknown;
}) => {
const toast = useToast();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-view.upload-car-image-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) {
toast({
status: 'success',
title: t('success.title'),
});
}
}, [query.isSuccess]);
};

View File

@ -0,0 +1 @@
export { CarImageForm } from './car-img-form';

View File

@ -5,11 +5,13 @@ import {
Heading,
HStack,
UnorderedList,
VStack,
ListItem,
Text,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import localizedFormat from "dayjs/plugin/localizedFormat";
dayjs.extend(localizedFormat);
import { Order } from '../../../models/landing';
import { formatDatetime } from '../../../lib';
@ -41,7 +43,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
location,
startWashTime,
endWashTime,
...props
created
}) => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-view.details',
@ -51,7 +53,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
});
return (
<VStack p={4} alignItems='flex-start' gap={4} {...props}>
<>
<HStack
width='full'
flexWrap='wrap'
@ -59,7 +61,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
gap={2}
>
<Heading as='h2' size='lg'>
{t('title', { number: orderNumber })}
{t('title', { number: orderNumber })} ({dayjs(created).format('LLLL')})
</Heading>
<OrderStatus value={status} />
</HStack>
@ -105,7 +107,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
<AlertIcon />
{t('alert')}
</Alert>
</VStack>
</>
);
};

View File

@ -9,7 +9,7 @@ export const isErrorMessage = (error: unknown): error is ErrorMessage => typeof
type ErrorResponse = {
success: false;
message: ErrorMessage;
error: ErrorMessage;
};
export type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;

View File

@ -21,6 +21,17 @@ export namespace CreateOrder {
};
}
export namespace UploadCarImage {
export type Response = void;
export type Params = {
orderId: Order.Id;
/**
* @example { file: File }
*/
body: FormData;
};
}
type GetArrItemType<ArrType> =
ArrType extends Array<infer ItemType> ? ItemType : never;

View File

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Master Page render 1`] = `
exports[`Master Page should display master list and show details when master button is clicked 1`] = `
<div>
<div
class="css-1yeiifd"

View File

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Order View page, initial load shows order details 1`] = `
exports[`Страница просмотра заказа отображает детали заказа после успешной загрузки 1`] = `
<div>
<div
class="chakra-container css-3n6qh3"
@ -16,7 +16,6 @@ exports[`Order View page, initial load shows order details 1`] = `
</h2>
<div
class="chakra-stack css-1n38vgh"
created="2025-01-19T14:04:02.985Z"
data-testid="order-details"
>
<div
@ -26,6 +25,9 @@ exports[`Order View page, initial load shows order details 1`] = `
class="chakra-heading css-1jb3vzl"
>
Заказ №{{number}}
(
Sunday, January 19, 2025 5:04 PM
)
</h2>
<span
class="css-6jfsiv"
@ -126,7 +128,7 @@ exports[`Order View page, initial load shows order details 1`] = `
</div>
`;
exports[`Order View page, initial load shows order details loading 1`] = `
exports[`Страница просмотра заказа отображает индикатор загрузки деталей заказа 1`] = `
<div>
<div
class="chakra-container css-3n6qh3"
@ -171,7 +173,7 @@ exports[`Order View page, initial load shows order details loading 1`] = `
</div>
`;
exports[`Order View page, initial load shows order error 1`] = `
exports[`Страница просмотра заказа отображает ошибку при некорректном ID заказа 1`] = `
<div>
<div
class="chakra-container css-3n6qh3"

View File

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`order page получение списка заказов 1`] = `
exports[`Страница заказов должна корректно отображать список заказов после загрузки данных 1`] = `
<div>
<div
class="css-1yeiifd"
@ -75,7 +75,7 @@ exports[`order page получение списка заказов 1`] = `
<p
class="chakra-text css-52ukzg"
>
16.02.2025
23.02.2025
</p>
<button
class="chakra-button css-ez23ye"

View File

@ -54,6 +54,41 @@ const server = setupServer(
],
});
}),
http.post('/api/arm/orders', () => {
return HttpResponse.json({
success: true,
body: [
{
id: 'order1',
carNumber: 'A123BC',
startWashTime: '2024-11-24T10:30:00.000Z',
endWashTime: '2024-11-24T16:30:00.000Z',
orderDate: '2024-11-24T08:41:46.366Z',
status: 'pending',
phone: '79001234563',
location: 'Казань, ул. Баумана, 1',
master: {
name: 'Олег Макаров',
phone: '79001234567',
id: '23423442',
},
notes: '',
},
{
id: 'order2',
carNumber: 'A245BC',
startWashTime: '2024-11-24T11:30:00.000Z',
endWashTime: '2024-11-24T17:30:00.000Z',
orderDate: '2024-11-24T07:40:46.366Z',
status: 'progress',
phone: '79001234567',
location: 'Казань, ул. Баумана, 43',
master: [],
notes: '',
},
],
});
}),
);
jest.mock('@brojs/cli', () => {
@ -70,11 +105,7 @@ describe('Master Page', () => {
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('render ', async () => {
server.events.on('request:start', ({ request }) => {
console.log('Outgoing:', request.method, request.url);
});
it('should display master list and show details when master button is clicked', async () => {
const { container } = render(
<Provider store={store}>
<ChakraProvider theme={chakraTheme}>
@ -88,10 +119,14 @@ describe('Master Page', () => {
);
const button = await waitFor(() => screen.getByTestId('master-button'));
fireEvent.click(button);
await waitFor(() => screen.getByText('Иван Иванов'));
// Проверяем отображение всех мастеров
await waitFor(() => {
expect(screen.getByText('Иван Иванов')).toBeInTheDocument();
expect(screen.getByText('Олег Макаров')).toBeInTheDocument();
expect(screen.getByText('Иван Галкин')).toBeInTheDocument();
});
expect(container).toMatchSnapshot();
});

View File

@ -11,12 +11,12 @@ jest.mock('react-router-dom', () => ({
useParams: jest.fn(),
}));
describe('Order View page, initial load', () => {
describe('Страница просмотра заказа', () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('shows order details loading', () => {
test('отображает индикатор загрузки деталей заказа', () => {
(useParams as jest.Mock).mockReturnValue({ orderId: 'id1' });
const { container } = render(
@ -33,7 +33,7 @@ describe('Order View page, initial load', () => {
expect(container).toMatchSnapshot();
});
test('shows order details', async () => {
test('отображает детали заказа после успешной загрузки', async () => {
(useParams as jest.Mock).mockReturnValue({ orderId: 'id1' });
const { container } = render(
@ -52,7 +52,7 @@ describe('Order View page, initial load', () => {
expect(container).toMatchSnapshot();
});
test('shows order error', async () => {
test('отображает ошибку при некорректном ID заказа', async () => {
(useParams as jest.Mock).mockReturnValue({ orderId: null });
const { container } = render(

View File

@ -46,10 +46,6 @@ describe('order page', () => {
afterAll(() => server.close());
it('получение пустого списка', async () => {
server.events.on('request:start', ({ request }) => {
console.log('Outgoing:', request.method, request.url);
});
render(
<Provider store={store}>
<ChakraProvider theme={chakraTheme}>

View File

@ -21,9 +21,43 @@ import Page from '../arm';
import { PageSpinner } from '../../components';
const server = setupServer(
http.get('/api/arm/orders', () => {
http.post('/api/arm/orders', () => {
return HttpResponse.json({}, { status: 500 });
}),
http.get('/api/arm/masters', () => {
return HttpResponse.json({
success: true,
body: [
{
id: '4545423234',
name: 'Иван Иванов',
phone: '+7 900 123 45 67',
},
{
name: 'Олег Макаров',
phone: '79001234567',
id: '23423442',
},
{
id: '345354234',
name: 'Иван Галкин',
schedule: [
{
id: 'order1',
startWashTime: '2024-11-24T10:30:00.000Z',
endWashTime: '2024-11-24T16:30:00.000Z',
},
{
id: 'order2',
startWashTime: '2024-11-24T11:30:00.000Z',
endWashTime: '2024-11-24T17:30:00.000Z',
},
],
phone: '+7 900 123 45 67',
},
],
});
}),
);
jest.mock('@brojs/cli', () => {

View File

@ -98,16 +98,12 @@ jest.mock('@brojs/cli', () => {
};
});
describe('order page', () => {
describe('Страница заказов', () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('получение списка заказов ', async () => {
server.events.on('request:start', ({ request }) => {
console.log('Outgoing:', request.method, request.url);
});
it('должна корректно отображать список заказов после загрузки данных', async () => {
const { container } = render(
<Provider store={store}>
<ChakraProvider theme={chakraTheme}>

View File

@ -21,6 +21,7 @@ import { Order } from '../../models/landing';
import { landingApi } from '../../__data__/service/landing.api';
import { isErrorMessage } from '../../models/api';
import { FEATURE } from '../../__data__/features';
import { CarImageForm } from '../../components/order-view/car-img';
const Page: FC = () => {
const { t } = useTranslation('~', {
@ -69,6 +70,7 @@ const Page: FC = () => {
<>
<>
{isSuccess && (
<VStack p={4} alignItems='flex-start' gap={4} data-testid='order-details'>
<OrderDetails
orderNumber={order.orderNumber}
status={order.status}
@ -80,13 +82,18 @@ const Page: FC = () => {
startWashTime={order.startWashTime}
endWashTime={order.endWashTime}
created={order.created}
data-testid='order-details'
/>
{FEATURE.carImageUpload.isOn && <CarImageForm orderId={orderId} />}
</VStack>
)}
</>
<>
{isError && (
<Alert status='error' alignItems='flex-start' data-testid='error'>
<Alert
status='error'
alignItems='flex-start'
data-testid='error'
>
<AlertIcon />
<Box>
<AlertTitle>

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', orderCreate: 'success', orderView: 'success-pending', orderCarImg: 'success' };
router.get('/set/:name/:value', (req, res) => {
const { name, value } = req.params;
@ -37,6 +37,12 @@ router.get('/', (req, res) => {
${generateRadioInput('orderView', 'success-working')}
${generateRadioInput('orderView', 'error')}
</fieldset>
<fieldset>
<legend>Лендинг - Детали заказа, фото машины</legend>
${generateRadioInput('orderCarImg', 'success')}
${generateRadioInput('orderCarImg', 'error-file-type')}
${generateRadioInput('orderCarImg', 'error-file-size')}
</fieldset>
</div>`);
});

View File

@ -98,6 +98,22 @@ router.post('/order/create', (req, res) => {
);
});
router.post('/order/:orderId/upload-car-img', (req, res) => {
const { orderId } = req.params;
const stubName = `${orderId}-${STUBS.orderCarImg}`;
try {
res
.status(/error/.test(stubName) ? 500 : 200)
.send(require(`../json/landing-order-car-image-upload/${stubName}.json`));
} catch (e) {
console.error(e);
res
.status(500)
.send(commonError);
}
});
router.use('/admin', require('./admin'));
module.exports = router;

View File

@ -0,0 +1,4 @@
{
"success": false,
"error": "Invalid car image file size. Limit is 5MB"
}

View File

@ -0,0 +1,4 @@
{
"success": false,
"error": "Invalid car image file type. Allowed types: jpg, png"
}

View File

@ -0,0 +1,3 @@
{
"success": true
}

View File

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

View File

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