Compare commits

...

30 Commits

Author SHA1 Message Date
RustamRu
901d8d78a1 0.7.0
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-09 11:17:24 +03:00
RustamRu
7736592830 fix: e2e tests
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-09 11:02:27 +03:00
RustamRu
8d447c9461 0.6.0
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-09 10:20:21 +03:00
6506b89dc7 Merge pull request 'feat: add playwright' (#83) from feature/playwright into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #83
2025-02-09 10:12:42 +03:00
89d432b360 Merge pull request 'fear: change requests to RTK query' (#78) from feature/rtk-query-arm into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #78
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-02-09 10:10:40 +03:00
f6cc2efb86 Merge pull request 'feature/order-form-upgrade' (#82) from feature/order-form-upgrade into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #82
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-02-09 10:09:45 +03:00
859fa4f2e1 feat: add playwright
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-09 09:57:04 +03:00
RustamRu
0ec9e146b9 feat: order creation animation (#77)
Some checks are pending
it-academy/dry-wash-pl/pipeline/head This commit looks good
it-academy/dry-wash-pl/pipeline/pr-main Build started...
2025-02-09 09:03:24 +03:00
RustamRu
1669f01879 feat: use RTK Query to create order deails (#81)
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-09 08:04:21 +03:00
658e23d4e3 fix: place orders in the model
Some checks are pending
it-academy/dry-wash-pl/pipeline/pr-main Build started...
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-08 22:36:30 +03:00
ed8ae95436 feat: add hook useShowToast.ts
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
2025-02-08 22:18:32 +03:00
a00aaff29d fear: change requests to RTK query
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
2025-02-08 21:21:57 +03:00
ad1f948641 Merge pull request 'feat: add tests' (#79) from feature/test into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #79
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-02-04 19:41:58 +03:00
bd66f00b81 Merge pull request 'feat: rewrite the form to react-hook-form and add validation' (#80) from feature/react-hook-form into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #80
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-02-04 19:38:09 +03:00
9a20c9f098 feat: rewrite the form to react-hook-form and add validation
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-03 00:06:16 +03:00
d48f8011c1 fix: update package-lock.json
All checks were successful
it-academy/dry-wash-pl/pipeline/pr-main This commit looks good
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-02-02 14:33:31 +03:00
f2319542e7 feat: add tests
Some checks failed
it-academy/dry-wash-pl/pipeline/pr-main There was a failure building this commit
2025-02-02 14:28:51 +03:00
3fb01392f0 fix: change place 2025-02-02 14:28:51 +03:00
1dd14caed2 feat: add tests 2025-02-02 14:28:43 +03:00
12982cdf9e Merge pull request 'feature/order-view-upgrade' (#75) from feature/order-view-upgrade into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #75
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-02-02 13:34:10 +03:00
RustamRu
31b440656c feat: order view status polling feature (#74)
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-01-26 19:28:23 +03:00
RustamRu
45c4ca16c8 feat: use RTK Query to get order deails (#73) 2025-01-26 19:20:36 +03:00
e3d316c418 Merge pull request 'fix: fill location from autocomplete (#71)' (#72) from feature/order-form-upgrade into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #72
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-01-26 15:59:57 +03:00
RustamRu
4c26928d23 fix: fill location from autocomplete (#71)
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-01-26 15:47:53 +03:00
1471bf94dd Merge pull request 'fix: option select (#55)' (#70) from feature/graphic-car-body-select into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #70
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2025-01-26 15:26:03 +03:00
RustamRu
d3ffaa97f8 fix: option select (#55)
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-01-26 15:06:11 +03:00
acd09d427c fix: change endpoint order
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-01-26 12:48:54 +03:00
34bf557a6f fix: change endpoint orders
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-01-26 12:43:40 +03:00
5e0ac9f7a5 fix: change endpoint
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
2025-01-26 12:36:42 +03:00
9a2ef18925 Merge pull request 'feat: add RTK for master' (#69) from feature/RTK into main
All checks were successful
it-academy/dry-wash-pl/pipeline/head This commit looks good
Reviewed-on: #69
2025-01-26 12:25:44 +03:00
61 changed files with 6731 additions and 1340 deletions

8
.gitignore vendored
View File

@@ -130,4 +130,10 @@ dist
.yarn/install-state.gz
.pnp.*
.idea
.idea
# Playwright
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

1
__mocks__/file-mock.ts Normal file
View File

@@ -0,0 +1 @@
module.exports = 'file';

View File

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

7
babel.config.js Normal file
View File

@@ -0,0 +1,7 @@
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-typescript',
['@babel/preset-react', { runtime: 'automatic' }],
],
};

View File

@@ -21,6 +21,7 @@ module.exports = {
features: {
'dry-wash-pl': {
// add your features here in the format [featureName]: { value: string }
'order-view-status-polling': { value: '3000' }
},
},
config: {

26
e2e/example.spec.ts Normal file
View File

@@ -0,0 +1,26 @@
import { test, expect } from '@playwright/test';
test.beforeEach('check server is up', async ({ page }) => {
try {
await page.goto('http://localhost:8099/dry-wash');
const makeOrderText = page.getByText('Сделать заказ', { exact: true });
await expect(makeOrderText).toBeVisible();
} catch (error) {
console.error('server not up');
test.skip();
}
});
test('login', async ({ page }) => {
await page.goto('http://localhost:8099/dry-wash/arm');
await page.getByRole('textbox', { name: 'Username or email' }).click();
await page
.getByRole('textbox', { name: 'Username or email' })
.fill('237x237');
await page.getByRole('textbox', { name: 'Password' }).click();
await page.getByRole('textbox', { name: 'Password' }).fill('');
await page.getByRole('button', { name: 'Sign In' }).click();
await page.getByRole('heading', { name: 'Заказы' }).click();
await page.getByRole('link', { name: 'Мастера' }).click();
await page.getByRole('link', { name: 'Заказы' }).click();
});

View File

@@ -1,12 +1,13 @@
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginReact from "eslint-plugin-react";
import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginReact from 'eslint-plugin-react';
import stylistic from '@stylistic/eslint-plugin';
import pluginImport from 'eslint-plugin-import';
export default [
{ files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
{ files: ['**/*.{js,mjs,cjs,ts,jsx,tsx}'] },
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
...tseslint.configs.recommended,
@@ -14,35 +15,38 @@ export default [
{
plugins: {
'@stylistic': stylistic,
'import': pluginImport,
import: pluginImport,
},
"rules": {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"warn", // or "error"
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': [
'warn', // or "error"
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
"sort-imports": ["off"],
"import/order": [
"error",
'sort-imports': ['off'],
'import/order': [
'error',
{
"groups": [
"builtin",
"external",
"internal",
"parent",
["sibling", "index"]
groups: [
'builtin',
'external',
'internal',
'parent',
['sibling', 'index'],
],
"newlines-between": "always",
}
'newlines-between': 'always',
},
],
semi: ["error", "always"],
semi: ['error', 'always'],
'@stylistic/indent': ['error', 2],
'react/prop-types': 'off'
'react/prop-types': 'off',
},
}
},
{
ignores: ['babel.config.js'],
},
];

View File

@@ -0,0 +1,19 @@
module.exports = {
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
coverageProvider: 'v8',
coverageDirectory: 'coverage',
collectCoverageFrom: ['**/src/**/*.{ts,tsx}', '!**/src/app.tsx'],
collectCoverage: true,
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,10 +39,11 @@
"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",
"dry-wash.order-view.get-order-query.error.title": "Failed to fetch the details of order #{{number}}",
"dry-wash.order-view.get-order-query.error.title": "Failed to fetch the details of order",
"dry-wash.order-view.details.title": "Order #{{number}}",
"dry-wash.order-view.details.owner": "Owner",
"dry-wash.order-view.details.car": "Car",
@@ -86,6 +87,15 @@
"dry-wash.arm.master.drawer.inputPhone.placeholder": "Enter Phone Number",
"dry-wash.arm.master.drawer.button.save": "Save",
"dry-wash.arm.master.drawer.button.cancel": "Cancel",
"dry-wash.arm.master.drawer.toast.create-master": "Master created",
"dry-wash.arm.master.drawer.toast.error.empty-fields": "Fields cannot be empty",
"dry-wash.arm.master.drawer.toast.error.base": "Error",
"dry-wash.arm.master.drawer.toast.error.create-master": "Error creating master",
"dry-wash.arm.master.drawer.toast.error.create-master-details": "Failed to add master. Please try again",
"dry-wash.arm.master.drawer.form.name.required": "Master name is required",
"dry-wash.arm.master.drawer.form.phone.required": "Phone number is required",
"dry-wash.arm.master.drawer.form.phone.pattern": "Invalid phone number",
"dry-wash.arm.master.drawer.form.name.minLength": "Name must contain at least 2 characters",
"dry-wash.arm.master.sideBar.orders": "Orders",
"dry-wash.arm.master.sideBar.master": "Masters",
"dry-wash.arm.master.sideBar.title": "Dry Master",

View File

@@ -25,10 +25,16 @@
"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": "Введите ФИО",
@@ -36,6 +42,15 @@
"dry-wash.arm.master.drawer.inputPhone.placeholder": "Введите номер телефона",
"dry-wash.arm.master.drawer.button.save": "Сохранить",
"dry-wash.arm.master.drawer.button.cancel": "Отменить",
"dry-wash.arm.master.drawer.toast.create-master": "Мастер создан",
"dry-wash.arm.master.drawer.toast.error.empty-fields": "Поля не могут быть пустыми",
"dry-wash.arm.master.drawer.toast.error.base": "Ошибка",
"dry-wash.arm.master.drawer.toast.error.create-master": "Ошибка при создании мастера",
"dry-wash.arm.master.drawer.toast.error.create-master-details": "Не удалось добавить мастера. Попробуйте еще раз",
"dry-wash.arm.master.drawer.form.name.required": "Имя мастера обязательно",
"dry-wash.arm.master.drawer.form.phone.required": "Телефон обязателен",
"dry-wash.arm.master.drawer.form.phone.pattern": "Некорректный номер телефона",
"dry-wash.arm.master.drawer.form.name.minLength": "Имя должно содержать минимум 2 символа",
"dry-wash.arm.master.sideBar.orders": "Заказы",
"dry-wash.arm.master.sideBar.master": "Мастера",
"dry-wash.arm.master.sideBar.title": "Сухой мастер",
@@ -79,10 +94,11 @@
"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": "Ваш заказ",
"dry-wash.order-view.get-order-query.error.title": "Не удалось загрузить детали заказа №{{number}}",
"dry-wash.order-view.get-order-query.error.title": "Не удалось загрузить детали заказа",
"dry-wash.order-view.details.title": "Заказ №{{number}}",
"dry-wash.order-view.details.owner": "Владелец",
"dry-wash.order-view.details.car": "Автомобиль",

5600
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,55 +1,74 @@
{
"name": "dry-wash",
"version": "0.5.0",
"description": "<a id=\"readme-top\"></a>",
"main": "./src/index.tsx",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "brojs server --port=8099 --with-open-browser",
"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",
"preversion": "npm run eslint"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@brojs/cli": "^1.6.3",
"@chakra-ui/icons": "^2.2.4",
"@chakra-ui/react": "^2.10.5",
"@emotion/react": "^11.4.1",
"@emotion/styled": "^11.3.0",
"@fontsource/open-sans": "^5.1.0",
"@lottiefiles/react-lottie-player": "^3.5.4",
"@pbe/react-yandex-maps": "^1.2.5",
"@reduxjs/toolkit": "^2.5.0",
"@types/react": "^18.3.12",
"dayjs": "^1.11.13",
"express": "^4.21.1",
"framer-motion": "^6.2.8",
"i18next": "^23.16.4",
"keycloak-js": "^23.0.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.2",
"react-i18next": "^15.1.1",
"react-icons": "^5.3.0",
"react-phone-number-input": "^3.4.9",
"react-redux": "^9.2.0",
"react-router-dom": "^6.27.0"
},
"devDependencies": {
"@eslint/js": "^9.14.0",
"@stylistic/eslint-plugin": "^2.10.1",
"@types/react-dom": "^18.3.1",
"eslint": "^9.14.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-react": "^7.37.2",
"globals": "^15.11.0",
"prettier": "3.3.3",
"typescript-eslint": "^8.12.2"
}
"name": "dry-wash",
"version": "0.7.0",
"description": "<a id=\"readme-top\"></a>",
"main": "./src/index.tsx",
"scripts": {
"test": "jest -u",
"start": "brojs server --port=8099 --with-open-browser",
"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",
"preversion": "npm run eslint"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.26.7",
"@babel/preset-env": "^7.26.7",
"@babel/preset-react": "^7.26.3",
"@babel/preset-typescript": "^7.26.0",
"@brojs/cli": "^1.8.4",
"@chakra-ui/icons": "^2.2.4",
"@chakra-ui/react": "^2.10.5",
"@emotion/react": "^11.4.1",
"@emotion/styled": "^11.3.0",
"@fontsource/open-sans": "^5.1.0",
"@lottiefiles/react-lottie-player": "^3.5.4",
"@pbe/react-yandex-maps": "^1.2.5",
"@reduxjs/toolkit": "^2.5.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.2.0",
"@types/react": "^18.3.12",
"babel-jest": "^29.7.0",
"dayjs": "^1.11.13",
"express": "^4.21.1",
"framer-motion": "^6.2.8",
"i18next": "^23.16.4",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-fixed-jsdom": "^0.0.9",
"keycloak-js": "^23.0.7",
"msw": "^2.7.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.2",
"react-i18next": "^15.1.1",
"react-icons": "^5.3.0",
"react-phone-number-input": "^3.4.9",
"react-redux": "^9.2.0",
"react-router-dom": "^6.27.0",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2"
},
"devDependencies": {
"@eslint/js": "^9.14.0",
"@playwright/test": "^1.50.1",
"@stylistic/eslint-plugin": "^2.10.1",
"@types/node": "^22.13.1",
"@types/react-dom": "^18.3.1",
"eslint": "^9.14.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-react": "^7.37.2",
"globals": "^15.11.0",
"prettier": "3.3.3",
"typescript": "^5.7.3",
"typescript-eslint": "^8.12.2"
},
"jest": {
"preset": "./jest-preset-it/jest-preset.ts"
}
}

79
playwright.config.ts Normal file
View File

@@ -0,0 +1,79 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// import path from 'path';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://127.0.0.1:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// url: 'http://127.0.0.1:3000',
// reuseExistingServer: !process.env.CI,
// },
});

15
src/__data__/features.ts Normal file
View File

@@ -0,0 +1,15 @@
import { getFeatures } from "@brojs/cli";
const features = getFeatures('dry-wash-pl');
export const FEATURE = {
orderViewStatusPolling: {
isOn: Boolean(features['order-view-status-polling']),
getValue: () => {
const interval = parseInt(features['order-view-status-polling'].value);
if (!Number.isNaN(interval)) {
return interval;
}
}
}
};

View File

@@ -1,34 +1,53 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { getConfigValue } from '@brojs/cli';
import dayjs from 'dayjs';
import { Master } from '../../models/api/master';
import { Master, OrderArm } from '../../models/api';
type SuccessResponse<Body> = {
success: true;
body: Body;
};
import { extractBodyFromResponse } from './utils';
type ErrorResponse = {
success: false;
message: string;
};
export type UpdateMasterPayload = Required<Pick<Master, 'id'>> &
Partial<Omit<Master, 'id'>>;
type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;
type UpdateOrderProps = Required<Pick<OrderArm, 'id'>> &
Partial<Pick<OrderArm, 'status' | 'notes'>> & {
master?: string;
};
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: getConfigValue('dry-wash.api') }),
tagTypes: ['Masters'],
baseQuery: fetchBaseQuery({
baseUrl: new URL(getConfigValue('dry-wash.api'), location.origin).href,
}),
tagTypes: ['Masters', 'Orders'],
endpoints: (builder) => ({
getMasters: builder.query<Master[], void>({
query: () => ({ url: '/arm/masters' }),
transformResponse: (response: BaseResponse<Master[]>) => {
if (response.success) {
return response.body;
}
},
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',
@@ -37,5 +56,29 @@ 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

@@ -0,0 +1,23 @@
import { GetOrder, CreateOrder } from "../../models/api";
import { api } from "./api";
import { extractBodyFromResponse, extractErrorMessageFromResponse } from "./utils";
export const landingApi = api.injectEndpoints({
endpoints: ({ mutation, 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`,
params: { body },
method: 'POST'
}),
transformResponse: extractBodyFromResponse<CreateOrder.Response>,
transformErrorResponse: extractErrorMessageFromResponse,
}),
})
});

View File

@@ -0,0 +1,15 @@
import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
import { BaseResponse } from "../../models/api";
export const extractBodyFromResponse = <Body>(response: BaseResponse<Body>) => {
if (response.success) {
return response.body;
}
};
export const extractErrorMessageFromResponse = ({ data }: FetchBaseQueryError) => {
if (typeof data === 'object' && 'message' in data && typeof data.message === 'string') {
return data.message;
}
};

View File

@@ -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}${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();
};
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 };

View File

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

View File

@@ -1,107 +0,0 @@
import { getConfigValue } from '@brojs/cli';
import { useEffect, useState } from 'react';
import { CreateOrder, GetOrder } from '../models/api';
import { QueryState, Trigger } from './types';
enum LandingEndpoints {
ORDER = '/order',
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 }];
};
const useGetOrderQuery = <D extends GetOrder.Response>({
orderId,
}: GetOrder.Params): QueryState<D> => {
const [isLoading, setIsLoading] = useState<QueryState<D>['isLoading']>(true);
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']>();
useEffect(() => {
(async () => {
try {
const response = await fetch(
`${endpoint}${LandingEndpoints.ORDER}/${orderId}`,
);
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);
} catch (error) {
setIsError(true);
setError(error);
throw error;
} finally {
setIsLoading(false);
}
})();
}, []);
return { isLoading, isSuccess, data, isError, error };
};
export { useCreateOrderMutation, useGetOrderQuery };

View File

@@ -1,22 +0,0 @@
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

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

File diff suppressed because one or more lines are too long

View File

@@ -3,6 +3,7 @@ export { default as CrossoverImg } from './crossover.webp';
export { default as HatchbackImg } from './hatchback.webp';
export { default as LiftbackImg } from './liftback.webp';
export { default as MinivanImg } from './minivan.webp';
export { default as OtherImg } from './other.webp';
export { default as PickupImg } from './pickup.webp';
export { default as SedanImg } from './sedan.webp';
export { default as SportsCarImg } from './sports-car.webp';

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
Editable,
EditableInput,
@@ -9,63 +9,51 @@ 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;
onSubmit: ({
id,
name,
phone,
}: {
id: string;
name?: string;
phone?: string;
}) => Promise<unknown>;
as: 'phone' | 'name';
fieldName: 'phone' | 'name';
id: string;
}
const EditableWrapper = ({ value, onSubmit, as, id }: EditableWrapperProps) => {
const EditableWrapper = ({ value, fieldName, id }: EditableWrapperProps) => {
const [updateMaster, { isError, isSuccess, error }] =
useUpdateMasterMutation();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master.editable',
});
const toast = useToast();
const showToast = useShowToast();
const [currentValue, setCurrentValue] = useState<string>(value);
const handleSubmit = async (newValue: string) => {
if (currentValue === newValue) return;
try {
await onSubmit({ id, [as]: newValue });
await updateMaster({ id, [fieldName]: 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);
}
setCurrentValue(newValue);
};
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 from 'react';
import React, { useEffect } 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 { armService } from '../../api/arm';
import { useDeleteMasterMutation } from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
interface MasterActionsMenu {
id: string;
@@ -21,38 +21,35 @@ const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
keyPrefix: 'dry-wash.arm.master.table.actionsMenu',
});
const { deleteMaster } = armService();
const toast = useToast();
const [deleteMaster, { isSuccess, isError, error, isLoading }] =
useDeleteMasterMutation();
const showToast = useShowToast();
const handleClickDelete = async () => {
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',
});
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'));
console.error(error);
}
};
}, [isError]);
return (
<Menu>
<MenuButton icon={<EditIcon />} as={IconButton} variant='outline' />
<MenuList>
<MenuItem onClick={handleClickDelete}>{t('delete')}</MenuItem>
<MenuItem onClick={handleClickDelete} isDisabled={isLoading}>
{t('delete')}
</MenuItem>
</MenuList>
</Menu>
);

View File

@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import {
Button,
FormControl,
@@ -11,110 +12,128 @@ import {
DrawerFooter,
DrawerHeader,
DrawerOverlay,
useToast,
InputGroup,
InputLeftElement,
FormErrorMessage,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { PhoneIcon } from '@chakra-ui/icons';
import { api } from '../../__data__/service/api';
import { useAddMasterMutation } from '../../__data__/service/api';
import { DrawerInputs } from '../../models/arm/form';
import useShowToast from '../../hooks/useShowToast';
const MasterDrawer = ({ isOpen, onClose }) => {
const [addMaster, { error, isSuccess }] = api.useAddMasterMutation();
const toast = useToast();
interface MasterDrawerProps {
isOpen: boolean;
onClose: () => void;
}
const [newMaster, setNewMaster] = useState({ name: '', phone: '' });
const MasterDrawer = ({ isOpen, onClose }: MasterDrawerProps) => {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<DrawerInputs>();
const handleSave = async () => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master.drawer',
});
const onSubmit: SubmitHandler<DrawerInputs> = async (data) => {
const trimMaster = {
phone: newMaster.phone.trim(),
name: newMaster.name.trim(),
name: data.name.trim(),
phone: data.phone.trim(),
};
if (trimMaster.name === '' || trimMaster.phone === '') {
const isEmptyFields = trimMaster.name === '' || trimMaster.phone === '';
if (isEmptyFields) {
showToast(t('toast.error.base'), 'error', t('toast.error.empty-fields'));
return;
}
addMaster(trimMaster);
await addMaster(trimMaster);
};
const [addMaster, { error, isSuccess }] = useAddMasterMutation();
const showToast = useShowToast();
useEffect(() => {
if (isSuccess) {
toast({
title: 'Мастер создан.',
description: `Мастер "${newMaster.name}" успешно добавлен.`,
status: 'success',
duration: 5000,
isClosable: true,
position: 'top-right',
});
showToast(t('toast.create-master'), 'success');
reset();
onClose();
}
}, [isSuccess]);
useEffect(() => {
if (error) {
toast({
title: 'Ошибка при создании мастера.',
description: 'Не удалось добавить мастера. Попробуйте еще раз.',
status: 'error',
duration: 5000,
isClosable: true,
position: 'top-right',
});
showToast(
t('toast.error.create-master'),
'error',
t('toast.error.create-master-details'),
);
console.error(error);
}
}, [error]);
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.master.drawer',
});
return (
<Drawer isOpen={isOpen} onClose={onClose} size='md'>
<DrawerOverlay />
<DrawerContent>
<DrawerCloseButton />
<DrawerHeader>{t('title')}</DrawerHeader>
<DrawerBody>
<FormControl mb='4'>
<FormLabel>{t('inputName.label')}</FormLabel>
<Input
// isInvalid
value={newMaster.name}
onChange={(e) =>
setNewMaster({ ...newMaster, name: e.target.value })
}
placeholder={t('inputName.placeholder')}
/>
</FormControl>
<FormControl>
<FormLabel>{t('inputPhone.label')}</FormLabel>
<InputGroup>
<InputLeftElement pointerEvents='none'>
<PhoneIcon color='gray.300' />
</InputLeftElement>
<form onSubmit={handleSubmit(onSubmit)}>
<DrawerCloseButton />
<DrawerHeader>{t('title')}</DrawerHeader>
<DrawerBody>
<FormControl mb='4' isInvalid={!!errors.name}>
<FormLabel>{t('inputName.label')}</FormLabel>
<Input
// isInvalid
value={newMaster.phone}
onChange={(e) =>
setNewMaster({ ...newMaster, phone: e.target.value })
}
placeholder={t('inputPhone.placeholder')}
{...register('name', {
required: t('form.name.required'),
minLength: {
value: 2,
message: t('form.name.minLength'),
},
})}
placeholder={t('inputName.placeholder')}
/>
</InputGroup>
</FormControl>
</DrawerBody>
<DrawerFooter>
<Button colorScheme='teal' mr={3} onClick={handleSave}>
{t('button.save')}
</Button>
<Button variant='ghost' onClick={onClose}>
{t('button.cancel')}
</Button>
</DrawerFooter>
<FormErrorMessage>
{errors.name && errors.name.message}
</FormErrorMessage>
</FormControl>
<FormControl isInvalid={!!errors.phone}>
<FormLabel>{t('inputPhone.label')}</FormLabel>
<InputGroup>
<InputLeftElement pointerEvents='none'>
<PhoneIcon color='gray.300' />
</InputLeftElement>
<Input
{...register('phone', {
required: t('form.phone.required'),
pattern: {
value: /^(\+7|8)\d{10}$/,
message: t('form.phone.pattern'),
},
setValueAs: (value) => value.replace(/[^\d+]/g, ''),
})}
placeholder={t('inputPhone.placeholder')}
/>
</InputGroup>
<FormErrorMessage>
{errors.phone && errors.phone.message}
</FormErrorMessage>
</FormControl>
</DrawerBody>
<DrawerFooter>
<Button colorScheme='teal' mr={3} type='submit'>
{t('button.save')}
</Button>
<Button variant='ghost' onClick={onClose}>
{t('button.cancel')}
</Button>
</DrawerFooter>
</form>
</DrawerContent>
</Drawer>
);

View File

@@ -5,10 +5,8 @@ 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',
});
@@ -16,12 +14,7 @@ const MasterItem = ({ name, phone, id, schedule }) => {
return (
<Tr>
<Td>
<EditableWrapper
id={id}
as={'name'}
value={name}
onSubmit={updateMaster}
/>
<EditableWrapper id={id} fieldName={'name'} value={name} />
</Td>
<Td>
{schedule?.length > 0 ? (
@@ -37,12 +30,7 @@ const MasterItem = ({ name, phone, id, schedule }) => {
)}
</Td>
<Td>
<EditableWrapper
id={id}
as={'phone'}
value={phone}
onSubmit={updateMaster}
/>
<EditableWrapper id={id} fieldName={'phone'} value={phone} />
</Td>
<Td>
<MasterActionsMenu id={id} />

View File

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

View File

@@ -4,35 +4,8 @@ import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { getTimeSlot } from '../../lib';
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];
import { useUpdateOrdersMutation } from '../../__data__/service/api';
import { OrderArm, Status, statuses } from '../../models/api';
const statusColors: Record<Status, string> = {
pending: 'yellow.100',
@@ -53,9 +26,8 @@ const OrderItem = ({
master,
allMasters,
id,
}: OrderProps) => {
const { updateOrders } = armService();
}: OrderArm) => {
const [updateOrders] = useUpdateOrdersMutation();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.arm.order',
});
@@ -72,16 +44,16 @@ const OrderItem = ({
if (selectedMaster) {
setMaster(masterName);
updateOrders({ id, masterId: selectedMaster.id });
updateOrders({ id, master: selectedMaster.id });
} else {
console.error('Master not found');
}
};
const handeChangeStatus = (e: ChangeEvent<HTMLSelectElement>) => {
const status = e.target.value;
const status = e.target.value as OrderArm['status'];
updateOrders({ id, status });
setStatus(e.target.value as OrderProps['status']);
setStatus(status);
};
return (

View File

@@ -10,16 +10,18 @@ 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 { Master } from '../../models/api/master';
import {
useGetMastersQuery,
useGetOrdersQuery,
} from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';
const TABLE_HEADERS = [
'carNumber' as const,
@@ -34,47 +36,34 @@ 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(() => {
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]);
if (isError) {
showToast(t('error.title'), 'error');
}
}, [isError, ordersError, mastersError, t]);
return (
<Box p='8'>
@@ -103,25 +92,24 @@ const Orders = () => {
</Tr>
</Thead>
<Tbody>
{loading && (
{isLoading && (
<Tr>
<Td colSpan={TABLE_HEADERS.length} textAlign='center' py='8'>
<Spinner size='lg' />
</Td>
</Tr>
)}
{!loading && orders.length === 0 && !error && (
{isSuccess && orders.length === 0 && (
<Tr>
<Td colSpan={TABLE_HEADERS.length}>
<Text>{t('table.empty')}</Text>
</Td>
</Tr>
)}
{!loading &&
!error &&
{isSuccess &&
orders.map((order, index) => (
<OrderItem
allMasters={allMasters}
allMasters={masters}
key={index}
{...order}
status={order.status as OrderProps['status']}

View File

@@ -1,34 +1,38 @@
import React, { forwardRef, useState } from 'react';
import React, { forwardRef } from 'react';
import {
Input,
Image,
InputProps,
Box,
Popover,
PopoverAnchor,
PopoverContent,
PopoverBody,
List,
ListItem,
useRadioGroup,
Grid,
GridItem,
UseRadioGroupProps,
useDisclosure,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { carBodySelectOptions } from './helper';
import { CarBodySelectOption } from './types';
import { carBodySelectOptions, getInputValue } from './helper';
import { CarBodyOption } from './option';
import { CarBodySelectProps } from './types';
export const CarBodySelect = forwardRef<HTMLInputElement, InputProps>(
export const CarBodySelect = forwardRef<HTMLInputElement, CarBodySelectProps>(
function CarBodySelect(props, ref) {
const initialOption = carBodySelectOptions.find(({ value }) => value === Number(props.value));
const [selected, setSelected] = useState<Partial<CarBodySelectOption>>(initialOption);
const handleOptionClick = (option: CarBodySelectOption) => {
setSelected(option);
const handleOptionClick: UseRadioGroupProps['onChange'] = (value) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
props.onChange(option.value);
props.onChange(value);
};
const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
const { value, getRadioProps, getRootProps } = useRadioGroup({
defaultValue: props.value,
value: props.value,
onChange: handleOptionClick,
});
const { isOpen, onOpen, onClose } = useDisclosure();
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.car-body-select',
@@ -37,7 +41,7 @@ export const CarBodySelect = forwardRef<HTMLInputElement, InputProps>(
return (
<Box width='100%'>
<Popover
isOpen={isDropdownOpen}
isOpen={isOpen}
autoFocus={false}
placement='bottom-start'
matchWidth
@@ -46,45 +50,29 @@ export const CarBodySelect = forwardRef<HTMLInputElement, InputProps>(
<Input
{...props}
ref={ref}
value={
selected?.labelTKey
? t(`options.${selected.labelTKey}`)
: undefined
}
value={getInputValue(Number(value), t) ?? props.value}
readOnly
onClick={() => setIsDropdownOpen(true)}
onBlur={() => setIsDropdownOpen(false)}
onClick={onOpen}
onBlur={onClose}
placeholder={t('placeholder')}
/>
</PopoverAnchor>
<PopoverContent width='100%' maxWidth='100%'>
<PopoverBody border='1px' borderColor='gray.300' p={0}>
<List
display='grid'
gridTemplateColumns='repeat(auto-fit, minmax(150px, 1fr))'
<Grid
templateColumns='repeat(auto-fit, minmax(150px, 1fr))'
{...getRootProps()}
>
{carBodySelectOptions.map((option) => (
<ListItem
key={option.value}
display='flex'
flexDirection='column'
justifyContent='flex-end'
alignItems='center'
p={2}
cursor='pointer'
_hover={{
bgColor: 'primary.50',
}}
_active={{
bgColor: 'primary.100',
}}
onClick={() => handleOptionClick(option)}
>
<Image src={option.img} />
{t(`options.${option.labelTKey}`)}
</ListItem>
{carBodySelectOptions.map(({ value, img, labelTKey }) => (
<GridItem key={value}>
<CarBodyOption
image={img}
label={t(`options.${labelTKey}`)}
{...getRadioProps({ value: String(value) })}
/>
</GridItem>
))}
</List>
</Grid>
</PopoverBody>
</PopoverContent>
</Popover>

View File

@@ -1,3 +1,6 @@
import { TFunction } from "i18next";
import { InputProps } from "@chakra-ui/react";
import {
CoupeImg,
CrossoverImg,
@@ -8,7 +11,8 @@ import {
SedanImg,
SportsCarImg,
StationWagonImg,
SuvImg
SuvImg,
OtherImg
} from "../../../../assets/images";
import { Car } from "../../../../models/landing";
@@ -67,6 +71,17 @@ export const carBodySelectOptions: CarBodySelectOption[] = [
},
{
value: Car.BodyStyle.OTHER,
labelTKey: 'other'
labelTKey: 'other',
img: OtherImg
},
];
];
export const getInputValue = (value: Car.BodyStyle, t: TFunction<"~", "dry-wash.order-create.car-body-select">): InputProps['value'] => {
const { labelTKey } = carBodySelectOptions.find((option) => value === option.value) ?? {};
if (labelTKey) {
return t(`options.${labelTKey}`);
}
return;
};

View File

@@ -0,0 +1,39 @@
import React from 'react';
import {
ImageProps,
StackProps,
Image,
useRadio,
chakra,
Box,
UseRadioProps,
Flex,
} from '@chakra-ui/react';
import { getPropsByState } from './helper';
type CarBodyOptionProps = {
image: ImageProps['src'];
label: StackProps['children'];
} & UseRadioProps;
export const CarBodyOption = ({
image,
label,
...radioProps
}: CarBodyOptionProps) => {
const { state, getInputProps, getRadioProps, htmlProps, getLabelProps } =
useRadio(radioProps);
return (
<chakra.label {...htmlProps} cursor='pointer'>
<input {...getInputProps({})} hidden />
<Box {...getRadioProps()} p={2} {...getPropsByState(state)}>
<Flex direction='column' alignItems='center' {...getLabelProps()}>
<Image src={image} rounded={4} />
{label}
</Flex>
</Box>
</chakra.label>
);
};

View File

@@ -0,0 +1,19 @@
import {
BoxProps,
} from '@chakra-ui/react';
import { RadioState } from '@chakra-ui/react/dist/types/radio/use-radio';
export const getPropsByState = ({ isChecked }: RadioState): BoxProps => {
if (isChecked) {
return {
bgColor: 'primary.200',
_hover: { bgColor: 'primary.100' },
_active: { bgColor: 'primary.300' },
};
}
return {
_hover: { bgColor: 'primary.50' },
_active: { bgColor: 'primary.100' },
};
};

View File

@@ -0,0 +1 @@
export { CarBodyOption } from './car-body-option';

View File

@@ -1,3 +1,5 @@
import { InputProps } from "@chakra-ui/react";
import { Car } from "../../../../models/landing";
export type CarBodySelectOption = {
@@ -16,3 +18,7 @@ export type CarBodySelectOption = {
'other';
img?: string;
};
export type CarBodySelectProps = {
value?: string;
} & Pick<InputProps, 'onChange'>;

View File

@@ -9,6 +9,7 @@ export const defaultValues: Partial<OrderFormValues> = {
phone: '',
carNumber: '',
carColor: '',
carBody: '',
availableDatetimeBegin: '',
availableDatetimeEnd: '',
};

View File

@@ -42,21 +42,29 @@ export const LocationInput = memo(
const onInputChange: InputProps['onChange'] = async (e) => {
const newInputValue = e.target.value;
setInputValue(newInputValue);
if (newInputValue.trim().length > 3) {
try {
const address = extractAddress(newInputValue);
const results = await ymaps.suggest(address);
setSuggestions(results);
} catch (error) {
console.error(error);
}
if (
isValidLocation(newInputValue) &&
(await isRealLocation(ymaps, newInputValue))
) {
onChange(newInputValue);
} else {
setSuggestions([]);
setInputValue(newInputValue);
if (newInputValue.trim().length > 3) {
try {
const address = extractAddress(newInputValue);
const results = await ymaps.suggest(address);
setSuggestions(results);
} catch (error) {
console.error(error);
}
} else {
setSuggestions([]);
}
setIsSuggestionsPanelOpen(suggestions.length > 1);
}
setIsSuggestionsPanelOpen(suggestions.length > 1);
};
const onFocus: InputProps['onFocus'] = () => {
@@ -103,7 +111,7 @@ export const LocationInput = memo(
{...props}
ref={ref}
onBlur={onBlur}
value={inputValue}
value={inputValue ?? value}
onChange={onInputChange}
onFocus={onFocus}
placeholder={t('placeholder')}

View File

@@ -19,7 +19,7 @@ import { OrderStatus } from './status';
type OrderDetailsProps = Pick<
Order.View,
| 'id'
| 'orderNumber'
| 'status'
| 'phone'
| 'carNumber'
@@ -32,7 +32,7 @@ type OrderDetailsProps = Pick<
>;
export const OrderDetails: FC<OrderDetailsProps> = ({
id,
orderNumber,
status,
phone,
carNumber,
@@ -58,7 +58,7 @@ export const OrderDetails: FC<OrderDetailsProps> = ({
gap={2}
>
<Heading as='h2' size='lg'>
{t('title', { number: id })}
{t('title', { number: orderNumber })}
</Heading>
<OrderStatus value={status} />
</HStack>

View File

@@ -15,19 +15,19 @@ const getPropsByStatus = (
colorScheme: 'red',
children: t('canceled'),
};
case 'progress':
return {
colorScheme: 'yellow',
children: t('progress'),
};
case 'pending':
return {
colorScheme: 'yellow',
children: t('pending'),
};
case 'progress':
return {
colorScheme: 'orange',
children: t('progress'),
};
case 'working':
return {
colorScheme: 'yellow',
colorScheme: 'orange',
children: t('working'),
};
case 'complete':

28
src/hooks/useShowToast.ts Normal file
View File

@@ -0,0 +1,28 @@
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;

15
src/models/api/common.ts Normal file
View File

@@ -0,0 +1,15 @@
type SuccessResponse<Body> = {
success: true;
body: Body;
};
export type ErrorMessage = string;
export const isErrorMessage = (error: unknown): error is ErrorMessage => typeof error === 'string';
type ErrorResponse = {
success: false;
message: ErrorMessage;
};
export type BaseResponse<Body> = SuccessResponse<Body> | ErrorResponse;

View File

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

View File

@@ -1,18 +1,49 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { Order } from "../landing";
import { Order } from '../landing';
export namespace CreateOrder {
export type Response = {
id: Order.Id
};
export type Params = {
body: Order.Create
};
};
import { ErrorMessage } from './common';
import { Master } from './master';
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;
};
export type Params = {
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;
};

4
src/models/arm/form.ts Normal file
View File

@@ -0,0 +1,4 @@
export type DrawerInputs = {
phone: string;
name: string;
};

View File

@@ -26,6 +26,8 @@ export type Create = {
}
};
export type Number = string;
export type View = {
phone: Customer.PhoneNumber;
carNumber: Car.RegistrationNumber;
@@ -34,6 +36,7 @@ export type View = {
location: Washing.Location;
startWashTime: Washing.AvailableBeginDateTime;
endWashTime: Washing.AvailableEndDateTime;
orderNumber: Number,
status: Status,
notes: string;
created: IsoDate;

View File

@@ -0,0 +1,593 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Arm Page render 1`] = `
<div>
<div
class="css-1yeiifd"
>
<div
class="css-13owfwq"
>
<h2
class="chakra-heading css-173d1bl"
>
Сухой мастер
</h2>
<div
class="chakra-stack css-1cggwyz"
>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
<a
class="chakra-button css-1kg18wp"
href="/auth/login"
>
Заказы
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
<a
class="chakra-button css-1kg18wp"
href="/auth/login"
>
Мастера
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
</div>
</div>
<div
class="css-jiwy8d"
>
<div
class="css-1glkkdp"
>
<h2
class="chakra-heading css-1xer3cv"
>
Заказы
</h2>
<div
class="css-1u3smh"
>
<button
class="chakra-button css-ez23ye"
type="button"
>
<svg
class="chakra-icon css-onkibi"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"
fill="currentColor"
/>
</svg>
</button>
<p
class="chakra-text css-52ukzg"
>
09.02.2025
</p>
<button
class="chakra-button css-ez23ye"
type="button"
>
<svg
class="chakra-icon css-onkibi"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"
fill="currentColor"
/>
</svg>
</button>
</div>
<table
class="chakra-table css-5605sr"
>
<thead
class="css-0"
>
<tr
class="css-0"
>
<th
class="css-1szkfps"
>
Номер машины
</th>
<th
class="css-1szkfps"
>
Дата заказа
</th>
<th
class="css-1szkfps"
>
Статус
</th>
<th
class="css-1szkfps"
>
Мастер
</th>
<th
class="css-1szkfps"
>
Телефон
</th>
<th
class="css-1szkfps"
>
Расположение
</th>
</tr>
</thead>
<tbody
class="css-0"
>
<tr
class="css-0"
>
<td
class="css-1v9gmks"
colspan="6"
>
<div
class="chakra-spinner css-1j92705"
>
<span
class="css-8b45rq"
>
Loading...
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<span
hidden=""
id="__chakra_env"
/>
</div>
`;
exports[`Arm Page render 2`] = `
<div>
<div
class="css-1yeiifd"
>
<div
class="css-13owfwq"
>
<h2
class="chakra-heading css-173d1bl"
>
Сухой мастер
</h2>
<div
class="chakra-stack css-1cggwyz"
>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
<a
class="chakra-button css-1kg18wp"
href="/auth/login"
>
Заказы
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
<a
class="chakra-button css-1kg18wp"
href="/auth/login"
>
Мастера
</a>
<hr
aria-orientation="horizontal"
class="chakra-divider css-svjswr"
/>
</div>
</div>
<div
class="css-jiwy8d"
>
<div
class="css-1glkkdp"
>
<h2
class="chakra-heading css-1xer3cv"
>
Заказы
</h2>
<div
class="css-1u3smh"
>
<button
class="chakra-button css-ez23ye"
type="button"
>
<svg
class="chakra-icon css-onkibi"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"
fill="currentColor"
/>
</svg>
</button>
<p
class="chakra-text css-52ukzg"
>
09.02.2025
</p>
<button
class="chakra-button css-ez23ye"
type="button"
>
<svg
class="chakra-icon css-onkibi"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"
fill="currentColor"
/>
</svg>
</button>
</div>
<table
class="chakra-table css-5605sr"
>
<thead
class="css-0"
>
<tr
class="css-0"
>
<th
class="css-1szkfps"
>
Номер машины
</th>
<th
class="css-1szkfps"
>
Дата заказа
</th>
<th
class="css-1szkfps"
>
Статус
</th>
<th
class="css-1szkfps"
>
Мастер
</th>
<th
class="css-1szkfps"
>
Телефон
</th>
<th
class="css-1szkfps"
>
Расположение
</th>
</tr>
</thead>
<tbody
class="css-0"
>
<tr
class="css-0"
>
<td
class="css-zgoslk"
>
A123BC
</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-11j19cx"
>
<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:"
>
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

@@ -0,0 +1,129 @@
import React from 'react';
import {
describe,
it,
expect,
jest,
beforeAll,
afterEach,
afterAll,
} from '@jest/globals';
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(
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: '',
},
],
});
}),
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', () => {
return {
getNavigationValue: () => '/auth/login',
getConfigValue: () => '/api',
};
});
describe('Arm Page', () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it('render ', async () => {
server.events.on('request:start', ({ request }) => {
console.log('Outgoing:', request.method, request.url);
});
const { container } = render(
<Provider store={store}>
<ChakraProvider theme={chakraTheme}>
<ErrorBoundary>
<BrowserRouter>
<Page mockUser={{ name: 'ilnaz' }} />
</BrowserRouter>
</ErrorBoundary>
</ChakraProvider>
</Provider>,
);
expect(container).toMatchSnapshot();
await waitFor(() => screen.getByText('A123BC'));
expect(container).toMatchSnapshot();
});
});

View File

@@ -6,8 +6,12 @@ import LayoutArm from '../../components/LayoutArm';
import authLogin from '../../keycloak';
import { URLs } from '../../__data__/urls';
const Page = () => {
const [user, setUser] = useState(null);
interface PageProps {
mockUser?: { name: string };
}
const Page = ({ mockUser }: PageProps) => {
const [user, setUser] = useState(mockUser || null);
const navigate = useNavigate();

View File

@@ -1,7 +1,13 @@
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, '');
@@ -26,4 +32,40 @@ export const formatFormValues = ({ phone, carNumber, carBody, carColor, carLocat
end: dayjs(availableDatetimeEnd).toISOString(),
}
};
};
};
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,41 +1,29 @@
import React, { FC } from 'react';
import { useTranslation } from 'react-i18next';
import { Container, Heading, useToast, VStack } from '@chakra-ui/react';
import { useNavigate } from 'react-router-dom';
import { Container, Heading, VStack } from '@chakra-ui/react';
import { Player as LottiePlayer } from '@lottiefiles/react-lottie-player';
import { withLandingThemeProvider } from '../../containers';
import { OrderForm, OrderFormProps } from '../../components/order-form';
import { useCreateOrderMutation } from '../../api';
import { URLs } from '../../__data__/urls';
import { landingApi } from '../../__data__/service/landing.api';
import { OrderCreationAnimation } from '../../assets/animation';
import { formatFormValues } from './helper';
import {
formatFormValues,
useHandleCreateOrderMutationResponse,
} from './helper';
const Page: FC = () => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create',
});
const [createOrder, createOrderMutation] = useCreateOrderMutation();
const toast = useToast();
const navigate = useNavigate();
const [createOrder, createOrderMutation] =
landingApi.useCreateOrderMutation();
useHandleCreateOrderMutationResponse(createOrderMutation);
const onOrderFormSubmit: OrderFormProps['onSubmit'] = (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,
});
});
createOrder({ body: formatFormValues(values) });
};
return (
@@ -48,13 +36,24 @@ const Page: FC = () => {
centerContent
>
<VStack w='full' h='full' alignItems='stretch' flexGrow={1}>
<Heading textAlign='center' mt={4}>
{t('title')}
</Heading>
<OrderForm
onSubmit={onOrderFormSubmit}
loading={createOrderMutation.isLoading}
/>
{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>
</>
)}
</VStack>
</Container>
);

View File

@@ -1,5 +1,13 @@
import React, { FC } from 'react';
import { Alert, AlertDescription, AlertIcon, AlertTitle, HStack, Spinner } from '@chakra-ui/react';
import {
Alert,
AlertDescription,
AlertIcon,
AlertTitle,
Box,
HStack,
Spinner,
} from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { Container, Heading, VStack } from '@chakra-ui/react';
import { useParams } from 'react-router-dom';
@@ -10,7 +18,9 @@ import {
} from '../../containers';
import { OrderDetails } from '../../components/order-view';
import { Order } from '../../models/landing';
import { useGetOrderQuery } from '../../api';
import { landingApi } from '../../__data__/service/landing.api';
import { isErrorMessage } from '../../models/api';
import { FEATURE } from '../../__data__/features';
const Page: FC = () => {
const { t } = useTranslation('~', {
@@ -21,12 +31,21 @@ const Page: FC = () => {
const {
isLoading,
isSuccess,
data: { body: order } = {},
data: order,
isError,
error,
} = useGetOrderQuery({
orderId,
});
} = landingApi.useGetOrderQuery(
{
orderId,
},
FEATURE.orderViewStatusPolling.isOn
? {
pollingInterval: FEATURE.orderViewStatusPolling.getValue(),
skipPollingIfUnfocused: true,
}
: undefined,
);
const errorMessage = isErrorMessage(error) ? error : undefined;
return (
<LandingThemeProvider>
@@ -51,7 +70,7 @@ const Page: FC = () => {
<>
{isSuccess && (
<OrderDetails
id={order.id}
orderNumber={order.orderNumber}
status={order.status}
phone={order.phone}
carNumber={order.carNumber}
@@ -66,14 +85,16 @@ const Page: FC = () => {
</>
<>
{isError && (
<Alert status='error'>
<Alert status='error' alignItems='flex-start'>
<AlertIcon />
<AlertTitle>
{t('get-order-query.error.title', {
number: orderId,
})}
</AlertTitle>
<AlertDescription>{error.data?.error}</AlertDescription>
<Box>
<AlertTitle>
{t('get-order-query.error.title')}
</AlertTitle>
{errorMessage && (
<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', orderView: 'success' };
const STUBS = { masters: 'success', orders: 'success', orderCreate: 'success', orderView: 'success-pending' };
router.get('/set/:name/:value', (req, res) => {
const { name, value } = req.params;
@@ -14,21 +14,27 @@ router.get('/set/:name/:value', (req, res) => {
router.get('/', (req, res) => {
res.send(`<div>
<fieldset>
<fieldset>
<legend>Мастера</legend>
${generateRadioInput('masters', 'success')}
${generateRadioInput('masters', 'error')}
${generateRadioInput('masters', 'empty')}
</fieldset>
<fieldset>
<fieldset>
<legend>Заказы</legend>
${generateRadioInput('orders', 'success')}
${generateRadioInput('orders', 'error')}
${generateRadioInput('orders', 'empty')}
</fieldset>
<fieldset>
<fieldset>
<legend>Лендинг - Сделать заказ</legend>
${generateRadioInput('orderCreate', 'success')}
${generateRadioInput('orderCreate', 'error')}
</fieldset>
<fieldset>
<legend>Лендинг - Детали заказа</legend>
${generateRadioInput('orderView', 'success')}
${generateRadioInput('orderView', 'success-pending')}
${generateRadioInput('orderView', 'success-working')}
${generateRadioInput('orderView', 'error')}
</fieldset>
</div>`);

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,10 +8,11 @@
"startWashTime": "2025-01-19T14:03:00.000Z",
"endWashTime": "2025-01-19T14:03:00.000Z",
"location": "55.793833888711006,49.19037910644527 Республика Татарстан (Татарстан), Казань, жилой район Седьмое Небо",
"status": "progress",
"orderNumber": "1",
"status": "pending",
"notes": "",
"created": "2025-01-19T14:04:02.985Z",
"updated": "2025-01-19T14:04:02.987Z",
"id": "678d06527d78ec30be2679d8"
"id": "id1"
}
}

View File

@@ -0,0 +1,18 @@
{
"success": true,
"body": {
"phone": "+79876543210",
"carNumber": "А123АА16",
"carBody": 2,
"carColor": "#ffffff",
"startWashTime": "2025-01-19T14:03:00.000Z",
"endWashTime": "2025-01-19T14:03:00.000Z",
"location": "55.793833888711006,49.19037910644527 Республика Татарстан (Татарстан), Казань, жилой район Седьмое Небо",
"orderNumber": "1",
"status": "working",
"notes": "",
"created": "2025-01-19T14:04:02.985Z",
"updated": "2025-01-19T14:04:02.987Z",
"id": "id1"
}
}