feat: eslint and format code

This commit is contained in:
IlyaDoronin 2024-05-21 10:41:31 +03:00
parent b0e1b4a4a6
commit 16901608af
149 changed files with 10606 additions and 10883 deletions

@ -24,7 +24,6 @@ deploy-to-staging:
- if: "$CI_COMMIT_BRANCH == $STAGING_BRANCH"
extends: .deploy_template
deploy-to-prod:
tags:
- front

@ -1 +1 @@
# pena_hub_admin_front
# pena_hub_admin_front

@ -1,6 +1,3 @@
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript",
],
presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript"],
};

@ -1,17 +1,17 @@
const CracoAlias = require("craco-alias");
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
// baseUrl SHOULD be specified
// plugin does not take it from tsconfig
baseUrl: "./src",
// tsConfigPath should point to the file where "baseUrl" and "paths" are specified
tsConfigPath: "./tsconfig.extend.json"
}
}
]
};
plugins: [
{
plugin: CracoAlias,
options: {
source: "tsconfig",
// baseUrl SHOULD be specified
// plugin does not take it from tsconfig
baseUrl: "./src",
// tsConfigPath should point to the file where "baseUrl" and "paths" are specified
tsConfigPath: "./tsconfig.extend.json",
},
},
],
};

@ -1,11 +1,11 @@
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
viewportWidth: 1200,
viewportHeight: 800,
fixturesFolder: "tests/e2e/fixtures",
supportFile: false,
defaultCommandTimeout: 100,
},
e2e: {
viewportWidth: 1200,
viewportHeight: 800,
fixturesFolder: "tests/e2e/fixtures",
supportFile: false,
defaultCommandTimeout: 100,
},
});

@ -1,110 +1,110 @@
describe("Форма Входа", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
});
beforeEach(() => {
cy.visit("http://localhost:3000");
});
it("должна успешно входить с правильными учетными данными", () => {
const email = "valid_user@example.com";
const password = "valid_password";
it("должна успешно входить с правильными учетными данными", () => {
const email = "valid_user@example.com";
const password = "valid_password";
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('button[type="submit"]').click();
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('button[type="submit"]').click();
cy.url().should("include", "http://localhost:3000/users");
});
cy.url().should("include", "http://localhost:3000/users");
});
it("должна отображать сообщение об ошибке при неверном формате электронной почты", () => {
const invalidEmail = "invalid_email";
it("должна отображать сообщение об ошибке при неверном формате электронной почты", () => {
const invalidEmail = "invalid_email";
cy.get('input[name="email"]').type(invalidEmail);
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.get('input[name="email"]').type(invalidEmail);
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.contains("Неверный формат эл. почты");
});
cy.contains("Неверный формат эл. почты");
});
it("должна отображать сообщение об ошибке при отсутствии пароля", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('button[type="submit"]').click();
it("должна отображать сообщение об ошибке при отсутствии пароля", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('button[type="submit"]').click();
cy.contains("Введите пароль");
});
cy.contains("Введите пароль");
});
it("должна отображать сообщение об ошибке для недопустимого пароля", () => {
const invalidPassword = "short";
it("должна отображать сообщение об ошибке для недопустимого пароля", () => {
const invalidPassword = "short";
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="password"]').type(invalidPassword);
cy.get('button[type="submit"]').click();
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="password"]').type(invalidPassword);
cy.get('button[type="submit"]').click();
cy.contains("Invalid password");
});
cy.contains("Invalid password");
});
});
describe("Форма регистрации", () => {
beforeEach(() => {
cy.visit("http://localhost:3000/signup");
});
beforeEach(() => {
cy.visit("http://localhost:3000/signup");
});
it("должна регистрировать нового пользователя с правильными данными", () => {
const email = Cypress._.random(1000) + "@example.com";
const password = "valid_password";
it("должна регистрировать нового пользователя с правильными данными", () => {
const email = Cypress._.random(1000) + "@example.com";
const password = "valid_password";
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('input[name="repeatPassword"]').type(password);
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('input[name="repeatPassword"]').type(password);
cy.get('button[type="submit"]').click();
cy.wait(5000);
cy.get('button[type="submit"]').click();
cy.wait(5000);
cy.url().should("include", "http://localhost:3000/users");
});
cy.url().should("include", "http://localhost:3000/users");
});
it("должна отображать ошибку при неверном формате электронной почты", () => {
const invalidEmail = "invalid_email";
it("должна отображать ошибку при неверном формате электронной почты", () => {
const invalidEmail = "invalid_email";
cy.get('input[name="email"]').type(invalidEmail);
cy.get('input[name="password"]').type("valid_password");
cy.get('input[name="repeatPassword"]').type("valid_password");
cy.get('input[name="email"]').type(invalidEmail);
cy.get('input[name="password"]').type("valid_password");
cy.get('input[name="repeatPassword"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.get('button[type="submit"]').click();
cy.contains("Неверный формат эл. почты");
});
cy.contains("Неверный формат эл. почты");
});
it("должна отображать ошибку при отсутствии пароля", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="repeatPassword"]').type("valid_password");
it("должна отображать ошибку при отсутствии пароля", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="repeatPassword"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.get('button[type="submit"]').click();
cy.contains("Обязательное поле").should("have.length", 1);
});
cy.contains("Обязательное поле").should("have.length", 1);
});
it("должна отображать ошибку при несовпадении паролей", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('input[name="repeatPassword"]').type("different_password");
it("должна отображать ошибку при несовпадении паролей", () => {
cy.get('input[name="email"]').type("valid_email@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('input[name="repeatPassword"]').type("different_password");
cy.get('button[type="submit"]').click();
cy.get('button[type="submit"]').click();
cy.contains("Пароли не совпадают");
});
cy.contains("Пароли не совпадают");
});
it("попытка отправки запроса при уже зарегистрированном пользователе", () => {
const email = "users@gmail.com";
const password = "12344321";
it("попытка отправки запроса при уже зарегистрированном пользователе", () => {
const email = "users@gmail.com";
const password = "12344321";
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('input[name="repeatPassword"]').type(password);
cy.get('input[name="email"]').type(email);
cy.get('input[name="password"]').type(password);
cy.get('input[name="repeatPassword"]').type(password);
cy.intercept("POST", process.env.REACT_APP_DOMAIN + "/auth/register").as("registerRequest");
cy.get('button[type="submit"]').click();
cy.wait("@registerRequest");
cy.intercept("POST", process.env.REACT_APP_DOMAIN + "/auth/register").as("registerRequest");
cy.get('button[type="submit"]').click();
cy.wait("@registerRequest");
cy.wait(5000);
cy.contains("user with this login is exist");
});
cy.wait(5000);
cy.contains("user with this login is exist");
});
});

@ -1,246 +1,246 @@
describe("Форма Создания Тарифа", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
it("должна отображать сообщение об ошибке при пустом названии тарифа", () => {
cy.get('input[id="tariff-amount"]').type("10");
it("должна отображать сообщение об ошибке при пустом названии тарифа", () => {
cy.get('input[id="tariff-amount"]').type("10");
// Выбрать первую привилегию с нужным текстом из выпадающего списка
cy.get("#privilege-select").click();
// Выбрать первую привилегию с нужным текстом из выпадающего списка
cy.get("#privilege-select").click();
cy.get(`[data-cy = "select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(`[data-cy = "select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get(".btn_createTariffBackend").click({ force: true });
cy.contains("Пустое название тарифа");
});
cy.contains("Пустое название тарифа");
});
it("должна отображать сообщение об ошибке при отсутствии выбора привилегии", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф");
cy.get('input[id="tariff-amount"]').type("10");
it("должна отображать сообщение об ошибке при отсутствии выбора привилегии", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф");
cy.get('input[id="tariff-amount"]').type("10");
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get(".btn_createTariffBackend").click({ force: true });
cy.contains("Не выбрана привилегия");
});
cy.contains("Не выбрана привилегия");
});
it("Создание трех тарифов", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
it("Создание трех тарифов", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.wait(5000);
});
cy.wait(5000);
});
});
describe("Форма Создания Тарифа", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
it("Удаление тарифа единично, одного за другим ", () => {
const tariffNamesToFind = ["Тестовый Тариф 1", "Тестовый Тариф 2", "Тестовый Тариф 3"];
it("Удаление тарифа единично, одного за другим ", () => {
const tariffNamesToFind = ["Тестовый Тариф 1", "Тестовый Тариф 2", "Тестовый Тариф 3"];
// Поиск каждого тарифа в DataGrid
cy.wait(3000);
tariffNamesToFind.forEach((tariffName) => {
cy.get(".tariffs-data-grid").scrollIntoView().contains(tariffName).should("be.visible");
});
// Поиск каждого тарифа в DataGrid
cy.wait(3000);
tariffNamesToFind.forEach((tariffName) => {
cy.get(".tariffs-data-grid").scrollIntoView().contains(tariffName).should("be.visible");
});
const deleteTariffs = () => {
let tariffsFound = true;
const deleteTariffs = () => {
let tariffsFound = true;
cy.get(".tariffs-data-grid .MuiDataGrid-row").then(($rows) => {
const rowCount = $rows.length;
cy.get(".tariffs-data-grid .MuiDataGrid-row").then(($rows) => {
const rowCount = $rows.length;
if (rowCount === 1) {
cy.log("Тарифы не найдены. Тест завершен.");
tariffsFound = false;
}
if (rowCount === 1) {
cy.log("Тарифы не найдены. Тест завершен.");
tariffsFound = false;
}
cy.wrap($rows).each(($row) => {
// Шаг 2: В каждом элементе найдите все дивы вложенные внутрь и выберите последний див
cy.wrap($row).find("div").last().scrollIntoView().get(".delete-tariff-button").last().click({ force: true });
});
cy.wrap($rows).each(($row) => {
// Шаг 2: В каждом элементе найдите все дивы вложенные внутрь и выберите последний див
cy.wrap($row).find("div").last().scrollIntoView().get(".delete-tariff-button").last().click({ force: true });
});
cy.wait(2000);
cy.contains("Да")
.click()
.then(() => {
if (!tariffsFound) {
return;
}
cy.wait(2000);
cy.contains("Да")
.click()
.then(() => {
if (!tariffsFound) {
return;
}
cy.wait(5000);
deleteTariffs();
});
});
};
cy.wait(5000);
deleteTariffs();
});
});
};
deleteTariffs();
deleteTariffs();
// Проверяем что Дата грид тарифов пустой
cy.wait(2000);
cy.get(".tariffs-data-grid .MuiDataGrid-row").should("not.exist");
});
// Проверяем что Дата грид тарифов пустой
cy.wait(2000);
cy.get(".tariffs-data-grid .MuiDataGrid-row").should("not.exist");
});
it("Удаление тарифов массово через DataGrid", () => {
// Добавляем 3 тариффа
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
it("Удаление тарифов массово через DataGrid", () => {
// Добавляем 3 тариффа
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
// Добавляем 3 тариффа
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
// Добавляем 3 тариффа
cy.wait(3000);
cy.get(".tariffs-data-grid .PrivateSwitchBase-input").first().click({ multiple: true });
cy.wait(3000);
cy.get(".tariffs-data-grid .PrivateSwitchBase-input").first().click({ multiple: true });
// Проверить, что кнопка "Удалить" появилась
cy.wait(2000);
cy.contains("Удаление").should("be.visible");
// Проверить, что кнопка "Удалить" появилась
cy.wait(2000);
cy.contains("Удаление").should("be.visible");
// Нажать на кнопку "Удалить"
cy.contains("Удаление").click();
// Нажать на кнопку "Удалить"
cy.contains("Удаление").click();
// Подтверждение удаления (если нужно)
cy.contains("Да").click();
// Подтверждение удаления (если нужно)
cy.contains("Да").click();
// Проверяем что Дата грид тарифов пустой
cy.wait(2000);
cy.get(".tariffs-data-grid .MuiDataGrid-row").should("not.exist");
});
// Проверяем что Дата грид тарифов пустой
cy.wait(2000);
cy.get(".tariffs-data-grid .MuiDataGrid-row").should("not.exist");
});
it("Добавление тарифом в корзину", () => {
// Добавляем 3 тариффа
it("Добавление тарифом в корзину", () => {
// Добавляем 3 тариффа
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("10");
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 2");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("15");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Количество дней, в течении которых пользование сервисом безлимитно"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
// Добавляем 3 тариффа
cy.get('input[id="tariff-name"]').scrollIntoView().clear({ force: true }).type("Тестовый Тариф 3");
cy.get('input[id="tariff-amount"]').scrollIntoView().clear({ force: true }).type("20");
cy.get("#privilege-select").click();
cy.wait(800);
cy.get(`[data-cy="select-option-Обьём ПенаДиска для хранения шаблонов и результатов шаблонизации"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
// Добавляем 3 тариффа
cy.wait(3000);
cy.get(".tariffs-data-grid .PrivateSwitchBase-input").first().click({ multiple: true });
cy.wait(3000);
cy.get(".tariffs-data-grid .PrivateSwitchBase-input").first().click({ multiple: true });
// Проверить, что кнопка "Удалить" появилась
cy.wait(2000);
cy.contains("рассчитать").should("be.visible");
// Проверить, что кнопка "Удалить" появилась
cy.wait(2000);
cy.contains("рассчитать").should("be.visible");
// Нажать на кнопку "Удалить"
cy.contains("рассчитать").click();
// Нажать на кнопку "Удалить"
cy.contains("рассчитать").click();
// смотрим что в корзине ровно столько тарифом, сколько мы добовляли
cy.wait(5000);
cy.get(".MuiTable-root tbody tr").its("length").should("eq", 3);
});
// смотрим что в корзине ровно столько тарифом, сколько мы добовляли
cy.wait(5000);
cy.get(".MuiTable-root tbody tr").its("length").should("eq", 3);
});
});
describe("Определение поведения кастомной цены тарифа", () => {
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
beforeEach(() => {
cy.visit("http://localhost:3000");
cy.get('input[name="email"]').type("valid_user@example.com");
cy.get('input[name="password"]').type("valid_password");
cy.get('button[type="submit"]').click();
cy.wait(3000);
cy.url().should("include", "http://localhost:3000/users");
cy.visit("http://localhost:3000/tariffs");
});
it("Смотрим чтобы при указание кастомной цены тарифа поля суммы и Цены за ед отображались верно", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
it("Смотрим чтобы при указание кастомной цены тарифа поля суммы и Цены за ед отображались верно", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("60");
cy.get('input[id="tariff-custom-price"]').type("5");
cy.get('input[id="tariff-amount"]').type("60");
cy.get('input[id="tariff-custom-price"]').type("5");
cy.get("#privilege-select").click();
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.wait(3000);
cy.wait(3000);
// Сумму
cy.get(".tariffs-data-grid").get(`[data-field="total"]`).contains("300");
// Сумму
cy.get(".tariffs-data-grid").get(`[data-field="total"]`).contains("300");
// Проверяем цену за ед
cy.get(".tariffs-data-grid").get(`[data-field="pricePerUnit"]`).contains("5");
});
// Проверяем цену за ед
cy.get(".tariffs-data-grid").get(`[data-field="pricePerUnit"]`).contains("5");
});
it("Проверка установки цены тарифа по умолчанию при отсутствии кастомной цены", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
it("Проверка установки цены тарифа по умолчанию при отсутствии кастомной цены", () => {
cy.get('input[id="tariff-name"]').type("Тестовый Тариф 1");
cy.get('input[id="tariff-amount"]').type("80");
cy.get('input[id="tariff-amount"]').type("80");
cy.get("#privilege-select").click();
cy.get("#privilege-select").click();
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.get(`[data-cy="select-option-Количество шаблонов, которые может сделать пользователь сервиса"]`).click();
cy.get(".btn_createTariffBackend").click({ force: true });
cy.wait(3000);
cy.wait(3000);
// Сумму
cy.get(".tariffs-data-grid").get(`[data-field="total"]`).contains("0.8");
// Сумму
cy.get(".tariffs-data-grid").get(`[data-field="total"]`).contains("0.8");
// Проверяем цену за ед
cy.get(".tariffs-data-grid").get(`[data-field="pricePerUnit"]`).contains("0.01");
});
// Проверяем цену за ед
cy.get(".tariffs-data-grid").get(`[data-field="pricePerUnit"]`).contains("0.01");
});
});

9
eslint.config.js Normal file

@ -0,0 +1,9 @@
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(eslint.configs.recommended, ...tseslint.configs.recommended, {
rules: {
semi: "error",
"prefer-const": "error",
},
});

@ -1,5 +1,5 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
preset: "ts-jest",
testEnvironment: "node",
};

@ -1,84 +1,83 @@
{
"name": "adminka",
"version": "0.1.0",
"private": true,
"dependencies": {
"@date-io/dayjs": "^2.15.0",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@frontend/kitui": "^1.0.82",
"@material-ui/pickers": "^3.3.10",
"@mui/icons-material": "^5.10.3",
"@mui/material": "^5.10.5",
"@mui/styled-engine-sc": "^5.10.3",
"@mui/x-data-grid": "^5.17.4",
"@mui/x-data-grid-generator": "^5.17.5",
"@mui/x-data-grid-premium": "^5.17.5",
"@mui/x-date-pickers": "^5.0.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.56",
"@types/react": "^18.0.18",
"@types/react-dom": "^18.0.6",
"@types/react-router-dom": "^5.3.3",
"axios": "^1.4.0",
"craco": "^0.0.3",
"cypress": "^12.17.2",
"date-fns": "^3.3.1",
"dayjs": "^1.11.5",
"formik": "^2.2.9",
"immer": "^10.0.2",
"moment": "^2.29.4",
"nanoid": "^4.0.1",
"notistack": "^3.0.1",
"numeral": "^2.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13",
"react-numeral": "^1.1.1",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"reconnecting-eventsource": "^1.6.2",
"start-server-and-test": "^2.0.0",
"styled-components": "^5.3.5",
"swr": "^2.2.5",
"typescript": "^4.8.2",
"use-debounce": "^9.0.4",
"web-vitals": "^2.1.4",
"zustand": "^4.3.8"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test --env=node --transformIgnorePatterns \"node_modules/(?!@frontend)/\"",
"test:cart": "craco test src/utils/calcCart --transformIgnorePatterns \"node_modules/(?!@frontend)/\"",
"test:cypress": "start-server-and-test start http://localhost:3000 cypress",
"cypress": "cypress open",
"eject": "craco eject",
"format": "prettier . --write"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"craco-alias": "^3.0.1",
"prettier": "^3.2.5"
}
"name": "adminka",
"version": "0.1.0",
"private": true,
"type": "module",
"dependencies": {
"@date-io/dayjs": "^2.15.0",
"@emotion/react": "^11.10.4",
"@emotion/styled": "^11.10.4",
"@frontend/kitui": "^1.0.82",
"@material-ui/pickers": "^3.3.10",
"@mui/icons-material": "^5.10.3",
"@mui/material": "^5.10.5",
"@mui/styled-engine-sc": "^5.10.3",
"@mui/x-data-grid": "^5.17.4",
"@mui/x-data-grid-generator": "^5.17.5",
"@mui/x-data-grid-premium": "^5.17.5",
"@mui/x-date-pickers": "^5.0.3",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.56",
"@types/react": "^18.0.18",
"@types/react-dom": "^18.0.6",
"@types/react-router-dom": "^5.3.3",
"axios": "^1.4.0",
"craco": "^0.0.3",
"cypress": "^12.17.2",
"date-fns": "^3.3.1",
"dayjs": "^1.11.5",
"formik": "^2.2.9",
"immer": "^10.0.2",
"moment": "^2.29.4",
"nanoid": "^4.0.1",
"notistack": "^3.0.1",
"numeral": "^2.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13",
"react-numeral": "^1.1.1",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"reconnecting-eventsource": "^1.6.2",
"start-server-and-test": "^2.0.0",
"styled-components": "^5.3.5",
"swr": "^2.2.5",
"typescript": "^4.8.2",
"use-debounce": "^9.0.4",
"web-vitals": "^2.1.4",
"zustand": "^4.3.8"
},
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test --env=node --transformIgnorePatterns \"node_modules/(?!@frontend)/\"",
"test:cart": "craco test src/utils/calcCart --transformIgnorePatterns \"node_modules/(?!@frontend)/\"",
"test:cypress": "start-server-and-test start http://localhost:3000 cypress",
"cypress": "cypress open",
"eject": "craco eject",
"format": "prettier . --write",
"lint": "eslint ./src --fix"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@eslint/js": "^9.3.0",
"craco-alias": "^3.0.1",
"eslint": "^9.3.0",
"prettier": "^3.2.5",
"typescript-eslint": "^7.10.0"
}
}

@ -1,4 +1,6 @@
@font-face {
font-family: "GilroyRegular";
src: local("GilroyRegular"), url(fonts/GilroyRegular.woff) format("woff");
}
font-family: "GilroyRegular";
src:
local("GilroyRegular"),
url(fonts/GilroyRegular.woff) format("woff");
}

@ -1,22 +1,19 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="fonts.css" />
<!--
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="stylesheet" href="fonts.css" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
@ -25,12 +22,12 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
@ -40,5 +37,5 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</body>
</html>

@ -1,15 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

@ -1,44 +1,35 @@
const puppeteer = require('puppeteer');
const url = "http://localhost:3000/users";
const urlMass = ['/users','/tariffs','/discounts','/promocode','/support', '/entities'];
const puppeteer = require("puppeteer");
const url = "http://localhost:3000/users";
const urlMass = ["/users", "/tariffs", "/discounts", "/promocode", "/support", "/entities"];
jest.setTimeout(1000 * 60 * 5);
let browser;
let page;
describe('Тест', (() => {
beforeAll(async()=>{
browser = puppeteer.launch({headless:true});
page = browser.newPage();
jest.setTimeout(1000 * 60 * 5);
page.goto(url);
// Set screen size
page.setViewport({width: 1080, height: 1024});
let browser;
let page;
})
afterAll(() => browser.quit());
test('Тест меню',async () => {
// Ждем загрузки менюшек
page.waitForSelector('.menu')
// Берем все ссылки с кнопок, у которых есть класс menu и вставляем в массив
let menuLink = page.evaluate(()=>{
let menuArray = document.querySelectorAll('.menu')
let Urls = Object.values(menuArray).map(
menuItem => (
menuItem.href.slice(menuItem.href.lastIndexOf('/'))
)
)
return Urls
})
// Проверяем, какие ссылки есть в нашем массиве, а каких нет
for (let i = 0; i < menuLink.length; i++) {
expect(urlMass.find((elem)=>elem===menuLink[i])).toBe(true)
}
})
}))
describe("Тест", () => {
beforeAll(async () => {
browser = puppeteer.launch({ headless: true });
page = browser.newPage();
page.goto(url);
// Set screen size
page.setViewport({ width: 1080, height: 1024 });
});
afterAll(() => browser.quit());
test("Тест меню", async () => {
// Ждем загрузки менюшек
page.waitForSelector(".menu");
// Берем все ссылки с кнопок, у которых есть класс menu и вставляем в массив
const menuLink = page.evaluate(() => {
const menuArray = document.querySelectorAll(".menu");
const Urls = Object.values(menuArray).map((menuItem) => menuItem.href.slice(menuItem.href.lastIndexOf("/")));
return Urls;
});
// Проверяем, какие ссылки есть в нашем массиве, а каких нет
for (let i = 0; i < menuLink.length; i++) {
expect(urlMass.find((elem) => elem === menuLink[i])).toBe(true);
}
});
});

@ -1,12 +1,12 @@
const puppeteer = require('puppeteer');
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {
waitUntil: 'networkidle2',
});
await page.pdf({ path: 'hn.pdf', format: 'a4' });
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://news.ycombinator.com", {
waitUntil: "networkidle2",
});
await page.pdf({ path: "hn.pdf", format: "a4" });
await browser.close();
})();
await browser.close();
})();

@ -2,56 +2,56 @@ import axios from "axios";
const message = "Artem";
describe("tests", () => {
let statusGetTickets: number;
let dataGetTickets: {};
let statusGetMessages: number;
let dataGetMessages: [];
let statusGetTickets: number;
let dataGetTickets: {};
let statusGetMessages: number;
let dataGetMessages: [];
beforeEach(async () => {
await axios({
method: "post",
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
data: {
amt: 20,
page: 0,
status: "open",
},
}).then((result) => {
dataGetTickets = result.data;
statusGetTickets = result.status;
});
beforeEach(async () => {
await axios({
method: "post",
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
data: {
amt: 20,
page: 0,
status: "open",
},
}).then((result) => {
dataGetTickets = result.data;
statusGetTickets = result.status;
});
await axios({
method: "post",
url: process.env.REACT_APP_DOMAIN + "/heruvym/getMessages",
data: {
amt: 100,
page: 0,
srch: "",
ticket: "cgg25qsvc9gd0bq9ne7g",
},
}).then((result) => {
dataGetMessages = result.data;
statusGetMessages = result.status;
});
});
await axios({
method: "post",
url: process.env.REACT_APP_DOMAIN + "/heruvym/getMessages",
data: {
amt: 100,
page: 0,
srch: "",
ticket: "cgg25qsvc9gd0bq9ne7g",
},
}).then((result) => {
dataGetMessages = result.data;
statusGetMessages = result.status;
});
});
// добавляем сообщения тикету с id cgg25qsvc9gd0bq9ne7g , вписываем текст в переменную message и проверяем тест
test("test sending messages to tickets", () => {
expect(statusGetTickets).toEqual(200);
// проверяем кличество тикетов отсалось неизменным
expect(dataGetTickets).toMatchObject({ count: 12 });
// добавляем сообщения тикету с id cgg25qsvc9gd0bq9ne7g , вписываем текст в переменную message и проверяем тест
test("test sending messages to tickets", () => {
expect(statusGetTickets).toEqual(200);
// проверяем кличество тикетов отсалось неизменным
expect(dataGetTickets).toMatchObject({ count: 12 });
expect(statusGetMessages).toBe(200);
expect(statusGetMessages).toBe(200);
expect(dataGetMessages[dataGetMessages.length - 1]).toMatchObject({
files: [],
message: message,
request_screenshot: "",
session_id: "6421ccdad01874dcffa8b128",
shown: {},
ticket_id: "cgg25qsvc9gd0bq9ne7g",
user_id: "6421ccdad01874dcffa8b128",
});
});
expect(dataGetMessages[dataGetMessages.length - 1]).toMatchObject({
files: [],
message: message,
request_screenshot: "",
session_id: "6421ccdad01874dcffa8b128",
shown: {},
ticket_id: "cgg25qsvc9gd0bq9ne7g",
user_id: "6421ccdad01874dcffa8b128",
});
});
});

@ -3,49 +3,47 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
type Name = {
firstname: string;
secondname: string;
middlename: string;
orgname: string;
firstname: string;
secondname: string;
middlename: string;
orgname: string;
};
type Wallet = {
currency: string;
cash: number;
purchasesAmount: number;
spent: number;
money: number;
currency: string;
cash: number;
purchasesAmount: number;
spent: number;
money: number;
};
export type Account = {
_id: string;
userId: string;
cart: string[];
status: string;
isDeleted: boolean;
createdAt: string;
updatedAt: string;
deletedAt: string;
name: Name;
wallet: Wallet;
_id: string;
userId: string;
cart: string[];
status: string;
isDeleted: boolean;
createdAt: string;
updatedAt: string;
deletedAt: string;
name: Name;
wallet: Wallet;
};
const baseUrl = process.env.REACT_APP_DOMAIN + "/customer"
const baseUrl = process.env.REACT_APP_DOMAIN + "/customer";
export const getAccountInfo = async (
id: string
): Promise<[Account | null, string?]> => {
try {
const accountInfoResponse = await makeRequest<never, Account>({
url: `${baseUrl}/account/${id}`,
method: "GET",
useToken: true,
});
export const getAccountInfo = async (id: string): Promise<[Account | null, string?]> => {
try {
const accountInfoResponse = await makeRequest<never, Account>({
url: `${baseUrl}/account/${id}`,
method: "GET",
useToken: true,
});
return [accountInfoResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [accountInfoResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Не удалось получить информацию об аккаунте. ${error}`];
}
return [null, `Не удалось получить информацию об аккаунте. ${error}`];
}
};

@ -2,68 +2,58 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
import type {
LoginRequest,
RegisterRequest,
RegisterResponse,
} from "@frontend/kitui";
import type { LoginRequest, RegisterRequest, RegisterResponse } from "@frontend/kitui";
const baseUrl = process.env.REACT_APP_DOMAIN + "/auth"
const baseUrl = process.env.REACT_APP_DOMAIN + "/auth";
export const signin = async (
login: string,
password: string
): Promise<[RegisterResponse | null, string?]> => {
try {
const signinResponse = await makeRequest<LoginRequest, RegisterResponse>({
url: baseUrl + "/login",
body: { login, password },
useToken: false,
});
export const signin = async (login: string, password: string): Promise<[RegisterResponse | null, string?]> => {
try {
const signinResponse = await makeRequest<LoginRequest, RegisterResponse>({
url: baseUrl + "/login",
body: { login, password },
useToken: false,
});
return [signinResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
console.error(error)
return [null, `Ошибка авторизации. ${error}`];
}
return [signinResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
console.error(error);
return [null, `Ошибка авторизации. ${error}`];
}
};
export const register = async (
login: string,
password: string,
phoneNumber: string = "--"
login: string,
password: string,
phoneNumber: string = "--"
): Promise<[RegisterResponse | null, string?]> => {
try {
const registerResponse = await makeRequest<
RegisterRequest,
RegisterResponse
>({
url: baseUrl + "/register",
body: { login, password, phoneNumber },
useToken: false,
});
try {
const registerResponse = await makeRequest<RegisterRequest, RegisterResponse>({
url: baseUrl + "/register",
body: { login, password, phoneNumber },
useToken: false,
});
return [registerResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [registerResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка регистрации. ${error}`];
}
return [null, `Ошибка регистрации. ${error}`];
}
};
export const logout = async (): Promise<[unknown, string?]> => {
try {
const logoutResponse = await makeRequest<never, unknown>({
url: baseUrl + "/logout",
method: "post",
contentType: true,
});
try {
const logoutResponse = await makeRequest<never, unknown>({
url: baseUrl + "/logout",
method: "post",
contentType: true,
});
return [logoutResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [logoutResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка выхода из аккаунта. ${error}`];
}
return [null, `Ошибка выхода из аккаунта. ${error}`];
}
};

@ -3,243 +3,224 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
import type { Discount } from "@frontend/kitui";
import type {
CreateDiscountBody,
DiscountType,
GetDiscountResponse,
} from "@root/model/discount";
import type { CreateDiscountBody, DiscountType, GetDiscountResponse } from "@root/model/discount";
import useSWR from "swr";
import { enqueueSnackbar } from "notistack";
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
const baseUrl = process.env.REACT_APP_DOMAIN + "/price";
interface CreateDiscountParams {
purchasesAmount: number;
cartPurchasesAmount: number;
discountMinValue: number;
discountFactor: number;
discountDescription: string;
discountName: string;
/** ISO string */
startDate: string;
/** ISO string */
endDate: string;
serviceType: string;
discountType: DiscountType;
privilegeId: string;
purchasesAmount: number;
cartPurchasesAmount: number;
discountMinValue: number;
discountFactor: number;
discountDescription: string;
discountName: string;
/** ISO string */
startDate: string;
/** ISO string */
endDate: string;
serviceType: string;
discountType: DiscountType;
privilegeId: string;
}
export function createDiscountObject({
endDate,
startDate,
discountName,
cartPurchasesAmount,
discountDescription,
discountFactor,
discountMinValue,
purchasesAmount,
serviceType,
discountType,
privilegeId,
endDate,
startDate,
discountName,
cartPurchasesAmount,
discountDescription,
discountFactor,
discountMinValue,
purchasesAmount,
serviceType,
discountType,
privilegeId,
}: CreateDiscountParams) {
const discount: CreateDiscountBody = {
Name: discountName,
Layer: 1,
Description: discountDescription,
Condition: {
Period: {
From: startDate,
To: endDate,
},
User: "",
UserType: "",
Coupon: "",
Usage: 0,
PurchasesAmount: 0,
CartPurchasesAmount: 0,
Product: "",
Term: 0,
PriceFrom: 0,
Group: "",
},
Target: {
Factor: discountFactor,
TargetScope: "Sum",
Overhelm: false,
TargetGroup: "",
Products: [
{
ID: "",
Factor: 0,
Overhelm: false,
},
],
},
};
const discount: CreateDiscountBody = {
Name: discountName,
Layer: 1,
Description: discountDescription,
Condition: {
Period: {
From: startDate,
To: endDate,
},
User: "",
UserType: "",
Coupon: "",
Usage: 0,
PurchasesAmount: 0,
CartPurchasesAmount: 0,
Product: "",
Term: 0,
PriceFrom: 0,
Group: "",
},
Target: {
Factor: discountFactor,
TargetScope: "Sum",
Overhelm: false,
TargetGroup: "",
Products: [
{
ID: "",
Factor: 0,
Overhelm: false,
},
],
},
};
switch (discountType) {
case "privilege":
discount.Layer = 1;
discount.Condition.Product = privilegeId;
discount.Condition.Term = discountMinValue / 100;
discount.Target.Products = [
{
Factor: discountFactor,
ID: privilegeId,
Overhelm: false,
},
];
break;
case "service":
discount.Layer = 2;
discount.Condition.PriceFrom = discountMinValue;
discount.Condition.Group = serviceType;
discount.Target.TargetGroup = serviceType;
break;
case "cartPurchasesAmount":
discount.Layer = 3;
discount.Condition.CartPurchasesAmount = cartPurchasesAmount;
break;
case "purchasesAmount":
discount.Layer = 4;
discount.Condition.PurchasesAmount = purchasesAmount;
break;
}
switch (discountType) {
case "privilege":
discount.Layer = 1;
discount.Condition.Product = privilegeId;
discount.Condition.Term = discountMinValue / 100;
discount.Target.Products = [
{
Factor: discountFactor,
ID: privilegeId,
Overhelm: false,
},
];
break;
case "service":
discount.Layer = 2;
discount.Condition.PriceFrom = discountMinValue;
discount.Condition.Group = serviceType;
discount.Target.TargetGroup = serviceType;
break;
case "cartPurchasesAmount":
discount.Layer = 3;
discount.Condition.CartPurchasesAmount = cartPurchasesAmount;
break;
case "purchasesAmount":
discount.Layer = 4;
discount.Condition.PurchasesAmount = purchasesAmount;
break;
}
return discount;
return discount;
}
export const changeDiscount = async (
discountId: string,
discount: Discount
): Promise<[unknown, string?]> => {
try {
const changeDiscountResponse = await makeRequest<Discount, unknown>({
url: baseUrl + "/discount/" + discountId,
method: "patch",
useToken: true,
body: discount,
});
export const changeDiscount = async (discountId: string, discount: Discount): Promise<[unknown, string?]> => {
try {
const changeDiscountResponse = await makeRequest<Discount, unknown>({
url: baseUrl + "/discount/" + discountId,
method: "patch",
useToken: true,
body: discount,
});
return [changeDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [changeDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка изменения скидки. ${error}`];
}
return [null, `Ошибка изменения скидки. ${error}`];
}
};
export const createDiscount = async (
discountParams: CreateDiscountParams
): Promise<[Discount | null, string?]> => {
const discount = createDiscountObject(discountParams);
export const createDiscount = async (discountParams: CreateDiscountParams): Promise<[Discount | null, string?]> => {
const discount = createDiscountObject(discountParams);
try {
const createdDiscountResponse = await makeRequest<
CreateDiscountBody,
Discount
>({
url: baseUrl + "/discount",
method: "post",
useToken: true,
body: discount,
});
try {
const createdDiscountResponse = await makeRequest<CreateDiscountBody, Discount>({
url: baseUrl + "/discount",
method: "post",
useToken: true,
body: discount,
});
return [createdDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [createdDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка создания скидки. ${error}`];
}
return [null, `Ошибка создания скидки. ${error}`];
}
};
export const deleteDiscount = async (
discountId: string
): Promise<[Discount | null, string?]> => {
try {
const deleteDiscountResponse = await makeRequest<never, Discount>({
url: baseUrl + "/discount/" + discountId,
method: "delete",
useToken: true,
});
export const deleteDiscount = async (discountId: string): Promise<[Discount | null, string?]> => {
try {
const deleteDiscountResponse = await makeRequest<never, Discount>({
url: baseUrl + "/discount/" + discountId,
method: "delete",
useToken: true,
});
return [deleteDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [deleteDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка удаления скидки. ${error}`];
}
return [null, `Ошибка удаления скидки. ${error}`];
}
};
export const patchDiscount = async (
discountId: string,
discountParams: CreateDiscountParams
discountId: string,
discountParams: CreateDiscountParams
): Promise<[Discount | null, string?]> => {
const discount = createDiscountObject(discountParams);
const discount = createDiscountObject(discountParams);
try {
const patchDiscountResponse = await makeRequest<
CreateDiscountBody,
Discount
>({
url: baseUrl + "/discount/" + discountId,
method: "patch",
useToken: true,
body: discount,
});
try {
const patchDiscountResponse = await makeRequest<CreateDiscountBody, Discount>({
url: baseUrl + "/discount/" + discountId,
method: "patch",
useToken: true,
body: discount,
});
return [patchDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [patchDiscountResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка изменения скидки. ${error}`];
}
return [null, `Ошибка изменения скидки. ${error}`];
}
};
export const requestDiscounts = async (): Promise<
[GetDiscountResponse | null, string?]
> => {
try {
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
url: baseUrl + "/discounts",
method: "get",
useToken: true,
});
export const requestDiscounts = async (): Promise<[GetDiscountResponse | null, string?]> => {
try {
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
url: baseUrl + "/discounts",
method: "get",
useToken: true,
});
return [discountsResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [discountsResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка получения скидок. ${error}`];
}
return [null, `Ошибка получения скидок. ${error}`];
}
};
async function getDiscounts() {
try {
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
url: baseUrl + "/discounts",
method: "get",
useToken: true,
});
try {
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
url: baseUrl + "/discounts",
method: "get",
useToken: true,
});
return discountsResponse.Discounts.filter((discount) => !discount.Deprecated);
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return discountsResponse.Discounts.filter((discount) => !discount.Deprecated);
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка получения списка скидок. ${error}`);
}
throw new Error(`Ошибка получения списка скидок. ${error}`);
}
}
export function useDiscounts() {
const { data } = useSWR("discounts", getDiscounts, {
keepPreviousData: true,
suspense: true,
onError: (error) => {
if (!(error instanceof Error)) return;
const { data } = useSWR("discounts", getDiscounts, {
keepPreviousData: true,
suspense: true,
onError: (error) => {
if (!(error instanceof Error)) return;
enqueueSnackbar(error.message, { variant: "error" });
}
});
enqueueSnackbar(error.message, { variant: "error" });
},
});
return data;
return data;
}

@ -3,48 +3,43 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
type RawDetail = {
Key: string;
Value: number | string | RawDetail[];
Key: string;
Value: number | string | RawDetail[];
};
type History = {
id: string;
userId: string;
comment: string;
key: string;
rawDetails: RawDetail[];
isDeleted: boolean;
createdAt: string;
updatedAt: string;
id: string;
userId: string;
comment: string;
key: string;
rawDetails: RawDetail[];
isDeleted: boolean;
createdAt: string;
updatedAt: string;
};
type HistoryResponse = {
records: History[];
totalPages: number;
records: History[];
totalPages: number;
};
const baseUrl = process.env.REACT_APP_DOMAIN + "/customer";
const getUserHistory = async (
accountId: string,
page: number
): Promise<[HistoryResponse | null, string?]> => {
try {
const historyResponse = await makeRequest<never, HistoryResponse>({
method: "GET",
url:
baseUrl +
`/history?page=${page}&limit=${100}&accountID=${accountId}&type=payCart`,
});
const getUserHistory = async (accountId: string, page: number): Promise<[HistoryResponse | null, string?]> => {
try {
const historyResponse = await makeRequest<never, HistoryResponse>({
method: "GET",
url: baseUrl + `/history?page=${page}&limit=${100}&accountID=${accountId}&type=payCart`,
});
return [historyResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [historyResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка при получении пользователей. ${error}`];
}
return [null, `Ошибка при получении пользователей. ${error}`];
}
};
export const historyApi = {
getUserHistory,
getUserHistory,
};

@ -5,39 +5,36 @@ import { enqueueSnackbar } from "notistack";
import { historyApi } from "./requests";
export function useHistory(accountId: string) {
const [currentPage, setCurrentPage] = useState<number>(1);
const [currentPage, setCurrentPage] = useState<number>(1);
const swrResponse = useSWRInfinite(
() => `history-${currentPage}`,
async () => {
const [historyResponse, error] = await historyApi.getUserHistory(
accountId,
currentPage
);
const swrResponse = useSWRInfinite(
() => `history-${currentPage}`,
async () => {
const [historyResponse, error] = await historyApi.getUserHistory(accountId, currentPage);
if (error) {
throw new Error(error);
}
if (error) {
throw new Error(error);
}
if (!historyResponse) {
throw new Error("Empty history data");
}
if (!historyResponse) {
throw new Error("Empty history data");
}
if (currentPage < historyResponse.totalPages) {
setCurrentPage((page) => page + 1);
}
if (currentPage < historyResponse.totalPages) {
setCurrentPage((page) => page + 1);
}
return historyResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return historyResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return swrResponse;
return swrResponse;
}

@ -3,21 +3,30 @@ import { Method, ResponseType, AxiosError } from "axios";
import { clearAuthToken } from "@frontend/kitui";
import { redirect } from "react-router-dom";
interface MakeRequest { method?: Method | undefined; url: string; body?: unknown; useToken?: boolean | undefined; contentType?: boolean | undefined; responseType?: ResponseType | undefined; signal?: AbortSignal | undefined; withCredentials?: boolean | undefined; }
interface MakeRequest {
method?: Method | undefined;
url: string;
body?: unknown;
useToken?: boolean | undefined;
contentType?: boolean | undefined;
responseType?: ResponseType | undefined;
signal?: AbortSignal | undefined;
withCredentials?: boolean | undefined;
}
async function makeRequest<TRequest = unknown, TResponse = unknown> (data:MakeRequest): Promise<TResponse> {
try {
const response = await KIT.makeRequest<unknown>(data)
async function makeRequest<TRequest = unknown, TResponse = unknown>(data: MakeRequest): Promise<TResponse> {
try {
const response = await KIT.makeRequest<unknown>(data);
return response as TResponse
} catch (e) {
const error = e as AxiosError;
//@ts-ignore
if (error.response?.status === 400 && error.response?.data?.message === "refreshToken is empty") {
clearAuthToken()
redirect("/");
}
throw e
};
};
export default makeRequest;
return response as TResponse;
} catch (e) {
const error = e as AxiosError;
//@ts-ignore
if (error.response?.status === 400 && error.response?.data?.message === "refreshToken is empty") {
clearAuthToken();
redirect("/");
}
throw e;
}
}
export default makeRequest;

@ -7,85 +7,71 @@ import { Privilege } from "@frontend/kitui";
import type { TMockData } from "./roles";
type SeverPrivilegesResponse = {
templategen: CustomPrivilege[];
squiz: CustomPrivilege[];
templategen: CustomPrivilege[];
squiz: CustomPrivilege[];
};
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator";
export const getRoles = async (): Promise<[TMockData | null, string?]> => {
try {
const rolesResponse = await makeRequest<never, TMockData>({
method: "get",
url: baseUrl + "/role",
});
try {
const rolesResponse = await makeRequest<never, TMockData>({
method: "get",
url: baseUrl + "/role",
});
return [rolesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [rolesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка запроса ролей. ${error}`];
}
return [null, `Ошибка запроса ролей. ${error}`];
}
};
export const putPrivilege = async (
body: Omit<Privilege, "_id" | "updatedAt">
): Promise<[unknown, string?]> => {
try {
const putedPrivilege = await makeRequest<
Omit<Privilege, "_id" | "updatedAt">,
unknown
>({
url: baseUrl + "/privilege",
method: "put",
body,
});
export const putPrivilege = async (body: Omit<Privilege, "_id" | "updatedAt">): Promise<[unknown, string?]> => {
try {
const putedPrivilege = await makeRequest<Omit<Privilege, "_id" | "updatedAt">, unknown>({
url: baseUrl + "/privilege",
method: "put",
body,
});
return [putedPrivilege];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [putedPrivilege];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка изменения привилегии. ${error}`];
}
return [null, `Ошибка изменения привилегии. ${error}`];
}
};
export const requestServicePrivileges = async (): Promise<
[SeverPrivilegesResponse | null, string?]
> => {
try {
const privilegesResponse = await makeRequest<
never,
SeverPrivilegesResponse
>({
url: baseUrl + "/privilege/service",
method: "get",
});
export const requestServicePrivileges = async (): Promise<[SeverPrivilegesResponse | null, string?]> => {
try {
const privilegesResponse = await makeRequest<never, SeverPrivilegesResponse>({
url: baseUrl + "/privilege/service",
method: "get",
});
return [privilegesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [privilegesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка запроса привилегий. ${error}`];
}
return [null, `Ошибка запроса привилегий. ${error}`];
}
};
export const requestPrivileges = async (
signal: AbortSignal | undefined
): Promise<[CustomPrivilege[], string?]> => {
try {
const privilegesResponse = await makeRequest<never, CustomPrivilege[]>(
{
url: baseUrl + "/privilege",
method: "get",
useToken: true,
signal,
}
);
export const requestPrivileges = async (signal: AbortSignal | undefined): Promise<[CustomPrivilege[], string?]> => {
try {
const privilegesResponse = await makeRequest<never, CustomPrivilege[]>({
url: baseUrl + "/privilege",
method: "get",
useToken: true,
signal,
});
return [privilegesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [privilegesResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [[], `Ошибка запроса привилегий. ${error}`];
}
return [[], `Ошибка запроса привилегий. ${error}`];
}
};

@ -1,11 +1,11 @@
import makeRequest from "@root/api/makeRequest";
import type {
CreatePromocodeBody,
GetPromocodeListBody,
Promocode,
PromocodeList,
PromocodeStatistics,
CreatePromocodeBody,
GetPromocodeListBody,
Promocode,
PromocodeList,
PromocodeStatistics,
} from "@root/model/promocodes";
import { parseAxiosError } from "@root/utils/parse-error";
@ -14,129 +14,117 @@ import { isAxiosError } from "axios";
const baseUrl = process.env.REACT_APP_DOMAIN + "/codeword/promocode";
const getPromocodeList = async (body: GetPromocodeListBody) => {
try {
const promocodeListResponse = await makeRequest<
GetPromocodeListBody,
PromocodeList
>({
url: baseUrl + "/getList",
method: "POST",
body,
useToken: false,
});
try {
const promocodeListResponse = await makeRequest<GetPromocodeListBody, PromocodeList>({
url: baseUrl + "/getList",
method: "POST",
body,
useToken: false,
});
return promocodeListResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
return promocodeListResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
};
const createFastlink = async (id: string) => {
try {
return await makeRequest<{ id: string }, { fastlink: string }>({
url: baseUrl + "/fastlink",
method: "POST",
body: { id },
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при создании фастлинка. ${error}`);
}
try {
return await makeRequest<{ id: string }, { fastlink: string }>({
url: baseUrl + "/fastlink",
method: "POST",
body: { id },
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при создании фастлинка. ${error}`);
}
};
export const getAllPromocodes = async () => {
try {
const promocodes: Promocode[] = [];
try {
const promocodes: Promocode[] = [];
let page = 0;
while (true) {
const promocodeList = await getPromocodeList({
limit: 100,
filter: {
active: true,
},
page,
});
let page = 0;
while (true) {
const promocodeList = await getPromocodeList({
limit: 100,
filter: {
active: true,
},
page,
});
if (promocodeList.items.length === 0) break;
if (promocodeList.items.length === 0) break;
promocodes.push(...promocodeList.items);
page++;
}
promocodes.push(...promocodeList.items);
page++;
}
return promocodes;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
return promocodes;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении списка промокодов. ${error}`);
}
};
const createPromocode = async (body: CreatePromocodeBody) => {
try {
const createPromocodeResponse = await makeRequest<
CreatePromocodeBody,
Promocode
>({
url: baseUrl + "/create",
method: "POST",
body,
useToken: false,
});
try {
const createPromocodeResponse = await makeRequest<CreatePromocodeBody, Promocode>({
url: baseUrl + "/create",
method: "POST",
body,
useToken: false,
});
return createPromocodeResponse;
} catch (nativeError) {
if (
isAxiosError(nativeError) &&
nativeError.response?.data.error === "Duplicate Codeword"
) {
throw new Error(`Промокод уже существует`);
}
return createPromocodeResponse;
} catch (nativeError) {
if (isAxiosError(nativeError) && nativeError.response?.data.error === "Duplicate Codeword") {
throw new Error(`Промокод уже существует`);
}
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка создания промокода. ${error}`);
}
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка создания промокода. ${error}`);
}
};
const deletePromocode = async (id: string): Promise<void> => {
try {
await makeRequest<never, never>({
url: `${baseUrl}/${id}`,
method: "DELETE",
useToken: false,
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка удаления промокода. ${error}`);
}
try {
await makeRequest<never, never>({
url: `${baseUrl}/${id}`,
method: "DELETE",
useToken: false,
});
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка удаления промокода. ${error}`);
}
};
const getPromocodeStatistics = async (id: string, from: number, to: number) => {
try {
const promocodeStatisticsResponse = await makeRequest<
unknown,
PromocodeStatistics
>({
url: baseUrl + `/stats`,
body: {
id: id,
from: from,
to: to,
},
method: "POST",
useToken: false,
});
return promocodeStatisticsResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении статистики промокода. ${error}`);
}
try {
const promocodeStatisticsResponse = await makeRequest<unknown, PromocodeStatistics>({
url: baseUrl + `/stats`,
body: {
id: id,
from: from,
to: to,
},
method: "POST",
useToken: false,
});
return promocodeStatisticsResponse;
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
throw new Error(`Ошибка при получении статистики промокода. ${error}`);
}
};
export const promocodeApi = {
getPromocodeList,
createPromocode,
deletePromocode,
getAllPromocodes,
getPromocodeStatistics,
createFastlink,
getPromocodeList,
createPromocode,
deletePromocode,
getAllPromocodes,
getPromocodeStatistics,
createFastlink,
};

@ -3,147 +3,134 @@ import useSwr, { mutate } from "swr";
import { enqueueSnackbar } from "notistack";
import { promocodeApi } from "./requests";
import type {
CreatePromocodeBody,
PromocodeList,
} from "@root/model/promocodes";
import type { CreatePromocodeBody, PromocodeList } from "@root/model/promocodes";
export function usePromocodes(
page: number,
pageSize: number,
promocodeId: string,
to: number,
from: number
) {
const promocodesCountRef = useRef<number>(0);
const swrResponse = useSwr(
["promocodes", page, pageSize],
async (key) => {
const result = await promocodeApi.getPromocodeList({
limit: key[2],
filter: {
active: true,
},
page: key[1],
});
export function usePromocodes(page: number, pageSize: number, promocodeId: string, to: number, from: number) {
const promocodesCountRef = useRef<number>(0);
const swrResponse = useSwr(
["promocodes", page, pageSize],
async (key) => {
const result = await promocodeApi.getPromocodeList({
limit: key[2],
filter: {
active: true,
},
page: key[1],
});
promocodesCountRef.current = result.count;
return result;
},
{
onError(err) {
console.error("Error fetching promocodes", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
promocodesCountRef.current = result.count;
return result;
},
{
onError(err) {
console.error("Error fetching promocodes", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
const createPromocode = useCallback(
async function (body: CreatePromocodeBody) {
try {
await promocodeApi.createPromocode(body);
mutate(["promocodes", page, pageSize]);
} catch (error) {
console.error("Error creating promocode", error);
if (error instanceof Error)
enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
const createPromocode = useCallback(
async function (body: CreatePromocodeBody) {
try {
await promocodeApi.createPromocode(body);
mutate(["promocodes", page, pageSize]);
} catch (error) {
console.error("Error creating promocode", error);
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
const deletePromocode = useCallback(
async function (id: string) {
try {
await mutate<PromocodeList | undefined, void>(
["promocodes", page, pageSize],
promocodeApi.deletePromocode(id),
{
optimisticData(currentData, displayedData) {
if (!displayedData) return;
const deletePromocode = useCallback(
async function (id: string) {
try {
await mutate<PromocodeList | undefined, void>(
["promocodes", page, pageSize],
promocodeApi.deletePromocode(id),
{
optimisticData(currentData, displayedData) {
if (!displayedData) return;
return {
count: displayedData.count - 1,
items: displayedData.items.filter((item) => item.id !== id),
};
},
rollbackOnError: true,
populateCache(result, currentData) {
if (!currentData) return;
return {
count: displayedData.count - 1,
items: displayedData.items.filter((item) => item.id !== id),
};
},
rollbackOnError: true,
populateCache(result, currentData) {
if (!currentData) return;
return {
count: currentData.count - 1,
items: currentData.items.filter((item) => item.id !== id),
};
},
}
);
} catch (error) {
console.error("Error deleting promocode", error);
if (error instanceof Error)
enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
return {
count: currentData.count - 1,
items: currentData.items.filter((item) => item.id !== id),
};
},
}
);
} catch (error) {
console.error("Error deleting promocode", error);
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
const promocodeStatistics = useSwr(
["promocodeStatistics", promocodeId, from, to],
async ([_, id, from, to]) => {
if (!id) {
return null;
}
const promocodeStatistics = useSwr(
["promocodeStatistics", promocodeId, from, to],
async ([_, id, from, to]) => {
if (!id) {
return null;
}
const promocodeStatisticsResponse =
await promocodeApi.getPromocodeStatistics(id, from, to);
const promocodeStatisticsResponse = await promocodeApi.getPromocodeStatistics(id, from, to);
return promocodeStatisticsResponse;
},
{
onError(err) {
console.error("Error fetching promocode statistics", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return promocodeStatisticsResponse;
},
{
onError(err) {
console.error("Error fetching promocode statistics", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
const createFastLink = useCallback(
async function (id: string) {
try {
await promocodeApi.createFastlink(id);
mutate(["promocodes", page, pageSize]);
} catch (error) {
console.error("Error creating fast link", error);
if (error instanceof Error)
enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
const createFastLink = useCallback(
async function (id: string) {
try {
await promocodeApi.createFastlink(id);
mutate(["promocodes", page, pageSize]);
} catch (error) {
console.error("Error creating fast link", error);
if (error instanceof Error) enqueueSnackbar(error.message, { variant: "error" });
}
},
[page, pageSize]
);
return {
...swrResponse,
createPromocode,
deletePromocode,
createFastLink,
promocodeStatistics: promocodeStatistics.data,
promocodesCount: promocodesCountRef.current,
};
return {
...swrResponse,
createPromocode,
deletePromocode,
createFastLink,
promocodeStatistics: promocodeStatistics.data,
promocodesCount: promocodesCountRef.current,
};
}
export function useAllPromocodes() {
const { data } = useSwr("allPromocodes", promocodeApi.getAllPromocodes, {
keepPreviousData: true,
suspense: true,
onError(err) {
console.error("Error fetching all promocodes", err);
enqueueSnackbar(err.message, { variant: "error" });
},
});
const { data } = useSwr("allPromocodes", promocodeApi.getAllPromocodes, {
keepPreviousData: true,
suspense: true,
onError(err) {
console.error("Error fetching all promocodes", err);
enqueueSnackbar(err.message, { variant: "error" });
},
});
return data;
return data;
}

@ -1,89 +1,77 @@
import makeRequest from "@root/api/makeRequest";
import type {
GetStatisticSchildBody,
QuizStatisticsItem,
GetPromocodeStatisticsBody,
AllPromocodeStatistics,
GetStatisticSchildBody,
QuizStatisticsItem,
GetPromocodeStatisticsBody,
AllPromocodeStatistics,
} from "./types";
export type QuizStatisticResponse = {
Registrations: number;
Quizes: number;
Results: number;
Registrations: number;
Quizes: number;
Results: number;
};
type TRequest = {
to: number;
from: number;
to: number;
from: number;
};
export const getStatistic = async (
to: number,
from: number
): Promise<QuizStatisticResponse> => {
try {
const generalResponse = await makeRequest<TRequest, QuizStatisticResponse>({
url: `${process.env.REACT_APP_DOMAIN}/squiz/statistic`,
body: { to, from },
});
return generalResponse;
} catch (nativeError) {
return { Registrations: 0, Quizes: 0, Results: 0 };
}
export const getStatistic = async (to: number, from: number): Promise<QuizStatisticResponse> => {
try {
const generalResponse = await makeRequest<TRequest, QuizStatisticResponse>({
url: `${process.env.REACT_APP_DOMAIN}/squiz/statistic`,
body: { to, from },
});
return generalResponse;
} catch (nativeError) {
return { Registrations: 0, Quizes: 0, Results: 0 };
}
};
export const getStatisticSchild = async (
from: number,
to: number
): Promise<QuizStatisticsItem[]> => {
try {
const StatisticResponse = await makeRequest<
GetStatisticSchildBody,
QuizStatisticsItem[]
>({
url: process.env.REACT_APP_DOMAIN + "/customer/quizlogo/stat",
method: "post",
useToken: true,
body: { to, from, page: 0, limit: 100 },
});
export const getStatisticSchild = async (from: number, to: number): Promise<QuizStatisticsItem[]> => {
try {
const StatisticResponse = await makeRequest<GetStatisticSchildBody, QuizStatisticsItem[]>({
url: process.env.REACT_APP_DOMAIN + "/customer/quizlogo/stat",
method: "post",
useToken: true,
body: { to, from, page: 0, limit: 100 },
});
if (!StatisticResponse) {
throw new Error("Статистика не найдена");
}
if (!StatisticResponse) {
throw new Error("Статистика не найдена");
}
return StatisticResponse;
} catch (nativeError) {
return [
{
ID: "0",
Regs: 0,
Money: 0,
Quizes: [{ QuizID: "0", Regs: 0, Money: 0 }],
},
];
}
return StatisticResponse;
} catch (nativeError) {
return [
{
ID: "0",
Regs: 0,
Money: 0,
Quizes: [{ QuizID: "0", Regs: 0, Money: 0 }],
},
];
}
};
export const getStatisticPromocode = async (
from: number,
to: number
from: number,
to: number
): Promise<Record<string, AllPromocodeStatistics>> => {
try {
const StatisticPromo = await makeRequest<
GetPromocodeStatisticsBody,
Record<string, AllPromocodeStatistics>
>({
url: process.env.REACT_APP_DOMAIN + "/customer/promocode/ltv",
method: "post",
useToken: true,
body: { to, from },
});
try {
const StatisticPromo = await makeRequest<GetPromocodeStatisticsBody, Record<string, AllPromocodeStatistics>>({
url: process.env.REACT_APP_DOMAIN + "/customer/promocode/ltv",
method: "post",
useToken: true,
body: { to, from },
});
return StatisticPromo;
} catch (nativeError) {
console.log(nativeError);
return StatisticPromo;
} catch (nativeError) {
console.log(nativeError);
return {};
}
return {};
}
};

@ -1,31 +1,31 @@
import { Moment } from "moment";
export type GetStatisticSchildBody = {
to: Moment | null;
from: Moment | null;
page: number;
limit: number;
to: Moment | null;
from: Moment | null;
page: number;
limit: number;
};
type StatisticsQuizes = {
QuizID: string;
Money: number;
Regs: number;
QuizID: string;
Money: number;
Regs: number;
};
export type QuizStatisticsItem = {
ID: string;
Money: number;
Quizes: StatisticsQuizes[];
Regs: number;
ID: string;
Money: number;
Quizes: StatisticsQuizes[];
Regs: number;
};
export type GetPromocodeStatisticsBody = {
from: number;
to: number;
from: number;
to: number;
};
export type AllPromocodeStatistics = {
Money: number;
Regs: number;
Money: number;
Regs: number;
};

@ -3,59 +3,59 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
export const MOCK_DATA_USERS = [
{
key: 0,
id: "someid1",
name: "admin",
desc: "Администратор сервиса",
},
{
key: 1,
id: "someid2",
name: "manager",
desc: "Менеджер сервиса",
},
{
key: 2,
id: "someid3",
name: "user",
desc: "Пользователь сервиса",
},
{
key: 0,
id: "someid1",
name: "admin",
desc: "Администратор сервиса",
},
{
key: 1,
id: "someid2",
name: "manager",
desc: "Менеджер сервиса",
},
{
key: 2,
id: "someid3",
name: "user",
desc: "Пользователь сервиса",
},
];
export type TMockData = typeof MOCK_DATA_USERS;
export type UserType = {
_id: string;
login: string;
email: string;
phoneNumber: string;
isDeleted: boolean;
createdAt: string;
updatedAt: string;
_id: string;
login: string;
email: string;
phoneNumber: string;
isDeleted: boolean;
createdAt: string;
updatedAt: string;
};
const baseUrl =process.env.REACT_APP_DOMAIN + "/role"
const baseUrl = process.env.REACT_APP_DOMAIN + "/role";
export const getRoles_mock = (): Promise<TMockData> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(MOCK_DATA_USERS);
}, 1000);
});
return new Promise((resolve) => {
setTimeout(() => {
resolve(MOCK_DATA_USERS);
}, 1000);
});
};
export const deleteRole = async (id: string): Promise<[unknown, string?]> => {
try {
const deleteRoleResponse = await makeRequest({
url: `${baseUrl}/${id}`,
method: "delete",
});
try {
const deleteRoleResponse = await makeRequest({
url: `${baseUrl}/${id}`,
method: "delete",
});
return [deleteRoleResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [deleteRoleResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка удаления роли. ${error}`];
}
return [null, `Ошибка удаления роли. ${error}`];
}
};

@ -7,95 +7,87 @@ import type { Tariff } from "@frontend/kitui";
import type { EditTariffRequestBody } from "@root/model/tariff";
type CreateTariffBackendRequest = {
name: string;
description: string;
order: number;
price: number;
isCustom: boolean;
privileges: Omit<Privilege, "_id" | "updatedAt">[];
name: string;
description: string;
order: number;
price: number;
isCustom: boolean;
privileges: Omit<Privilege, "_id" | "updatedAt">[];
};
type GetTariffsResponse = {
totalPages: number;
tariffs: Tariff[];
totalPages: number;
tariffs: Tariff[];
};
const baseUrl =process.env.REACT_APP_DOMAIN + "/strator"
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator";
export const createTariff = async (
body: CreateTariffBackendRequest
): Promise<[unknown, string?]> => {
try {
const createdTariffResponse = await makeRequest<CreateTariffBackendRequest>(
{
url: baseUrl + "/tariff/",
method: "post",
body,
}
);
export const createTariff = async (body: CreateTariffBackendRequest): Promise<[unknown, string?]> => {
try {
const createdTariffResponse = await makeRequest<CreateTariffBackendRequest>({
url: baseUrl + "/tariff/",
method: "post",
body,
});
return [createdTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [createdTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка создания тарифа. ${error}`];
}
return [null, `Ошибка создания тарифа. ${error}`];
}
};
export const putTariff = async (tariff: Tariff): Promise<[null, string?]> => {
try {
const putedTariffResponse = await makeRequest<EditTariffRequestBody, null>({
method: "put",
url: baseUrl + `/tariff/${tariff._id}`,
body: {
name: tariff.name,
price: tariff.price ?? 0,
isCustom: false,
order: tariff.order || 1,
description: tariff.description ?? "",
privileges: tariff.privileges,
},
});
try {
const putedTariffResponse = await makeRequest<EditTariffRequestBody, null>({
method: "put",
url: baseUrl + `/tariff/${tariff._id}`,
body: {
name: tariff.name,
price: tariff.price ?? 0,
isCustom: false,
order: tariff.order || 1,
description: tariff.description ?? "",
privileges: tariff.privileges,
},
});
return [putedTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [putedTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка редактирования тарифа. ${error}`];
}
return [null, `Ошибка редактирования тарифа. ${error}`];
}
};
export const deleteTariff = async (
tariffId: string
): Promise<[Tariff | null, string?]> => {
try {
const deletedTariffResponse = await makeRequest<{ id: string }, Tariff>({
method: "delete",
url: baseUrl + "/tariff",
body: { id: tariffId },
});
export const deleteTariff = async (tariffId: string): Promise<[Tariff | null, string?]> => {
try {
const deletedTariffResponse = await makeRequest<{ id: string }, Tariff>({
method: "delete",
url: baseUrl + "/tariff",
body: { id: tariffId },
});
return [deletedTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [deletedTariffResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка удаления тарифа. ${error}`];
}
return [null, `Ошибка удаления тарифа. ${error}`];
}
};
export const requestTariffs = async (
page: number
): Promise<[GetTariffsResponse | null, string?]> => {
try {
const tariffsResponse = await makeRequest<never, GetTariffsResponse>({
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
method: "get",
});
export const requestTariffs = async (page: number): Promise<[GetTariffsResponse | null, string?]> => {
try {
const tariffsResponse = await makeRequest<never, GetTariffsResponse>({
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
method: "get",
});
return [tariffsResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [tariffsResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка запроса тарифов. ${error}`];
}
return [null, `Ошибка запроса тарифов. ${error}`];
}
};

@ -4,26 +4,21 @@ import { parseAxiosError } from "@root/utils/parse-error";
import type { SendTicketMessageRequest } from "@root/model/ticket";
const baseUrl = process.env.REACT_APP_DOMAIN + "/heruvym"
const baseUrl = process.env.REACT_APP_DOMAIN + "/heruvym";
export const sendTicketMessage = async (
body: SendTicketMessageRequest
): Promise<[unknown, string?]> => {
try {
const sendTicketMessageResponse = await makeRequest<
SendTicketMessageRequest,
unknown
>({
url: `${baseUrl}/send`,
method: "POST",
useToken: true,
body,
});
export const sendTicketMessage = async (body: SendTicketMessageRequest): Promise<[unknown, string?]> => {
try {
const sendTicketMessageResponse = await makeRequest<SendTicketMessageRequest, unknown>({
url: `${baseUrl}/send`,
method: "POST",
useToken: true,
body,
});
return [sendTicketMessageResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [sendTicketMessageResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка отправки сообщения. ${error}`];
}
return [null, `Ошибка отправки сообщения. ${error}`];
}
};

@ -5,85 +5,76 @@ import { parseAxiosError } from "@root/utils/parse-error";
import type { UserType } from "@root/api/roles";
export type UsersListResponse = {
totalPages: number;
users: UserType[];
totalPages: number;
users: UserType[];
};
const baseUrl = process.env.REACT_APP_DOMAIN + "/user";
const getUserInfo = async (id: string): Promise<[UserType | null, string?]> => {
try {
const userInfoResponse = await makeRequest<never, UserType>({
url: `${baseUrl}/${id}`,
method: "GET",
useToken: true,
});
try {
const userInfoResponse = await makeRequest<never, UserType>({
url: `${baseUrl}/${id}`,
method: "GET",
useToken: true,
});
return [userInfoResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [userInfoResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка получения информации о пользователе. ${error}`];
}
return [null, `Ошибка получения информации о пользователе. ${error}`];
}
};
const getUserList = async (
page = 1,
limit = 10
): Promise<[UsersListResponse | null, string?]> => {
try {
const userResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
const getUserList = async (page = 1, limit = 10): Promise<[UsersListResponse | null, string?]> => {
try {
const userResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
return [userResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [userResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка при получении пользователей. ${error}`];
}
return [null, `Ошибка при получении пользователей. ${error}`];
}
};
const getManagerList = async (
page = 1,
limit = 10
): Promise<[UsersListResponse | null, string?]> => {
try {
const managerResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
const getManagerList = async (page = 1, limit = 10): Promise<[UsersListResponse | null, string?]> => {
try {
const managerResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
return [managerResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [managerResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка при получении менеджеров. ${error}`];
}
return [null, `Ошибка при получении менеджеров. ${error}`];
}
};
const getAdminList = async (
page = 1,
limit = 10
): Promise<[UsersListResponse | null, string?]> => {
try {
const adminResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
const getAdminList = async (page = 1, limit = 10): Promise<[UsersListResponse | null, string?]> => {
try {
const adminResponse = await makeRequest<never, UsersListResponse>({
method: "get",
url: baseUrl + `/?page=${page}&limit=${limit}`,
});
return [adminResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [adminResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка при получении админов. ${error}`];
}
return [null, `Ошибка при получении админов. ${error}`];
}
};
export const userApi = {
getUserInfo,
getUserList,
getManagerList,
getAdminList,
getUserInfo,
getUserList,
getManagerList,
getAdminList,
};

@ -5,100 +5,94 @@ import { enqueueSnackbar } from "notistack";
import { userApi } from "./requests";
export function useAdmins(page: number, pageSize: number) {
const adminPagesRef = useRef<number>(0);
const adminPagesRef = useRef<number>(0);
const swrResponse = useSwr(
["admin", page, pageSize],
async ([_, page, pageSize]) => {
const [adminResponse, error] = await userApi.getManagerList(
page,
pageSize
);
const swrResponse = useSwr(
["admin", page, pageSize],
async ([_, page, pageSize]) => {
const [adminResponse, error] = await userApi.getManagerList(page, pageSize);
if (error) {
throw new Error(error);
}
if (error) {
throw new Error(error);
}
adminPagesRef.current = adminResponse?.totalPages || 1;
return adminResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
adminPagesRef.current = adminResponse?.totalPages || 1;
return adminResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return {
...swrResponse,
adminPages: adminPagesRef.current,
};
return {
...swrResponse,
adminPages: adminPagesRef.current,
};
}
export function useManagers(page: number, pageSize: number) {
const managerPagesRef = useRef<number>(0);
const managerPagesRef = useRef<number>(0);
const swrResponse = useSwr(
["manager", page, pageSize],
async ([_, page, pageSize]) => {
const [managerResponse, error] = await userApi.getManagerList(
page,
pageSize
);
const swrResponse = useSwr(
["manager", page, pageSize],
async ([_, page, pageSize]) => {
const [managerResponse, error] = await userApi.getManagerList(page, pageSize);
if (error) {
throw new Error(error);
}
if (error) {
throw new Error(error);
}
managerPagesRef.current = managerResponse?.totalPages || 1;
return managerResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
managerPagesRef.current = managerResponse?.totalPages || 1;
return managerResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return {
...swrResponse,
managerPages: managerPagesRef.current,
};
return {
...swrResponse,
managerPages: managerPagesRef.current,
};
}
export function useUsers(page: number, pageSize: number) {
const userPagesRef = useRef<number>(0);
const userPagesRef = useRef<number>(0);
const swrResponse = useSwr(
["users", page, pageSize],
async ([_, page, pageSize]) => {
const [userResponse, error] = await userApi.getUserList(page, pageSize);
const swrResponse = useSwr(
["users", page, pageSize],
async ([_, page, pageSize]) => {
const [userResponse, error] = await userApi.getUserList(page, pageSize);
if (error) {
throw new Error(error);
}
if (error) {
throw new Error(error);
}
userPagesRef.current = userResponse?.totalPages || 1;
return userResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
userPagesRef.current = userResponse?.totalPages || 1;
return userResponse;
},
{
onError(err) {
console.error("Error fetching users", err);
enqueueSnackbar(err.message, { variant: "error" });
},
focusThrottleInterval: 60e3,
keepPreviousData: true,
}
);
return {
...swrResponse,
userPagesCount: userPagesRef.current,
};
return {
...swrResponse,
userPagesCount: userPagesRef.current,
};
}

@ -3,65 +3,58 @@ import makeRequest from "@root/api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
type File = {
name: "inn" | "rule" | "egrule" | "certificate";
url: string;
name: "inn" | "rule" | "egrule" | "certificate";
url: string;
};
export type Verification = {
_id: string;
accepted: boolean;
status: "org" | "nko";
updated_at: string;
comment: string;
taxnumber: string;
files: File[];
_id: string;
accepted: boolean;
status: "org" | "nko";
updated_at: string;
comment: string;
taxnumber: string;
files: File[];
};
type PatchVerificationBody = {
id?: string;
status?: "org" | "nko";
comment?: string;
accepted?: boolean;
taxnumber?: string;
id?: string;
status?: "org" | "nko";
comment?: string;
accepted?: boolean;
taxnumber?: string;
};
const baseUrl = process.env.REACT_APP_DOMAIN + "/verification"
const baseUrl = process.env.REACT_APP_DOMAIN + "/verification";
export const verification = async (
userId: string
): Promise<[Verification | null, string?]> => {
try {
const verificationResponse = await makeRequest<never, Verification>({
method: "get",
url: baseUrl + `/verification/${userId}`,
});
export const verification = async (userId: string): Promise<[Verification | null, string?]> => {
try {
const verificationResponse = await makeRequest<never, Verification>({
method: "get",
url: baseUrl + `/verification/${userId}`,
});
return [verificationResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [verificationResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка верификации. ${error}`];
}
return [null, `Ошибка верификации. ${error}`];
}
};
export const patchVerification = async (
body: PatchVerificationBody
): Promise<[unknown, string?]> => {
try {
const patchedVerificationResponse = await makeRequest<
PatchVerificationBody,
unknown
>({
method: "patch",
useToken: true,
url: baseUrl + `/verification`,
body,
});
export const patchVerification = async (body: PatchVerificationBody): Promise<[unknown, string?]> => {
try {
const patchedVerificationResponse = await makeRequest<PatchVerificationBody, unknown>({
method: "patch",
useToken: true,
url: baseUrl + `/verification`,
body,
});
return [patchedVerificationResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [patchedVerificationResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Ошибка изменения верификации. ${error}`];
}
return [null, `Ошибка изменения верификации. ${error}`];
}
};

@ -1,4 +1,6 @@
@font-face {
font-family: "GilroyRegular";
src: local("GilroyRegular"), url(./fonts/GilroyRegular.woff) format("woff");
}
font-family: "GilroyRegular";
src:
local("GilroyRegular"),
url(./fonts/GilroyRegular.woff) format("woff");
}

@ -2,18 +2,18 @@ import React from "react";
import { Box, Typography } from "@mui/material";
type ArticleProps = {
header: JSX.Element;
body: JSX.Element;
isBoby?: boolean;
header: JSX.Element;
body: JSX.Element;
isBoby?: boolean;
};
export const Article = ({ header, body, isBoby = false }: ArticleProps) => {
return (
<Box component="section">
<Box>
<Typography variant="h1">{header}</Typography>
</Box>
{isBoby ? <Box>{body}</Box> : <React.Fragment />}
</Box>
);
return (
<Box component="section">
<Box>
<Typography variant="h1">{header}</Typography>
</Box>
{isBoby ? <Box>{body}</Box> : <React.Fragment />}
</Box>
);
};

@ -1,20 +1,20 @@
import { calcCart } from "@frontend/kitui";
import Input from "@kitUI/input";
import {
Alert,
Box,
Button,
Checkbox,
FormControlLabel,
Paper,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
useMediaQuery,
useTheme
Alert,
Box,
Button,
Checkbox,
FormControlLabel,
Paper,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import { useDiscounts } from "@root/api/discounts";
import { useAllPromocodes } from "@root/api/promocode/swr";
@ -27,249 +27,237 @@ import { currencyFormatter } from "@root/utils/currencyFormatter";
import { useState } from "react";
import CartItemRow from "./CartItemRow";
export default function Cart() {
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(400));
const discounts = useDiscounts();
const promocodes = useAllPromocodes();
const cartData = useCartStore((store) => store.cartData);
const tariffs = useTariffStore(state => state.tariffs);
const [couponField, setCouponField] = useState<string>("");
const [loyaltyField, setLoyaltyField] = useState<string>("");
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(400));
const discounts = useDiscounts();
const promocodes = useAllPromocodes();
const cartData = useCartStore((store) => store.cartData);
const tariffs = useTariffStore((state) => state.tariffs);
const [couponField, setCouponField] = useState<string>("");
const [loyaltyField, setLoyaltyField] = useState<string>("");
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
const selectedTariffIds = useTariffStore((state) => state.selectedTariffIds);
async function handleCalcCartClick() {
await requestPrivileges();
await requestDiscounts();
async function handleCalcCartClick() {
await requestPrivileges();
await requestDiscounts();
const cartTariffs = tariffs.filter(tariff => selectedTariffIds.includes(tariff._id));
const cartTariffs = tariffs.filter((tariff) => selectedTariffIds.includes(tariff._id));
let loyaltyValue = parseInt(loyaltyField);
let loyaltyValue = parseInt(loyaltyField);
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
const promocode = promocodes.find(promocode => {
if (promocode.dueTo < (Date.now() / 1000)) return false;
const promocode = promocodes.find((promocode) => {
if (promocode.dueTo < Date.now() / 1000) return false;
return promocode.codeword === couponField.trim();
});
return promocode.codeword === couponField.trim();
});
const userId = crypto.randomUUID();
const userId = crypto.randomUUID();
const discountsWithPromocodeDiscount = promocode ? [
...discounts,
createDiscountFromPromocode(promocode, userId),
] : discounts;
const discountsWithPromocodeDiscount = promocode
? [...discounts, createDiscountFromPromocode(promocode, userId)]
: discounts;
try {
const cartData = calcCart(cartTariffs, discountsWithPromocodeDiscount, loyaltyValue, userId);
try {
const cartData = calcCart(cartTariffs, discountsWithPromocodeDiscount, loyaltyValue, userId);
setErrorMessage(null);
setCartData(cartData);
} catch (error: any) {
setErrorMessage(error.message);
setCartData(null);
}
}
setErrorMessage(null);
setCartData(cartData);
} catch (error: any) {
setErrorMessage(error.message);
setCartData(null);
}
}
return (
<Box
component="section"
sx={{
border: "1px solid white",
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
pb: "20px",
borderRadius: "4px",
}}
>
<Typography variant="caption">корзина</Typography>
<Paper
variant="bar"
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "20px",
flexDirection: mobile ? "column" : undefined
}}
>
<FormControlLabel
checked={isNonCommercial}
onChange={(e, checked) => setIsNonCommercial(checked)}
control={
<Checkbox
sx={{
color: theme.palette.secondary.main,
"&.Mui-checked": {
color: theme.palette.secondary.main,
},
}}
/>
}
label="НКО"
sx={{
color: theme.palette.secondary.main,
}}
/>
<Box
sx={{
border: "1px solid white",
padding: "3px",
display: "flex",
flexDirection: "column",
}}
>
<Input
label="промокод"
size="small"
value={couponField}
onChange={(e) => setCouponField(e.target.value)}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</Box>
{/* {cartTotal?.couponState &&
return (
<Box
component="section"
sx={{
border: "1px solid white",
display: "flex",
flexDirection: "column",
alignItems: "center",
width: "100%",
pb: "20px",
borderRadius: "4px",
}}
>
<Typography variant="caption">корзина</Typography>
<Paper
variant="bar"
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "20px",
flexDirection: mobile ? "column" : undefined,
}}
>
<FormControlLabel
checked={isNonCommercial}
onChange={(e, checked) => setIsNonCommercial(checked)}
control={
<Checkbox
sx={{
color: theme.palette.secondary.main,
"&.Mui-checked": {
color: theme.palette.secondary.main,
},
}}
/>
}
label="НКО"
sx={{
color: theme.palette.secondary.main,
}}
/>
<Box
sx={{
border: "1px solid white",
padding: "3px",
display: "flex",
flexDirection: "column",
}}
>
<Input
label="промокод"
size="small"
value={couponField}
onChange={(e) => setCouponField(e.target.value)}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</Box>
{/* {cartTotal?.couponState &&
(cartTotal.couponState === "applied" ? (
<Alert severity="success">Купон применен!</Alert>
) : (
<Alert severity="error">Подходящий купон не найден!</Alert>
))
} */}
<Box
sx={{
border: "1px solid white",
padding: "3px",
display: "flex",
flexDirection: "column",
ml: mobile ? 0 : "auto",
}}
>
<Input
label="лояльность"
size="small"
type="number"
value={loyaltyField}
onChange={(e) => setLoyaltyField(e.target.value)}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</Box>
<Button onClick={handleCalcCartClick}>рассчитать</Button>
</Paper>
<Box
sx={{
border: "1px solid white",
padding: "3px",
display: "flex",
flexDirection: "column",
ml: mobile ? 0 : "auto",
}}
>
<Input
label="лояльность"
size="small"
type="number"
value={loyaltyField}
onChange={(e) => setLoyaltyField(e.target.value)}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</Box>
<Button onClick={handleCalcCartClick}>рассчитать</Button>
</Paper>
{cartData?.services.length && (
<>
<Table
sx={{
width: "90%",
margin: "5px",
border: "2px solid",
borderColor: theme.palette.secondary.main,
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography
variant="h4"
sx={{ color: theme.palette.secondary.main }}
>
Имя
</Typography>
</TableCell>
<TableCell>
<Typography
variant="h4"
sx={{ color: theme.palette.secondary.main }}
>
Описание
</Typography>
</TableCell>
<TableCell>
<Typography
variant="h4"
sx={{ color: theme.palette.secondary.main }}
>
Скидки
</Typography>
</TableCell>
<TableCell>
<Typography
variant="h4"
sx={{ color: theme.palette.secondary.main }}
>
стоимость
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{cartData.services.flatMap(service => service.tariffs.map(tariffCartData => {
const appliedDiscounts = tariffCartData.privileges.flatMap(
privilege => Array.from(privilege.appliedDiscounts)
).sort((a, b) => a.Layer - b.Layer);
{cartData?.services.length && (
<>
<Table
sx={{
width: "90%",
margin: "5px",
border: "2px solid",
borderColor: theme.palette.secondary.main,
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
Имя
</Typography>
</TableCell>
<TableCell>
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
Описание
</Typography>
</TableCell>
<TableCell>
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
Скидки
</Typography>
</TableCell>
<TableCell>
<Typography variant="h4" sx={{ color: theme.palette.secondary.main }}>
стоимость
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{cartData.services.flatMap((service) =>
service.tariffs.map((tariffCartData) => {
const appliedDiscounts = tariffCartData.privileges
.flatMap((privilege) => Array.from(privilege.appliedDiscounts))
.sort((a, b) => a.Layer - b.Layer);
return (
<CartItemRow
key={tariffCartData.id}
tariffCartData={tariffCartData}
appliedDiscounts={appliedDiscounts}
/>
);
}))}
</TableBody>
</Table>
return (
<CartItemRow
key={tariffCartData.id}
tariffCartData={tariffCartData}
appliedDiscounts={appliedDiscounts}
/>
);
})
)}
</TableBody>
</Table>
<Typography
id="transition-modal-title"
variant="h6"
sx={{
fontWeight: "normal",
textAlign: "center",
marginTop: "10px",
}}
>
ИТОГО: <span>{currencyFormatter.format(cartData.priceAfterDiscounts / 100)}</span>
</Typography>
</>
)}
<Typography
id="transition-modal-title"
variant="h6"
sx={{
fontWeight: "normal",
textAlign: "center",
marginTop: "10px",
}}
>
ИТОГО: <span>{currencyFormatter.format(cartData.priceAfterDiscounts / 100)}</span>
</Typography>
</>
)}
{errorMessage !== null && (
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
{errorMessage}
</Alert>
)}
</Box>
);
{errorMessage !== null && (
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
{errorMessage}
</Alert>
)}
</Box>
);
}

@ -4,51 +4,42 @@ import { Discount, TariffCartData } from "@frontend/kitui";
import { currencyFormatter } from "@root/utils/currencyFormatter";
import { useEffect } from "react";
interface Props {
tariffCartData: TariffCartData;
appliedDiscounts: Discount[];
tariffCartData: TariffCartData;
appliedDiscounts: Discount[];
}
export default function CartItemRow({ tariffCartData, appliedDiscounts }: Props) {
const theme = useTheme();
const theme = useTheme();
useEffect(() => {
if (tariffCartData.privileges.length > 1) {
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
}
}, [tariffCartData.id, tariffCartData.name, tariffCartData.privileges.length]);
useEffect(() => {
if (tariffCartData.privileges.length > 1) {
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
}
}, [tariffCartData.id, tariffCartData.name, tariffCartData.privileges.length]);
return (
<TableRow
key={tariffCartData.id}
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
".MuiTableCell-root": {
color: theme.palette.secondary.main,
}
}}
>
<TableCell>
{tariffCartData.name}
</TableCell>
<TableCell>
{tariffCartData.privileges[0].description}
</TableCell>
<TableCell>
{appliedDiscounts.map((discount, index, arr) => (
<span key={discount.ID}>
<DiscountTooltip discount={discount} />
{index < arr.length - 1 && (
<span>,&nbsp;</span>
)}
</span>
))}
</TableCell>
<TableCell>
{currencyFormatter.format(tariffCartData.price / 100)}
</TableCell>
</TableRow>
);
return (
<TableRow
key={tariffCartData.id}
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
".MuiTableCell-root": {
color: theme.palette.secondary.main,
},
}}
>
<TableCell>{tariffCartData.name}</TableCell>
<TableCell>{tariffCartData.privileges[0].description}</TableCell>
<TableCell>
{appliedDiscounts.map((discount, index, arr) => (
<span key={discount.ID}>
<DiscountTooltip discount={discount} />
{index < arr.length - 1 && <span>,&nbsp;</span>}
</span>
))}
</TableCell>
<TableCell>{currencyFormatter.format(tariffCartData.price / 100)}</TableCell>
</TableRow>
);
}

@ -2,27 +2,26 @@ import { Tooltip, Typography } from "@mui/material";
import { Discount, findDiscountFactor } from "@frontend/kitui";
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
interface Props {
discount: Discount;
discount: Discount;
}
export function DiscountTooltip({ discount }: Props) {
const discountText = formatDiscountFactor(findDiscountFactor(discount));
const discountText = formatDiscountFactor(findDiscountFactor(discount));
return discountText ? (
<Tooltip
title={
<>
<Typography>Слой: {discount.Layer}</Typography>
<Typography>Название: {discount.Name}</Typography>
<Typography>Описание: {discount.Description}</Typography>
</>
}
>
<span>{discountText}</span>
</Tooltip>
) : (
<span>Ошибка поиска значения скидки</span>
);
return discountText ? (
<Tooltip
title={
<>
<Typography>Слой: {discount.Layer}</Typography>
<Typography>Название: {discount.Name}</Typography>
<Typography>Описание: {discount.Description}</Typography>
</>
}
>
<span>{discountText}</span>
</Tooltip>
) : (
<span>Ошибка поиска значения скидки</span>
);
}

@ -1,46 +1,55 @@
import { SxProps, TextField, Theme, useTheme } from "@mui/material";
import { HTMLInputTypeAttribute, ChangeEvent } from "react";
import {InputBaseProps} from "@mui/material/InputBase";
import { InputBaseProps } from "@mui/material/InputBase";
export function CustomTextField({ id, label, value, name, onBlur,error, type, sx, onChange: setValue }: {
id: string;
label: string;
value: number | string | null;
name?: string;
onBlur?: InputBaseProps['onBlur'];
error?: boolean;
type?: HTMLInputTypeAttribute;
sx?: SxProps<Theme>;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
export function CustomTextField({
id,
label,
value,
name,
onBlur,
error,
type,
sx,
onChange: setValue,
}: {
id: string;
label: string;
value: number | string | null;
name?: string;
onBlur?: InputBaseProps["onBlur"];
error?: boolean;
type?: HTMLInputTypeAttribute;
sx?: SxProps<Theme>;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
}) {
const theme = useTheme();
const theme = useTheme();
return (
<TextField
fullWidth
id={id}
label={label}
variant="filled"
name={name}
onBlur={onBlur}
error={error}
color="secondary"
type={type}
sx={sx}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
value={value ? value : ""}
onChange={setValue}
/>
);
}
return (
<TextField
fullWidth
id={id}
label={label}
variant="filled"
name={name}
onBlur={onBlur}
error={error}
color="secondary"
type={type}
sx={sx}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
value={value ? value : ""}
onChange={setValue}
/>
);
}

@ -3,26 +3,26 @@ import { useState } from "react";
import { Box, SxProps, Theme, Typography, useMediaQuery, useTheme } from "@mui/material";
interface CustomWrapperProps {
text: string;
sx?: SxProps<Theme>;
result?: boolean;
children: JSX.Element;
text: string;
sx?: SxProps<Theme>;
result?: boolean;
children: JSX.Element;
}
export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps) => {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const [isExpanded, setIsExpanded] = useState<boolean>(false);
return (
<Box
sx={{
width: "100%",
overflow: "hidden",
borderRadius: "12px",
boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
return (
<Box
sx={{
width: "100%",
overflow: "hidden",
borderRadius: "12px",
boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
0px 41.7776px 129.093px rgba(210, 208, 225, 0.172525),
0px 22.3363px 69.0192px rgba(210, 208, 225, 0.143066),
0px 12.5216px 38.6916px rgba(210, 208, 225, 0.12),
@ -30,99 +30,99 @@ export const CustomWrapper = ({ text, sx, result, children }: CustomWrapperProps
0px 2.76726px 8.55082px rgba(210, 208, 225, 0.067
4749)`,
...sx,
}}
>
<Box
sx={{
border: "2px solid grey",
"&:first-of-type": {
borderTopLeftRadius: "12px ",
borderTopRightRadius: "12px",
},
"&:last-of-type": {
borderBottomLeftRadius: "12px",
borderBottomRightRadius: "12px",
},
"&:not(:last-of-type)": {
borderBottom: `1px solid gray`,
},
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "88px",
px: "20px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
fontSize: "18px",
lineHeight: upMd ? undefined : "19px",
fontWeight: 400,
color: "#FFFFFF",
px: 0,
}}
>
{text}
</Typography>
...sx,
}}
>
<Box
sx={{
border: "2px solid grey",
"&:first-of-type": {
borderTopLeftRadius: "12px ",
borderTopRightRadius: "12px",
},
"&:last-of-type": {
borderBottomLeftRadius: "12px",
borderBottomRightRadius: "12px",
},
"&:not(:last-of-type)": {
borderBottom: `1px solid gray`,
},
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "88px",
px: "20px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
fontSize: "18px",
lineHeight: upMd ? undefined : "19px",
fontWeight: 400,
color: "#FFFFFF",
px: 0,
}}
>
{text}
</Typography>
<Box
sx={{
display: "flex",
height: "100%",
alignItems: "center",
}}
>
{result ? (
<>
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<Box
sx={{
display: "flex",
height: "100%",
alignItems: "center",
}}
>
{result ? (
<>
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<Box
sx={{
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
pl: upSm ? "2px" : 0,
height: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
/>
</>
) : (
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#fe9903"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</Box>
</Box>
{isExpanded && <>{children}</>}
</Box>
</Box>
);
<Box
sx={{
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
pl: upSm ? "2px" : 0,
height: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
/>
</>
) : (
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#fe9903"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</Box>
</Box>
{isExpanded && <>{children}</>}
</Box>
</Box>
);
};

@ -1,26 +1,21 @@
import { styled } from "@mui/material/styles";
import { Button, Skeleton} from "@mui/material";
import { Button, Skeleton } from "@mui/material";
const BeautifulButton = styled(Button)(({ theme }) => ({
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18,
}));
interface Props {
isReady: boolean
text:string
type?: "button" | "reset" | "submit"
isReady: boolean;
text: string;
type?: "button" | "reset" | "submit";
}
export default ({
isReady = true,
text,
type = "button"
}:Props) => {
if (isReady) {
return <BeautifulButton type={type}>{text}</BeautifulButton>
}
return <Skeleton>{text}</Skeleton>
}
export default ({ isReady = true, text, type = "button" }: Props) => {
if (isReady) {
return <BeautifulButton type={type}>{text}</BeautifulButton>;
}
return <Skeleton>{text}</Skeleton>;
};

@ -1,28 +1,27 @@
import { DataGrid } from "@mui/x-data-grid";
import { styled } from "@mui/material/styles";
export default styled(DataGrid)(({ theme }) => ({
width: "100%",
minHeight: "400px",
margin: "10px 0",
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none"
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main
},
"& .MuiButton-text": {
color: theme.palette.secondary.main
},
width: "100%",
minHeight: "400px",
margin: "10px 0",
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none",
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main,
},
"& .MuiButton-text": {
color: theme.palette.secondary.main,
},
})) as typeof DataGrid;

@ -1,16 +1,16 @@
import {TextField} from "@mui/material";
import { TextField } from "@mui/material";
import { styled } from "@mui/material/styles";
export default styled(TextField)(({ theme }) => ({
variant: "outlined",
height: "40px",
size: "small",
color: theme.palette.secondary.main,
width: "140px",
backgroundColor: theme.palette.content.main,
"& .MuiFormLabel-root": {
color: theme.palette.secondary.main,
},
"& .Mui-focused": {
color: theme.palette.secondary.main,
}
}));
variant: "outlined",
height: "40px",
size: "small",
color: theme.palette.secondary.main,
width: "140px",
backgroundColor: theme.palette.content.main,
"& .MuiFormLabel-root": {
color: theme.palette.secondary.main,
},
"& .Mui-focused": {
color: theme.palette.secondary.main,
},
}));

@ -1,18 +1,18 @@
import { styled } from "@mui/material/styles";
import { TextField } from "@mui/material";
export default styled(TextField)(({ theme }) => ({
color: theme.palette.grayLight.main,
"& .MuiInputLabel-root": {
color: theme.palette.grayLight.main,
},
"& .MuiFilledInput-root": {
border: theme.palette.grayLight.main + " 1px solid",
borderRadius: "0",
backgroundColor: theme.palette.hover.main,
color: theme.palette.grayLight.main,
},
color: theme.palette.grayLight.main,
"& .MuiInputLabel-root": {
color: theme.palette.grayLight.main,
},
"& .MuiFilledInput-root": {
border: theme.palette.grayLight.main + " 1px solid",
borderRadius: "0",
backgroundColor: theme.palette.hover.main,
color: theme.palette.grayLight.main,
},
"& .MuiFilledInput-root.Mui-error": {
fontSize: "8px",
},
"& .MuiFilledInput-root.Mui-error": {
fontSize: "8px",
},
}));

@ -3,15 +3,15 @@ import * as React from "react";
import { useLocation, Navigate } from "react-router-dom";
interface Props {
children: JSX.Element;
children: JSX.Element;
}
export default function PrivateRoute({ children }: Props) {
const token = useToken();
const location = useLocation();
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
if (token) {
return children;
}
return <Navigate to="/" state={{ from: location }} />;
};
const token = useToken();
const location = useLocation();
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
if (token) {
return children;
}
return <Navigate to="/" state={{ from: location }} />;
}

@ -2,20 +2,19 @@ import { useLocation, Navigate } from "react-router-dom";
import { useToken } from "@frontend/kitui";
interface Props {
children: JSX.Element;
children: JSX.Element;
}
const PublicRoute = ({ children }: Props) => {
const location = useLocation();
const token = useToken();
const location = useLocation();
const token = useToken();
if (token) {
return <Navigate to="/users" state={{ from: location }} />;
}
if (token) {
return <Navigate to="/users" state={{ from: location }} />;
}
return children;
return children;
};
export default PublicRoute;

@ -1,50 +1,51 @@
import { Discount } from "@frontend/kitui";
export type GetDiscountResponse = {
Discounts: Discount[];
Discounts: Discount[];
};
export const discountTypes = {
"purchasesAmount": "Лояльность",
"cartPurchasesAmount": "Корзина",
"service": "Сервис",
"privilege": "Товар",
purchasesAmount: "Лояльность",
cartPurchasesAmount: "Корзина",
service: "Сервис",
privilege: "Товар",
} as const;
export type DiscountType = keyof typeof discountTypes;
export type CreateDiscountBody = {
Name: string;
Layer: 1 | 2 | 3 | 4;
Description: string;
Condition: {
Period: {
/** ISO string */
From: string;
/** ISO string */
To: string;
};
User: string;
UserType: string;
Coupon: string;
PurchasesAmount: number;
CartPurchasesAmount: number;
Product: string;
Term: number;
Usage: number;
PriceFrom: number;
Group: string;
};
Target: {
Factor: number;
TargetScope: "Sum" | "Group" | "Each";
Overhelm: boolean;
TargetGroup: string;
Products: [{
ID: string;
Factor: number;
Overhelm: false;
}];
};
Name: string;
Layer: 1 | 2 | 3 | 4;
Description: string;
Condition: {
Period: {
/** ISO string */
From: string;
/** ISO string */
To: string;
};
User: string;
UserType: string;
Coupon: string;
PurchasesAmount: number;
CartPurchasesAmount: number;
Product: string;
Term: number;
Usage: number;
PriceFrom: number;
Group: string;
};
Target: {
Factor: number;
TargetScope: "Sum" | "Group" | "Each";
Overhelm: boolean;
TargetGroup: string;
Products: [
{
ID: string;
Factor: number;
Overhelm: false;
},
];
};
};

@ -1,16 +1,16 @@
export const SERVICE_LIST = [
{
serviceKey: "templategen",
displayName: "Шаблонизатор документов",
},
{
serviceKey: "squiz",
displayName: "Опросник",
},
{
serviceKey: "dwarfener",
displayName: "Аналитика сокращателя",
},
] as const;
{
serviceKey: "templategen",
displayName: "Шаблонизатор документов",
},
{
serviceKey: "squiz",
displayName: "Опросник",
},
{
serviceKey: "dwarfener",
displayName: "Аналитика сокращателя",
},
] as const;
export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];

@ -1,51 +1,51 @@
export type CreatePromocodeBody = {
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
bonus: {
privilege: {
privilegeID: string;
amount: number;
serviceKey: string;
};
discount: {
layer: number;
factor: number;
target: string;
threshold: number;
};
};
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
bonus: {
privilege: {
privilegeID: string;
amount: number;
serviceKey: string;
};
discount: {
layer: number;
factor: number;
target: string;
threshold: number;
};
};
};
export type GetPromocodeListBody = {
page: number;
limit: number;
filter: {
active: boolean;
text?: string;
};
page: number;
limit: number;
filter: {
active: boolean;
text?: string;
};
};
export type Promocode = CreatePromocodeBody & {
id: string;
dueTo: number;
activationLimit: number;
outdated: boolean;
offLimit: boolean;
delete: boolean;
createdAt: string;
fastLinks: string[];
id: string;
dueTo: number;
activationLimit: number;
outdated: boolean;
offLimit: boolean;
delete: boolean;
createdAt: string;
fastLinks: string[];
};
export type PromocodeList = {
count: number;
items: Promocode[];
count: number;
items: Promocode[];
};
export type PromocodeStatistics = {
id: string;
usageCount: number;
usageMap: Record<string, number>;
id: string;
usageCount: number;
usageMap: Record<string, number>;
};

@ -1,18 +1,18 @@
import { Privilege } from "@frontend/kitui";
export const SERVICE_LIST = [
{
serviceKey: "templategen",
displayName: "Шаблонизатор документов",
},
{
serviceKey: "squiz",
displayName: "Опросник",
},
{
serviceKey: "dwarfener",
displayName: "Аналитика сокращателя",
},
{
serviceKey: "templategen",
displayName: "Шаблонизатор документов",
},
{
serviceKey: "squiz",
displayName: "Опросник",
},
{
serviceKey: "dwarfener",
displayName: "Аналитика сокращателя",
},
] as const;
export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
@ -20,10 +20,10 @@ export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
export type PrivilegeType = "unlim" | "gencount" | "activequiz" | "abcount" | "extended";
export type EditTariffRequestBody = {
description: string;
name: string;
order: number;
price: number;
isCustom: boolean;
privileges: Omit<Privilege, "_id" | "updatedAt">[];
description: string;
name: string;
order: number;
price: number;
isCustom: boolean;
privileges: Omit<Privilege, "_id" | "updatedAt">[];
};

@ -1,44 +1,42 @@
export interface CreateTicketRequest {
Title: string;
Message: string;
};
Title: string;
Message: string;
}
export interface CreateTicketResponse {
Ticket: string;
};
Ticket: string;
}
export interface SendTicketMessageRequest {
message: string;
ticket: string;
lang: string;
files: string[];
};
message: string;
ticket: string;
lang: string;
files: string[];
}
export type TicketStatus = "open";
export interface Ticket {
id: string;
user: string;
sess: string;
ans: string;
state: string;
top_message: TicketMessage;
title: string;
created_at: string;
updated_at: string;
rate: number;
};
id: string;
user: string;
sess: string;
ans: string;
state: string;
top_message: TicketMessage;
title: string;
created_at: string;
updated_at: string;
rate: number;
}
export interface TicketMessage {
id: string;
ticket_id: string;
user_id: string,
session_id: string;
message: string;
files: string[],
shown: { [key: string]: number; },
request_screenshot: string,
created_at: string;
};
id: string;
ticket_id: string;
user_id: string;
session_id: string;
message: string;
files: string[];
shown: { [key: string]: number };
request_screenshot: string;
created_at: string;
}

@ -1,5 +1,5 @@
export interface User {
ID: string;
Type: "" | "nko";
PurchasesAmount: number;
}
ID: string;
Type: "" | "nko";
PurchasesAmount: number;
}

@ -11,118 +11,118 @@ import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import OutlinedInput from "@kitUI/outlinedInput";
export default () => {
const theme = useTheme();
const navigate = useNavigate();
const [restore, setRestore] = React.useState(true);
const [isReady, setIsReady] = React.useState(true);
if (restore) {
return (
<Formik
initialValues={{
mail: "",
}}
onSubmit={(values) => {
setRestore(false);
}}
>
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Восстановление пароля
</Typography>
<Logo />
const theme = useTheme();
const navigate = useNavigate();
const [restore, setRestore] = React.useState(true);
const [isReady, setIsReady] = React.useState(true);
if (restore) {
return (
<Formik
initialValues={{
mail: "",
}}
onSubmit={(values) => {
setRestore(false);
}}
>
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Восстановление пароля
</Typography>
<Logo />
<Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field as={OutlinedInput} autoComplete="none" variant="filled" name="mail" label="Эл. почта" />
</Box>
<CleverButton type="submit" text="Отправить" isReady={isReady} />
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Я помню пароль</Typography>
</Link>
</Box>
</Box>
</Form>
</Formik>
);
} else {
return (
<Formik
initialValues={{
code: "",
}}
onSubmit={(values) => {}}
>
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Восстановление пароля
</Typography>
<Logo />
<Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field as={OutlinedInput} autoComplete="none" variant="filled" name="mail" label="Эл. почта" />
</Box>
<CleverButton type="submit" text="Отправить" isReady={isReady} />
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Я помню пароль</Typography>
</Link>
</Box>
</Box>
</Form>
</Formik>
);
} else {
return (
<Formik
initialValues={{
code: "",
}}
onSubmit={(values) => {}}
>
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Восстановление пароля
</Typography>
<Logo />
<Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field as={OutlinedInput} name="code" variant="filled" label="Код из сообщения" />
</Box>
<Box sx={{ display: "flex", alignItems: "center", marginTop: "15px", "> *": { marginRight: "10px" } }}>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field as={OutlinedInput} name="code" variant="filled" label="Код из сообщения" />
</Box>
<CleverButton type="submit" text="Отправить" isReady={isReady} />
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Я помню пароль</Typography>
</Link>
</Box>
</Box>
</Form>
</Formik>
);
}
<CleverButton type="submit" text="Отправить" isReady={isReady} />
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Я помню пароль</Typography>
</Link>
</Box>
</Box>
</Form>
</Formik>
);
}
};

@ -3,13 +3,7 @@ import { enqueueSnackbar } from "notistack";
import { useTheme } from "@mui/material/styles";
import { Formik, Field, Form, FormikHelpers } from "formik";
import { Link } from "react-router-dom";
import {
Box,
Checkbox,
Typography,
FormControlLabel,
Button, useMediaQuery,
} from "@mui/material";
import { Box, Checkbox, Typography, FormControlLabel, Button, useMediaQuery } from "@mui/material";
import Logo from "@pages/Logo";
import OutlinedInput from "@kitUI/outlinedInput";
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
@ -17,210 +11,197 @@ import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { signin } from "@root/api/auth";
interface Values {
email: string;
password: string;
email: string;
password: string;
}
function validate(values: Values) {
const errors = {} as any;
const errors = {} as any;
if (!values.email) {
errors.email = "Обязательное поле";
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
errors.email = "Неверный формат эл. почты";
}
if (!values.email) {
errors.email = "Обязательное поле";
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
errors.email = "Неверный формат эл. почты";
}
if (!values.password) {
errors.password = "Введите пароль";
}
if (!values.password) {
errors.password = "Введите пароль";
}
if (values.password && !/^[\S]{8,25}$/i.test(values.password)) {
errors.password = "Invalid password";
}
if (values.password && !/^[\S]{8,25}$/i.test(values.password)) {
errors.password = "Invalid password";
}
return errors;
return errors;
}
const SigninForm = () => {
const theme = useTheme();
const navigate = useNavigate();
const isMobile = useMediaQuery(theme.breakpoints.down(600));
const initialValues: Values = {
email: "",
password: "",
};
const theme = useTheme();
const navigate = useNavigate();
const isMobile = useMediaQuery(theme.breakpoints.down(600));
const initialValues: Values = {
email: "",
password: "",
};
const onSignFormSubmit = async (
values: Values,
formikHelpers: FormikHelpers<Values>
) => {
formikHelpers.setSubmitting(true);
const onSignFormSubmit = async (values: Values, formikHelpers: FormikHelpers<Values>) => {
formikHelpers.setSubmitting(true);
const [_, signinError] = await signin(values.email, values.password);
const [_, signinError] = await signin(values.email, values.password);
formikHelpers.setSubmitting(false);
formikHelpers.setSubmitting(false);
if (signinError) {
return enqueueSnackbar(signinError);
}
if (signinError) {
return enqueueSnackbar(signinError);
}
navigate("/users");
};
navigate("/users");
};
return (
<Formik
initialValues={initialValues}
validate={validate}
onSubmit={onSignFormSubmit}
>
{(props) => (
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
padding: isMobile ? "0 16px" : undefined
}}
>
<Logo />
<Box>
<Typography variant="h5" color={theme.palette.secondary.main}>
Добро пожаловать
</Typography>
<Typography variant="h6" color={theme.palette.secondary.main}>
Мы рады что вы выбрали нас!
</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
name="email"
variant="filled"
label="Эл. почта"
error={props.touched.email && !!props.errors.email}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.email && props.errors.email}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
type="password"
name="password"
variant="filled"
label="Пароль"
error={props.touched.password && !!props.errors.password}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.password && props.errors.password}
</Typography>
}
/>
</Box>
<Box
component="article"
sx={{
display: "flex",
alignItems: "center",
}}
>
<FormControlLabel
sx={{ color: "white" }}
control={
<Checkbox
value="checkedA"
inputProps={{ "aria-label": "Checkbox A" }}
sx={{
color: "white",
transform: "scale(1.5)",
"&.Mui-checked": {
color: "white",
},
"&.MuiFormControlLabel-root": {
color: "white",
},
}}
/>
}
label="Запомнить этот компьютер"
/>
</Box>
<Link to="/restore" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>
Забыли пароль?
</Typography>
</Link>
<Button
type="submit"
disabled={props.isSubmitting}
sx={{
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18,
}}
>
Войти
</Button>
<Box
sx={{
display: "flex",
}}
>
<Typography color={theme.palette.secondary.main}>
У вас нет аккаунта?&nbsp;
</Typography>
<Link to="/signup" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>
Зарегестрируйтесь
</Typography>
</Link>
</Box>
</Box>
</Box>
</Form>
)}
</Formik>
);
return (
<Formik initialValues={initialValues} validate={validate} onSubmit={onSignFormSubmit}>
{(props) => (
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
padding: isMobile ? "0 16px" : undefined,
}}
>
<Logo />
<Box>
<Typography variant="h5" color={theme.palette.secondary.main}>
Добро пожаловать
</Typography>
<Typography variant="h6" color={theme.palette.secondary.main}>
Мы рады что вы выбрали нас!
</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
name="email"
variant="filled"
label="Эл. почта"
error={props.touched.email && !!props.errors.email}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.email && props.errors.email}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
type="password"
name="password"
variant="filled"
label="Пароль"
error={props.touched.password && !!props.errors.password}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.password && props.errors.password}
</Typography>
}
/>
</Box>
<Box
component="article"
sx={{
display: "flex",
alignItems: "center",
}}
>
<FormControlLabel
sx={{ color: "white" }}
control={
<Checkbox
value="checkedA"
inputProps={{ "aria-label": "Checkbox A" }}
sx={{
color: "white",
transform: "scale(1.5)",
"&.Mui-checked": {
color: "white",
},
"&.MuiFormControlLabel-root": {
color: "white",
},
}}
/>
}
label="Запомнить этот компьютер"
/>
</Box>
<Link to="/restore" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Забыли пароль?</Typography>
</Link>
<Button
type="submit"
disabled={props.isSubmitting}
sx={{
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18,
}}
>
Войти
</Button>
<Box
sx={{
display: "flex",
}}
>
<Typography color={theme.palette.secondary.main}>У вас нет аккаунта?&nbsp;</Typography>
<Link to="/signup" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>Зарегестрируйтесь</Typography>
</Link>
</Box>
</Box>
</Box>
</Form>
)}
</Formik>
);
};
export default SigninForm;
export default SigninForm;

@ -12,201 +12,192 @@ import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { register } from "@root/api/auth";
interface Values {
email: string;
password: string;
repeatPassword: string;
email: string;
password: string;
repeatPassword: string;
}
function validate(values: Values) {
const errors: Partial<Values> = {};
const errors: Partial<Values> = {};
if (!values.email) {
errors.email = "Обязательное поле";
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
errors.email = "Неверный формат эл. почты";
}
if (!values.email) {
errors.email = "Обязательное поле";
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
errors.email = "Неверный формат эл. почты";
}
if (!values.password) {
errors.password = "Обязательное поле";
} else if (!/^[\S]{8,25}$/i.test(values.password)) {
errors.password = "Неверный пароль";
}
if (values.password !== values.repeatPassword) {
errors.repeatPassword = "Пароли не совпадают";
}
if (!values.password) {
errors.password = "Обязательное поле";
} else if (!/^[\S]{8,25}$/i.test(values.password)) {
errors.password = "Неверный пароль";
}
if (values.password !== values.repeatPassword) {
errors.repeatPassword = "Пароли не совпадают";
}
return errors;
return errors;
}
const SignUp = () => {
const navigate = useNavigate();
const theme = useTheme();
const navigate = useNavigate();
const theme = useTheme();
return (
<Formik
initialValues={{
email: "",
password: "",
repeatPassword: "",
}}
validate={validate}
onSubmit={async (values, formikHelpers) => {
formikHelpers.setSubmitting(true);
return (
<Formik
initialValues={{
email: "",
password: "",
repeatPassword: "",
}}
validate={validate}
onSubmit={async (values, formikHelpers) => {
formikHelpers.setSubmitting(true);
const [_, registerError] = await register(
values.email,
values.repeatPassword
);
const [_, registerError] = await register(values.email, values.repeatPassword);
formikHelpers.setSubmitting(false);
formikHelpers.setSubmitting(false);
if (registerError) {
return enqueueSnackbar(registerError);
}
if (registerError) {
return enqueueSnackbar(registerError);
}
navigate("/users");
}}
>
{(props) => (
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Новый аккаунт
</Typography>
<Logo />
navigate("/users");
}}
>
{(props) => (
<Form>
<Box
component="section"
sx={{
minHeight: "100vh",
height: "100%",
width: "100%",
backgroundColor: theme.palette.content.main,
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "15px 0",
}}
>
<Box
component="article"
sx={{
width: "350px",
backgroundColor: theme.palette.content.main,
display: "flex",
flexDirection: "column",
justifyContent: "center",
"> *": {
marginTop: "15px",
},
}}
>
<Typography variant="h6" color={theme.palette.secondary.main}>
Новый аккаунт
</Typography>
<Logo />
<Box>
<Typography variant="h5" color={theme.palette.secondary.main}>
Добро пожаловать
</Typography>
<Typography variant="h6" color={theme.palette.secondary.main}>
Мы рады что вы выбрали нас!
</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
name="email"
variant="filled"
label="Эл. почта"
id="email"
error={props.touched.email && !!props.errors.email}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.email && props.errors.email}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
sx={{}}
as={OutlinedInput}
type="password"
name="password"
variant="filled"
label="Пароль"
id="password"
error={props.touched.password && !!props.errors.password}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.password && props.errors.password}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
type="password"
name="repeatPassword"
variant="filled"
label="Повторите пароль"
id="repeatPassword"
error={
props.touched.repeatPassword &&
!!props.errors.repeatPassword
}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.repeatPassword &&
props.errors.repeatPassword}
</Typography>
}
/>
</Box>
<Button
type="submit"
disabled={props.isSubmitting}
sx={{
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18,
}}
>
Войти
</Button>
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>
У меня уже есть аккаунт
</Typography>
</Link>
</Box>
</Box>
</Form>
)}
</Formik>
);
<Box>
<Typography variant="h5" color={theme.palette.secondary.main}>
Добро пожаловать
</Typography>
<Typography variant="h6" color={theme.palette.secondary.main}>
Мы рады что вы выбрали нас!
</Typography>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<EmailOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
name="email"
variant="filled"
label="Эл. почта"
id="email"
error={props.touched.email && !!props.errors.email}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.email && props.errors.email}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
sx={{}}
as={OutlinedInput}
type="password"
name="password"
variant="filled"
label="Пароль"
id="password"
error={props.touched.password && !!props.errors.password}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.password && props.errors.password}
</Typography>
}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
marginTop: "15px",
"> *": { marginRight: "10px" },
}}
>
<LockOutlinedIcon htmlColor={theme.palette.golden.main} />
<Field
as={OutlinedInput}
type="password"
name="repeatPassword"
variant="filled"
label="Повторите пароль"
id="repeatPassword"
error={props.touched.repeatPassword && !!props.errors.repeatPassword}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.touched.repeatPassword && props.errors.repeatPassword}
</Typography>
}
/>
</Box>
<Button
type="submit"
disabled={props.isSubmitting}
sx={{
width: "250px",
margin: "15px auto",
padding: "20px 30px",
fontSize: 18,
}}
>
Войти
</Button>
<Link to="/signin" style={{ textDecoration: "none" }}>
<Typography color={theme.palette.golden.main}>У меня уже есть аккаунт</Typography>
</Link>
</Box>
</Box>
</Form>
)}
</Formik>
);
};
export default SignUp;

@ -1,65 +1,73 @@
import * as React from "react";
import {Box, Button, Typography} from "@mui/material";
import { Box, Button, Typography } from "@mui/material";
import { ThemeProvider } from "@mui/material";
import theme from "../../theme";
import CssBaseline from '@mui/material/CssBaseline';
import {Link} from "react-router-dom";
import CssBaseline from "@mui/material/CssBaseline";
import { Link } from "react-router-dom";
const Error404: React.FC = () => {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<CssBaseline />
<Box
sx={{
backgroundColor: theme.palette.primary.main,
color: theme.palette.secondary.main,
height: "100%",
}}
>
<Box
sx={{
width: "100vw",
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Box
sx={{
width: "150px",
height: "120px",
display: "flex",
flexDirection: "row",
}}
>
<Typography
sx={{
fontSize: "80px",
}}
>
4
</Typography>
<Typography
sx={{
color: theme.palette.golden.main,
fontSize: "80px",
}}
>
0
</Typography>
<Typography
sx={{
fontSize: "80px",
}}
>
4
</Typography>
</Box>
<Box>
<Link to="/users">
<Button>На главную</Button>
</Link>
</Box>
</Box>
</Box>
</ThemeProvider>
</React.Fragment>
);
};
const Error404: React.FC = () => {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<CssBaseline />
<Box sx={{
backgroundColor: theme.palette.primary.main,
color: theme.palette.secondary.main,
height: "100%"
}}>
<Box sx={{
width: "100vw",
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}>
<Box sx={{
width: "150px",
height: "120px",
display: "flex",
flexDirection: "row"
}}>
<Typography sx={{
fontSize: "80px"
}}>
4
</Typography>
<Typography sx={{
color: theme.palette.golden.main,
fontSize: "80px"
}}>
0
</Typography>
<Typography sx={{
fontSize: "80px"
}}>
4
</Typography>
</Box>
<Box>
<Link
to="/users">
<Button>На главную</Button>
</Link>
</Box>
</Box>
</Box>
</ThemeProvider>
</React.Fragment>
);
}
export default Error404;
export default Error404;

@ -2,41 +2,42 @@ import * as React from "react";
import { Box, Typography } from "@mui/material";
import theme from "../../theme";
const Authorization: React.FC = () => {
return (
<React.Fragment>
<Box
sx={{
display: "flex",
}}
>
<Typography
variant="subtitle1"
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
cursor: "default",
}}
>
PENA
</Typography>
<Typography
variant="subtitle2"
sx={{
width: "55px",
color: theme.palette.primary.main,
backgroundColor: theme.palette.goldenDark.main,
borderRadius: "5px",
margin: theme.spacing(0.5),
cursor: "default",
}}
>
HUB
</Typography>
</Box>
</React.Fragment>
);
};
const Authorization: React.FC = () => {
return (
<React.Fragment>
<Box sx={{
display: "flex"
}}>
<Typography
variant="subtitle1"
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
cursor: "default"
}}>
PENA
</Typography>
<Typography
variant = "subtitle2"
sx = {{
width: "55px",
color: theme.palette.primary.main,
backgroundColor: theme.palette.goldenDark.main,
borderRadius: "5px",
margin: theme.spacing(0.5),
cursor: "default"
}}
>
HUB
</Typography>
</Box>
</React.Fragment>
);
}
export default Authorization;
export default Authorization;

@ -2,171 +2,173 @@ import * as React from "react";
import { Box, Typography, Button } from "@mui/material";
import { ThemeProvider } from "@mui/material";
import theme from "../../theme";
import CssBaseline from '@mui/material/CssBaseline';
import CssBaseline from "@mui/material/CssBaseline";
import Logo from "../Logo";
const Authorization: React.FC = () => {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<CssBaseline />
<Box
sx={{
backgroundColor: theme.palette.primary.main,
color: theme.palette.secondary.main,
height: "100%",
}}
>
<Box
sx={{
width: "100vw",
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Box
sx={{
width: "350px",
height: "700px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Logo />
const Authorization: React.FC = () => {
return (
<React.Fragment>
<ThemeProvider theme={theme}>
<CssBaseline />
<Box sx={{
backgroundColor: theme.palette.primary.main,
color: theme.palette.secondary.main,
height: "100%"
}}>
<Box sx={{
width: "100vw",
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center"
}}>
<Box sx={{
width: "350px",
height: "700px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}>
<Logo />
<Box
sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box>
<Typography variant="h6">Все пользователи</Typography>
</Box>
<Box sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
}}>
<Box>
<Typography variant="h6">
Все пользователи
</Typography>
</Box>
<Button variant="enter">ВОЙТИ</Button>
</Box>
<Button
variant = 'enter'
>
ВОЙТИ
</Button>
</Box>
<Box
sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box>
<Typography variant="h6">Общая статистика</Typography>
</Box>
<Box sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
}}>
<Box>
<Typography variant="h6">
Общая статистика
</Typography>
</Box>
<Button
variant="enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ВОЙТИ
</Button>
</Box>
<Button
variant = "enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main
}
}}>
ВОЙТИ
</Button>
</Box>
<Box
sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box>
<Typography variant="h6">Шаблонизатор документов</Typography>
</Box>
<Box sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
}}>
<Box>
<Typography variant="h6">
Шаблонизатор документов
</Typography>
</Box>
<Button
variant="enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ВОЙТИ
</Button>
</Box>
<Button
variant = "enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main
}
}}>
ВОЙТИ
</Button>
</Box>
<Box
sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box>
<Typography variant="h6">Конструктор опросов</Typography>
</Box>
<Box sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
}}>
<Box>
<Typography variant="h6">
Конструктор опросов
</Typography>
</Box>
<Button
variant="enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ВОЙТИ
</Button>
</Box>
<Button
variant = "enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main
}
}}>
ВОЙТИ
</Button>
</Box>
<Box
sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box>
<Typography variant="h6">Сокращатель ссылок</Typography>
</Box>
<Box sx={{
width: "100%",
height: "100px",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
}}>
<Box>
<Typography variant="h6">
Сокращатель ссылок
</Typography>
</Box>
<Button
variant="enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ВОЙТИ
</Button>
</Box>
</Box>
</Box>
</Box>
</ThemeProvider>
</React.Fragment>
);
};
<Button
variant = "enter"
sx={{
backgroundColor: theme.palette.content.main,
"&:hover": {
backgroundColor: theme.palette.menu.main
}
}}>
ВОЙТИ
</Button>
</Box>
</Box>
</Box>
</Box>
</ThemeProvider>
</React.Fragment>
);
}
export default Authorization;
export default Authorization;

@ -1,169 +1,177 @@
import { KeyboardEvent, useRef, useState } from "react";
import { enqueueSnackbar } from "notistack";
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
import { Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme } from "@mui/material";
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import { CustomPrivilege } from "@frontend/kitui";
import { putPrivilege } from "@root/api/privilegies";
import SaveIcon from '@mui/icons-material/Save';
import SaveIcon from "@mui/icons-material/Save";
import { currencyFormatter } from "@root/utils/currencyFormatter";
interface CardPrivilege {
privilege: CustomPrivilege;
privilege: CustomPrivilege;
}
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
const [inputOpen, setInputOpen] = useState<boolean>(false);
const [inputValue, setInputValue] = useState<string>("");
const priceRef = useRef<HTMLDivElement>(null);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
const [inputOpen, setInputOpen] = useState<boolean>(false);
const [inputValue, setInputValue] = useState<string>("");
const priceRef = useRef<HTMLDivElement>(null);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
const translationType = {
count: "за единицу",
day: "за день",
mb: "за МБ",
};
const translationType = {
count: "за единицу",
day: "за день",
mb: "за МБ",
};
const putPrivileges = async () => {
const putPrivileges = async () => {
const [, putedPrivilegeError] = await putPrivilege({
name: privilege.name,
privilegeId: privilege.privilegeId,
serviceKey: privilege.serviceKey,
description: privilege.description,
amount: 1,
type: privilege.type,
value: privilege.value,
price: 100 * Number(inputValue),
});
const [, putedPrivilegeError] = await putPrivilege({
name: privilege.name,
privilegeId: privilege.privilegeId,
serviceKey: privilege.serviceKey,
description: privilege.description,
amount: 1,
type: privilege.type,
value: privilege.value,
price: 100 * Number(inputValue),
});
if (putedPrivilegeError) {
return enqueueSnackbar(putedPrivilegeError);
}
if (putedPrivilegeError) {
return enqueueSnackbar(putedPrivilegeError);
}
if (!priceRef.current) {
return;
}
if (!priceRef.current) {
return;
}
enqueueSnackbar("Изменения сохранены");
enqueueSnackbar("Изменения сохранены");
priceRef.current.innerText = "price: " + inputValue;
setInputValue("");
setInputOpen(false);
};
priceRef.current.innerText = "price: " + inputValue;
setInputValue("");
setInputOpen(false);
};
const onTextfieldKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
return setInputOpen(false);
}
if (event.key === "Enter" && inputValue !== "") {
putPrivileges();
setInputOpen(false);
}
};
const onTextfieldKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
return setInputOpen(false);
}
if (event.key === "Enter" && inputValue !== "") {
putPrivileges();
setInputOpen(false);
}
};
function handleSavePrice() {
setInputOpen(false);
if (!inputValue) return;
function handleSavePrice() {
setInputOpen(false);
if (!inputValue) return;
putPrivileges();
}
putPrivileges();
}
return (
<Box
key={privilege.type}
sx={{
px: "20px",
return (
<Box
key={privilege.type}
sx={{
px: "20px",
display: "flex",
alignItems: "center",
border: "1px solid gray",
}}
>
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
<Box sx={{ width: mobile ? "120px" : "200px", py: "25px" }}>
<Typography
variant="h6"
sx={{
color: "#fe9903",
overflowWrap: "break-word",
overflow: "hidden",
}}
>
{privilege.name}
</Typography>
<Tooltip
sx={{
span: {
fontSize: "1rem",
},
}}
placement="top"
title={<Typography sx={{ fontSize: "16px" }}>{privilege.description}</Typography>}
>
<IconButton disableRipple>
<svg width="40" height="40" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M9.25 9.25H10V14.5H10.75"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
fill="#7E2AEA"
/>
</svg>
</IconButton>
</Tooltip>
<IconButton onClick={() => setInputOpen(!inputOpen)}>
<ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
</IconButton>
</Box>
</Box>
<Box sx={{ maxWidth: "600px", width: "100%", display: "flex", alignItems: mobile ? "center" : undefined, justifyContent: "space-around", flexDirection: mobile ? "column" : "row", gap: "5px" }}>
{inputOpen ? (
<TextField
type="number"
onKeyDown={onTextfieldKeyDown}
placeholder="введите число"
fullWidth
onChange={(event) => setInputValue(event.target.value)}
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
marginLeft: "5px",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
InputProps={{
endAdornment: (
<IconButton onClick={handleSavePrice}>
<SaveIcon />
</IconButton>
)
}}
/>
) : (
<div ref={priceRef} style={{ color: "white", marginRight: "5px" }}>
price: {currencyFormatter.format(privilege.price / 100)}
</div>
)}
<Typography sx={{ color: "white" }}>{translationType[privilege.type]}</Typography>
</Box>
</Box>
);
display: "flex",
alignItems: "center",
border: "1px solid gray",
}}
>
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
<Box sx={{ width: mobile ? "120px" : "200px", py: "25px" }}>
<Typography
variant="h6"
sx={{
color: "#fe9903",
overflowWrap: "break-word",
overflow: "hidden",
}}
>
{privilege.name}
</Typography>
<Tooltip
sx={{
span: {
fontSize: "1rem",
},
}}
placement="top"
title={<Typography sx={{ fontSize: "16px" }}>{privilege.description}</Typography>}
>
<IconButton disableRipple>
<svg width="40" height="40" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M9.25 9.25H10V14.5H10.75"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
fill="#7E2AEA"
/>
</svg>
</IconButton>
</Tooltip>
<IconButton onClick={() => setInputOpen(!inputOpen)}>
<ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
</IconButton>
</Box>
</Box>
<Box
sx={{
maxWidth: "600px",
width: "100%",
display: "flex",
alignItems: mobile ? "center" : undefined,
justifyContent: "space-around",
flexDirection: mobile ? "column" : "row",
gap: "5px",
}}
>
{inputOpen ? (
<TextField
type="number"
onKeyDown={onTextfieldKeyDown}
placeholder="введите число"
fullWidth
onChange={(event) => setInputValue(event.target.value)}
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
marginLeft: "5px",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
InputProps={{
endAdornment: (
<IconButton onClick={handleSavePrice}>
<SaveIcon />
</IconButton>
),
}}
/>
) : (
<div ref={priceRef} style={{ color: "white", marginRight: "5px" }}>
price: {currencyFormatter.format(privilege.price / 100)}
</div>
)}
<Typography sx={{ color: "white" }}>{translationType[privilege.type]}</Typography>
</Box>
</Box>
);
};

@ -1,47 +1,47 @@
import React, { useEffect, useState } from "react";
type ConditionalRenderProps = {
isLoading: boolean;
role: string;
childrenUser?: JSX.Element;
childrenAdmin?: JSX.Element;
childrenManager?: JSX.Element;
isLoading: boolean;
role: string;
childrenUser?: JSX.Element;
childrenAdmin?: JSX.Element;
childrenManager?: JSX.Element;
};
const ConditionalRender = ({
isLoading,
role,
childrenUser,
childrenAdmin,
childrenManager,
isLoading,
role,
childrenUser,
childrenAdmin,
childrenManager,
}: ConditionalRenderProps): JSX.Element => {
// const [role, setRole] = useState<string>("");
// const [role, setRole] = useState<string>("");
// useEffect(() => {
// const axiosAccount = async () => {
// try {
// const { data } = await axios.get(process.env.REACT_APP_DOMAIN + "/user/643e23f3dba63ba17272664d");
// setRole(data.role);
// } catch (error) {
// console.error("Ошибка при получение роли пользавателя");
// }
// };
// axiosAccount();
// }, [role]);
// useEffect(() => {
// const axiosAccount = async () => {
// try {
// const { data } = await axios.get(process.env.REACT_APP_DOMAIN + "/user/643e23f3dba63ba17272664d");
// setRole(data.role);
// } catch (error) {
// console.error("Ошибка при получение роли пользавателя");
// }
// };
// axiosAccount();
// }, [role]);
if (!isLoading) {
if (role === "admin") {
return childrenAdmin ? childrenAdmin : <div>Администратор</div>;
}
if (role === "user") {
return childrenUser ? childrenUser : <div>Пользователь</div>;
}
if (role === "manager") {
return childrenManager ? childrenManager : <div>Менеджер</div>;
}
}
if (!isLoading) {
if (role === "admin") {
return childrenAdmin ? childrenAdmin : <div>Администратор</div>;
}
if (role === "user") {
return childrenUser ? childrenUser : <div>Пользователь</div>;
}
if (role === "manager") {
return childrenManager ? childrenManager : <div>Менеджер</div>;
}
}
return <React.Fragment />;
return <React.Fragment />;
};
export default ConditionalRender;

@ -1,81 +1,83 @@
import { useState } from "react";
import {
Button,
Checkbox,
FormControl,
ListItemText,
MenuItem,
Select,
SelectChangeEvent,
TextField, useMediaQuery, useTheme,
Button,
Checkbox,
FormControl,
ListItemText,
MenuItem,
Select,
SelectChangeEvent,
TextField,
useMediaQuery,
useTheme,
} from "@mui/material";
import { MOCK_DATA_USERS } from "@root/api/roles";
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
},
},
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
},
},
};
export default function CreateForm() {
const [personName, setPersonName] = useState<string[]>([]);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
const {
target: { value },
} = event;
setPersonName(typeof value === "string" ? value.split(",") : value);
};
const [personName, setPersonName] = useState<string[]>([]);
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
const {
target: { value },
} = event;
setPersonName(typeof value === "string" ? value.split(",") : value);
};
return (
<>
<TextField
placeholder="название"
fullWidth
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
/>
<Button sx={{ ml: "5px", bgcolor: "#fe9903", color: "white", minWidth: "85px" }}>Отправить</Button>
<FormControl sx={{ ml: mobile ? "10px" : "25px", width: "80%" }}>
<Select
sx={{ bgcolor: "white", height: "48px" }}
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
multiple
value={personName}
onChange={handleChange}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{MOCK_DATA_USERS.map(({ name, id }) => (
<MenuItem key={id} value={name}>
<Checkbox checked={personName.indexOf(name) > -1} />
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
</FormControl>
</>
);
return (
<>
<TextField
placeholder="название"
fullWidth
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
/>
<Button sx={{ ml: "5px", bgcolor: "#fe9903", color: "white", minWidth: "85px" }}>Отправить</Button>
<FormControl sx={{ ml: mobile ? "10px" : "25px", width: "80%" }}>
<Select
sx={{ bgcolor: "white", height: "48px" }}
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
multiple
value={personName}
onChange={handleChange}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{MOCK_DATA_USERS.map(({ name, id }) => (
<MenuItem key={id} value={name}>
<Checkbox checked={personName.indexOf(name) > -1} />
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
</FormControl>
</>
);
}

@ -1,13 +1,13 @@
import { useState } from "react";
import {
Button,
Checkbox,
FormControl,
ListItemText,
MenuItem,
Select,
SelectChangeEvent,
TextField,
Button,
Checkbox,
FormControl,
ListItemText,
MenuItem,
Select,
SelectChangeEvent,
TextField,
} from "@mui/material";
import { MOCK_DATA_USERS } from "@root/api/roles";
import { deleteRole } from "@root/api/roles";
@ -16,82 +16,76 @@ import { enqueueSnackbar } from "notistack";
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
},
},
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
},
},
};
export default function DeleteForm() {
const [personName, setPersonName] = useState<string[]>([]);
const [roleId, setRoleId] = useState<string>();
const [personName, setPersonName] = useState<string[]>([]);
const [roleId, setRoleId] = useState<string>();
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
const {
target: { value },
} = event;
setPersonName(typeof value === "string" ? value.split(",") : value);
};
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
const {
target: { value },
} = event;
setPersonName(typeof value === "string" ? value.split(",") : value);
};
const rolesDelete = async (id = "") => {
const [_, deletedRoleError] = await deleteRole(id);
const rolesDelete = async (id = "") => {
const [_, deletedRoleError] = await deleteRole(id);
if (deletedRoleError) {
return enqueueSnackbar(deletedRoleError);
}
};
if (deletedRoleError) {
return enqueueSnackbar(deletedRoleError);
}
};
return (
<>
<Button
onClick={() => rolesDelete(roleId)}
sx={{ mr: "5px", bgcolor: "#fe9903", color: "white" }}
>
Удалить
</Button>
<TextField
placeholder="название"
fullWidth
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
/>
<FormControl sx={{ ml: "25px", width: "80%" }}>
<Select
sx={{ bgcolor: "white", height: "48px" }}
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
value={personName}
onChange={handleChange}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{MOCK_DATA_USERS.map(({ name, id }) => (
<MenuItem key={id} value={name}>
<Checkbox
onClick={() => setRoleId(id)}
checked={personName.indexOf(name) > -1}
/>
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
</FormControl>
</>
);
return (
<>
<Button onClick={() => rolesDelete(roleId)} sx={{ mr: "5px", bgcolor: "#fe9903", color: "white" }}>
Удалить
</Button>
<TextField
placeholder="название"
fullWidth
sx={{
alignItems: "center",
maxWidth: "400px",
width: "100%",
"& .MuiInputBase-root": {
backgroundColor: "#F2F3F7",
height: "48px",
},
}}
inputProps={{
sx: {
borderRadius: "10px",
fontSize: "18px",
lineHeight: "21px",
py: 0,
},
}}
/>
<FormControl sx={{ ml: "25px", width: "80%" }}>
<Select
sx={{ bgcolor: "white", height: "48px" }}
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
value={personName}
onChange={handleChange}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{MOCK_DATA_USERS.map(({ name, id }) => (
<MenuItem key={id} value={name}>
<Checkbox onClick={() => setRoleId(id)} checked={personName.indexOf(name) > -1} />
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
</FormControl>
</>
);
}

@ -6,21 +6,17 @@ import { requestPrivileges } from "@root/services/privilegies.service";
import { СardPrivilege } from "./CardPrivilegie";
export default function ListPrivilege() {
const privileges = usePrivilegeStore((state) => state.privileges);
const privileges = usePrivilegeStore((state) => state.privileges);
useEffect(() => {
requestPrivileges();
}, []);
useEffect(() => {
requestPrivileges();
}, []);
return (
<>
{privileges.map(privilege => (
<СardPrivilege
key={privilege._id}
privilege={privilege}
/>
)
)}
</>
);
return (
<>
{privileges.map((privilege) => (
<СardPrivilege key={privilege._id} privilege={privilege} />
))}
</>
);
}

@ -5,24 +5,24 @@ import { Box, SxProps, Theme, Typography, useMediaQuery, useTheme } from "@mui/m
import ListPrivilege from "./ListPrivilegie";
interface CustomWrapperProps {
text: string;
sx?: SxProps<Theme>;
result?: boolean;
text: string;
sx?: SxProps<Theme>;
result?: boolean;
}
export const PrivilegesWrapper = ({ text, sx, result }: CustomWrapperProps) => {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
const [isExpanded, setIsExpanded] = useState<boolean>(false);
return (
<Box
sx={{
width: "100%",
overflow: "hidden",
borderRadius: "12px",
boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
return (
<Box
sx={{
width: "100%",
overflow: "hidden",
borderRadius: "12px",
boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
0px 41.7776px 129.093px rgba(210, 208, 225, 0.172525),
0px 22.3363px 69.0192px rgba(210, 208, 225, 0.143066),
0px 12.5216px 38.6916px rgba(210, 208, 225, 0.12),
@ -30,99 +30,99 @@ export const PrivilegesWrapper = ({ text, sx, result }: CustomWrapperProps) => {
0px 2.76726px 8.55082px rgba(210, 208, 225, 0.067
4749)`,
...sx,
}}
>
<Box
sx={{
border: "2px solid grey",
"&:first-of-type": {
borderTopLeftRadius: "12px ",
borderTopRightRadius: "12px",
},
"&:last-of-type": {
borderBottomLeftRadius: "12px",
borderBottomRightRadius: "12px",
},
"&:not(:last-of-type)": {
borderBottom: `1px solid gray`,
},
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "88px",
px: "20px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
fontSize: "18px",
lineHeight: upMd ? undefined : "19px",
fontWeight: 400,
color: "#FFFFFF",
px: 0,
}}
>
{text}
</Typography>
...sx,
}}
>
<Box
sx={{
border: "2px solid grey",
"&:first-of-type": {
borderTopLeftRadius: "12px ",
borderTopRightRadius: "12px",
},
"&:last-of-type": {
borderBottomLeftRadius: "12px",
borderBottomRightRadius: "12px",
},
"&:not(:last-of-type)": {
borderBottom: `1px solid gray`,
},
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "88px",
px: "20px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography
sx={{
width: "100%",
display: "flex",
justifyContent: "center",
fontSize: "18px",
lineHeight: upMd ? undefined : "19px",
fontWeight: 400,
color: "#FFFFFF",
px: 0,
}}
>
{text}
</Typography>
<Box
sx={{
display: "flex",
height: "100%",
alignItems: "center",
}}
>
{result ? (
<>
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<Box
sx={{
display: "flex",
height: "100%",
alignItems: "center",
}}
>
{result ? (
<>
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#7E2AEA"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<Box
sx={{
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
pl: upSm ? "2px" : 0,
height: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
/>
</>
) : (
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#fe9903"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</Box>
</Box>
{isExpanded && <ListPrivilege />}
</Box>
</Box>
);
<Box
sx={{
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
pl: upSm ? "2px" : 0,
height: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
/>
</>
) : (
<svg width="30" height="31" viewBox="0 0 30 31" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect y="0.8125" width="30" height="30" rx="6" fill="#252734" />
<path
d="M7.5 19.5625L15 12.0625L22.5 19.5625"
stroke="#fe9903"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</Box>
</Box>
{isExpanded && <ListPrivilege />}
</Box>
</Box>
);
};

@ -1,13 +1,13 @@
import {
AccordionDetails,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
useMediaQuery,
useTheme
AccordionDetails,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import { CustomWrapper } from "@root/kitUI/CustomWrapper";
@ -19,118 +19,116 @@ import { PrivilegesWrapper } from "./PrivilegiesWrapper";
import theme from "../../theme";
export const SettingRoles = (): JSX.Element => {
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
return (
<AccordionDetails sx={{ maxWidth: "890px",
width: "100%", }}>
<CustomWrapper
text="Роли"
children={
<>
<Table
sx={{
maxWidth: "890px",
width: "100%",
border: "2px solid",
borderColor: "gray",
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
Настройки ролей
</Typography>
</TableCell>
</TableRow>
</TableHead>
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(600));
return (
<AccordionDetails sx={{ maxWidth: "890px", width: "100%" }}>
<CustomWrapper
text="Роли"
children={
<>
<Table
sx={{
maxWidth: "890px",
width: "100%",
border: "2px solid",
borderColor: "gray",
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
Настройки ролей
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow
sx={{
p: "5px",
display: "flex",
alignItems: "center",
borderTop: "2px solid",
borderColor: theme.palette.grayLight.main,
height: mobile ? undefined : "100px",
cursor: "pointer",
flexDirection: mobile ? "column" : "row",
gap: "5px"
}}
>
<FormCreateRoles />
</TableRow>
</TableBody>
</Table>
<Table
sx={{
mt: "30px",
maxWidth: "890px",
width: "100%",
border: "2px solid",
borderColor: "gray",
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
Удаление ролей
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow
sx={{
p: "5px",
display: "flex",
alignItems: "center",
borderTop: "2px solid",
borderColor: theme.palette.grayLight.main,
height: mobile ? undefined : "100px",
cursor: "pointer",
flexDirection: mobile ? "column" : "row",
gap: "5px",
}}
>
<FormCreateRoles />
</TableRow>
</TableBody>
</Table>
<Table
sx={{
mt: "30px",
maxWidth: "890px",
width: "100%",
border: "2px solid",
borderColor: "gray",
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
Удаление ролей
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow
sx={{
p: "5px",
display: "flex",
alignItems: "center",
borderTop: "2px solid",
borderColor: theme.palette.grayLight.main,
height: mobile ? undefined : "100px",
cursor: "pointer",
flexDirection: mobile ? "column" : "row",
gap: "5px"
}}
>
<FormDeleteRoles />
</TableRow>
</TableBody>
</Table>
</>
}
/>
<TableBody>
<TableRow
sx={{
p: "5px",
display: "flex",
alignItems: "center",
borderTop: "2px solid",
borderColor: theme.palette.grayLight.main,
height: mobile ? undefined : "100px",
cursor: "pointer",
flexDirection: mobile ? "column" : "row",
gap: "5px",
}}
>
<FormDeleteRoles />
</TableRow>
</TableBody>
</Table>
</>
}
/>
<PrivilegesWrapper text="Привилегии" sx={{ mt: "50px", maxWidth: "890px",
width: "100%", }} />
</AccordionDetails>
);
<PrivilegesWrapper text="Привилегии" sx={{ mt: "50px", maxWidth: "890px", width: "100%" }} />
</AccordionDetails>
);
};

@ -1,6 +1,6 @@
import { enqueueSnackbar } from "notistack";
import { GridSelectionModel } from "@mui/x-data-grid";
import {Box, Button, useMediaQuery, useTheme} from "@mui/material";
import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import { changeDiscount } from "@root/api/discounts";
import { findDiscountsById } from "@root/stores/discounts";
@ -9,56 +9,58 @@ import { requestDiscounts } from "@root/services/discounts.service";
import { mutate } from "swr";
interface Props {
selectedRows: GridSelectionModel;
selectedRows: GridSelectionModel;
}
export default function DiscountDataGrid({ selectedRows }: Props) {
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(400));
const changeData = async (isActive: boolean) => {
let done = 0;
let fatal = 0;
const theme = useTheme();
const mobile = useMediaQuery(theme.breakpoints.down(400));
const changeData = async (isActive: boolean) => {
let done = 0;
let fatal = 0;
for (const id of selectedRows) {
const discount = findDiscountsById(String(id));
for (const id of selectedRows) {
const discount = findDiscountsById(String(id));
if (!discount) {
return enqueueSnackbar("Скидка не найдена");
}
if (!discount) {
return enqueueSnackbar("Скидка не найдена");
}
const [, changedDiscountError] = await changeDiscount(String(id), {
...discount,
Deprecated: isActive,
});
const [, changedDiscountError] = await changeDiscount(String(id), {
...discount,
Deprecated: isActive,
});
if (changedDiscountError) {
done += 1;
} else {
fatal += 1;
}
mutate("discounts");
}
if (changedDiscountError) {
done += 1;
} else {
fatal += 1;
}
mutate("discounts");
}
await requestDiscounts();
await requestDiscounts();
if (done) {
enqueueSnackbar("Успешно изменён статус " + done + " скидок");
}
if (done) {
enqueueSnackbar("Успешно изменён статус " + done + " скидок");
}
if (fatal) {
enqueueSnackbar(fatal + " скидок не изменили статус");
}
};
if (fatal) {
enqueueSnackbar(fatal + " скидок не изменили статус");
}
};
return (
<Box
sx={{
width: mobile ? "250px" : "400px",
display: "flex",
justifyContent: "space-between",
flexDirection: mobile ? "column" : undefined,
gap: "10px"}}>
<Button onClick={() => changeData(false)}>Активировать</Button>
<Button onClick={() => changeData(true)}>Деактивировать</Button>
</Box>
);
return (
<Box
sx={{
width: mobile ? "250px" : "400px",
display: "flex",
justifyContent: "space-between",
flexDirection: mobile ? "column" : undefined,
gap: "10px",
}}
>
<Button onClick={() => changeData(false)}>Активировать</Button>
<Button onClick={() => changeData(true)}>Деактивировать</Button>
</Box>
);
}

@ -1,22 +1,20 @@
import {
Box,
Typography,
Button,
useTheme,
FormControl,
FormLabel,
RadioGroup,
FormControlLabel,
Radio,
InputLabel, TextField,
Box,
Typography,
Button,
useTheme,
FormControl,
FormLabel,
RadioGroup,
FormControlLabel,
Radio,
InputLabel,
TextField,
} from "@mui/material";
import MenuItem from "@mui/material/MenuItem";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import { SERVICE_LIST, ServiceType } from "@root/model/tariff";
import {
resetPrivilegeArray,
usePrivilegeStore,
} from "@root/stores/privilegesStore";
import { resetPrivilegeArray, usePrivilegeStore } from "@root/stores/privilegesStore";
import { addDiscount } from "@root/stores/discounts";
import { enqueueSnackbar } from "notistack";
import { DiscountType, discountTypes } from "@root/model/discount";
@ -26,494 +24,480 @@ import { Formik, Field, Form, FormikHelpers } from "formik";
import { mutate } from "swr";
interface Values {
discountNameField: string,
discountDescriptionField: string,
discountFactorField: string,
serviceType: string,
discountType: DiscountType,
purchasesAmountField: string,
cartPurchasesAmountField: string,
discountMinValueField: string,
privilegeIdField: string,
discountNameField: string;
discountDescriptionField: string;
discountFactorField: string;
serviceType: string;
discountType: DiscountType;
purchasesAmountField: string;
cartPurchasesAmountField: string;
discountMinValueField: string;
privilegeIdField: string;
}
export default function CreateDiscount() {
const theme = useTheme();
const privileges = usePrivilegeStore((state) => state.privileges);
const theme = useTheme();
const privileges = usePrivilegeStore((state) => state.privileges);
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
const initialValues: Values = {
discountNameField: "",
discountDescriptionField: "",
discountFactorField: "",
serviceType: "",
discountType: "purchasesAmount",
purchasesAmountField: "",
cartPurchasesAmountField: "",
discountMinValueField: "",
privilegeIdField: "",
}
const initialValues: Values = {
discountNameField: "",
discountDescriptionField: "",
discountFactorField: "",
serviceType: "",
discountType: "purchasesAmount",
purchasesAmountField: "",
cartPurchasesAmountField: "",
discountMinValueField: "",
privilegeIdField: "",
};
const handleCreateDiscount = async(
values: Values,
formikHelpers: FormikHelpers<Values>
) => {
const purchasesAmount = Number(parseFloat(values.purchasesAmountField.replace(",", "."))) * 100;
const discountFactor =
(100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100;
const cartPurchasesAmount = Number(parseFloat(
values.cartPurchasesAmountField.replace(",", ".")) * 100
);
const discountMinValue = Number(parseFloat(
values.discountMinValueField.replace(",", ".")) * 100
);
const handleCreateDiscount = async (values: Values, formikHelpers: FormikHelpers<Values>) => {
const purchasesAmount = Number(parseFloat(values.purchasesAmountField.replace(",", "."))) * 100;
const [createdDiscountResponse, createdDiscountError] =
await createDiscount({
cartPurchasesAmount,
discountFactor,
discountMinValue,
purchasesAmount,
discountDescription: values.discountDescriptionField,
discountName: values.discountNameField,
startDate: new Date().toISOString(),
endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
serviceType: values.serviceType,
discountType: values.discountType,
privilegeId: values.privilegeIdField,
});
const discountFactor = (100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100;
const cartPurchasesAmount = Number(parseFloat(values.cartPurchasesAmountField.replace(",", ".")) * 100);
const discountMinValue = Number(parseFloat(values.discountMinValueField.replace(",", ".")) * 100);
if (createdDiscountError) {
console.error("Error creating discount", createdDiscountError);
const [createdDiscountResponse, createdDiscountError] = await createDiscount({
cartPurchasesAmount,
discountFactor,
discountMinValue,
purchasesAmount,
discountDescription: values.discountDescriptionField,
discountName: values.discountNameField,
startDate: new Date().toISOString(),
endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
serviceType: values.serviceType,
discountType: values.discountType,
privilegeId: values.privilegeIdField,
});
return enqueueSnackbar(createdDiscountError);
}
if (createdDiscountError) {
console.error("Error creating discount", createdDiscountError);
if (createdDiscountResponse) {
mutate("discounts");
addDiscount(createdDiscountResponse);
}
}
return enqueueSnackbar(createdDiscountError);
}
const validateFulledFields = (values: Values) => {
const errors = {} as any;
if (values.discountNameField.length === 0) {
errors.discountNameField = 'Поле "Имя" пустое'
}
if (values.discountDescriptionField.length === 0) {
errors.discountDescriptionField = 'Поле "Описание" пустое'
}
if (((100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100) < 0) {
errors.discountFactorField = "Процент скидки не может быть больше 100"
}
if (!isFinite(((100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100))) {
errors.discountFactorField = 'Поле "Процент скидки" не число'
}
if (values.discountType === "privilege" && !values.privilegeIdField) {
errors.privilegeIdField = "Привилегия не выбрана"
}
if (values.discountType === "service" && !values.serviceType) {
errors.serviceType = "Сервис не выбран"
}
if (values.discountType === "purchasesAmount" && !isFinite(parseFloat(values.purchasesAmountField.replace(",", ".")))) {
errors.purchasesAmountField = 'Поле "Внесено больше" не число'
}
if (values.discountType === "cartPurchasesAmount" && !isFinite(parseFloat(values.cartPurchasesAmountField.replace(",", ".")))) {
errors.cartPurchasesAmountField = 'Поле "Объём в корзине" не число'
}
if (values.discountType === ("service" || "privilege") && !isFinite(parseFloat(values.discountMinValueField.replace(",", ".")))) {
errors.discountMinValueField = 'Поле "Минимальное значение" не число'
}
console.error(errors)
return errors;
}
if (createdDiscountResponse) {
mutate("discounts");
addDiscount(createdDiscountResponse);
}
};
const validateFulledFields = (values: Values) => {
const errors = {} as any;
if (values.discountNameField.length === 0) {
errors.discountNameField = 'Поле "Имя" пустое';
}
if (values.discountDescriptionField.length === 0) {
errors.discountDescriptionField = 'Поле "Описание" пустое';
}
if ((100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100 < 0) {
errors.discountFactorField = "Процент скидки не может быть больше 100";
}
if (!isFinite((100 - parseFloat(values.discountFactorField.replace(",", "."))) / 100)) {
errors.discountFactorField = 'Поле "Процент скидки" не число';
}
if (values.discountType === "privilege" && !values.privilegeIdField) {
errors.privilegeIdField = "Привилегия не выбрана";
}
if (values.discountType === "service" && !values.serviceType) {
errors.serviceType = "Сервис не выбран";
}
if (
values.discountType === "purchasesAmount" &&
!isFinite(parseFloat(values.purchasesAmountField.replace(",", ".")))
) {
errors.purchasesAmountField = 'Поле "Внесено больше" не число';
}
if (
values.discountType === "cartPurchasesAmount" &&
!isFinite(parseFloat(values.cartPurchasesAmountField.replace(",", ".")))
) {
errors.cartPurchasesAmountField = 'Поле "Объём в корзине" не число';
}
if (
values.discountType === ("service" || "privilege") &&
!isFinite(parseFloat(values.discountMinValueField.replace(",", ".")))
) {
errors.discountMinValueField = 'Поле "Минимальное значение" не число';
}
console.error(errors);
return errors;
};
return (
<Formik
initialValues={initialValues}
onSubmit={handleCreateDiscount}
validate={validateFulledFields}
>
{(props) => (
<Form style={{width: "100%", display: "flex", justifyContent: "center"}}>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginTop: "15px",
width: "100%",
padding: "16px",
maxWidth: "600px",
gap: "1em",
}}
>
<Field
as={TextField}
id="discount-name"
label="Название"
variant="filled"
name="discountNameField"
error={props.touched.discountNameField && !!props.errors.discountNameField}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.discountNameField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<Field
as={TextField}
id="discount-desc"
label="Описание"
variant="filled"
name="discountDescriptionField"
type="text"
error={props.touched.discountDescriptionField && !!props.errors.discountDescriptionField}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.discountDescriptionField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<Typography
variant="h4"
sx={{
width: "90%",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
paddingLeft: "10px",
}}
>
Условия:
</Typography>
<Field
as={TextField}
id="discount-factor"
label="Процент скидки"
variant="filled"
name="discountFactorField"
error={props.touched.discountFactorField && !!props.errors.discountFactorField}
value={props.values.discountFactorField}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.discountFactorField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<FormControl>
<FormLabel
id="discount-type"
sx={{
color: "white",
"&.Mui-focused": {
color: "white",
},
}}
>
Тип скидки
</FormLabel>
<RadioGroup
row
aria-labelledby="discount-type"
name="discountType"
value={props.values.discountType}
onChange={(
event: React.ChangeEvent<HTMLInputElement>
) => {
props.setFieldValue("discountType", event.target.value as DiscountType);
}}
onBlur={props.handleBlur}
>
{Object.keys(discountTypes).map((type) => (
<FormControlLabel
key={type}
value={type}
control={<Radio color="secondary"/>}
label={discountTypes[type as DiscountType]}
/>
))}
</RadioGroup>
</FormControl>
{props.values.discountType === "purchasesAmount" && (
<TextField
id="discount-purchases"
name="purchasesAmountField"
variant="filled"
error={props.touched.purchasesAmountField && !!props.errors.purchasesAmountField}
label="Внесено больше"
onChange={(e) => {
props.setFieldValue("purchasesAmountField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.purchasesAmountField}
onBlur={props.handleBlur}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.purchasesAmountField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
)}
{props.values.discountType === "cartPurchasesAmount" && (
<TextField
id="discount-cart-purchases"
label="Объем в корзине"
name="cartPurchasesAmountField"
variant="filled"
error={props.touched.cartPurchasesAmountField && !!props.errors.cartPurchasesAmountField}
onChange={(e) => {
props.setFieldValue("cartPurchasesAmountField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.cartPurchasesAmountField}
onBlur={props.handleBlur}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.cartPurchasesAmountField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
)}
{props.values.discountType === "service" && (
<>
<Select
labelId="discount-service-label"
id="discount-service"
name="serviceType"
onBlur={props.handleBlur}
onChange={(e) => {
props.setFieldValue("serviceType", e.target.value as ServiceType);
}}
error={props.touched.serviceType && !!props.errors.serviceType}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
>
{SERVICE_LIST.map((service) => (
<MenuItem key={service.serviceKey} value={service.serviceKey}>
{service.displayName}
</MenuItem>
))}
</Select>
<TextField
id="discount-min-value"
name="discountMinValueField"
label="Минимальное значение"
onBlur={props.handleBlur}
variant="filled"
onChange={(e) => {
props.setFieldValue("discountMinValueField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.discountMinValueField}
error={props.touched.discountMinValueField && !!props.errors.discountMinValueField}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.discountMinValueField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
</>
)}
{props.values.discountType === "privilege" && (
<>
<FormControl
fullWidth
sx={{
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
name="privilegeIdField"
onBlur={props.handleBlur}
onChange={(e) => {
props.setFieldValue("privilegeIdField", e.target.value);
}}
error={props.touched.privilegeIdField && !!props.errors.privilegeIdField}
label="Привилегия"
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{sx: {pt: "12px"}}}
>
{privileges.map((privilege, index) => (
<MenuItem key={index} value={privilege.privilegeId}>
{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
id="discount-min-value"
name="discountMinValueField"
label="Минимальное значение"
onBlur={props.handleBlur}
variant="filled"
onChange={(e) => {
props.setFieldValue("discountMinValueField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.discountMinValueField}
error={props.touched.discountMinValueField && !!props.errors.discountMinValueField}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{fontSize: "12px", width: "200px"}}>
{props.errors.discountMinValueField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
</>
)}
<Box
sx={{
width: "90%",
marginTop: "55px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
variant="contained"
type='submit'
sx={{
backgroundColor: theme.palette.menu.main,
height: "52px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Создать
</Button>
</Box>
</Box>
</Form>
)}
</Formik>
);
return (
<Formik initialValues={initialValues} onSubmit={handleCreateDiscount} validate={validateFulledFields}>
{(props) => (
<Form style={{ width: "100%", display: "flex", justifyContent: "center" }}>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginTop: "15px",
width: "100%",
padding: "16px",
maxWidth: "600px",
gap: "1em",
}}
>
<Field
as={TextField}
id="discount-name"
label="Название"
variant="filled"
name="discountNameField"
error={props.touched.discountNameField && !!props.errors.discountNameField}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>{props.errors.discountNameField}</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<Field
as={TextField}
id="discount-desc"
label="Описание"
variant="filled"
name="discountDescriptionField"
type="text"
error={props.touched.discountDescriptionField && !!props.errors.discountDescriptionField}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.discountDescriptionField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<Typography
variant="h4"
sx={{
width: "90%",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
paddingLeft: "10px",
}}
>
Условия:
</Typography>
<Field
as={TextField}
id="discount-factor"
label="Процент скидки"
variant="filled"
name="discountFactorField"
error={props.touched.discountFactorField && !!props.errors.discountFactorField}
value={props.values.discountFactorField}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>{props.errors.discountFactorField}</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<FormControl>
<FormLabel
id="discount-type"
sx={{
color: "white",
"&.Mui-focused": {
color: "white",
},
}}
>
Тип скидки
</FormLabel>
<RadioGroup
row
aria-labelledby="discount-type"
name="discountType"
value={props.values.discountType}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
props.setFieldValue("discountType", event.target.value as DiscountType);
}}
onBlur={props.handleBlur}
>
{Object.keys(discountTypes).map((type) => (
<FormControlLabel
key={type}
value={type}
control={<Radio color="secondary" />}
label={discountTypes[type as DiscountType]}
/>
))}
</RadioGroup>
</FormControl>
{props.values.discountType === "purchasesAmount" && (
<TextField
id="discount-purchases"
name="purchasesAmountField"
variant="filled"
error={props.touched.purchasesAmountField && !!props.errors.purchasesAmountField}
label="Внесено больше"
onChange={(e) => {
props.setFieldValue("purchasesAmountField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.purchasesAmountField}
onBlur={props.handleBlur}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>{props.errors.purchasesAmountField}</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
)}
{props.values.discountType === "cartPurchasesAmount" && (
<TextField
id="discount-cart-purchases"
label="Объем в корзине"
name="cartPurchasesAmountField"
variant="filled"
error={props.touched.cartPurchasesAmountField && !!props.errors.cartPurchasesAmountField}
onChange={(e) => {
props.setFieldValue("cartPurchasesAmountField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.cartPurchasesAmountField}
onBlur={props.handleBlur}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.cartPurchasesAmountField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
)}
{props.values.discountType === "service" && (
<>
<Select
labelId="discount-service-label"
id="discount-service"
name="serviceType"
onBlur={props.handleBlur}
onChange={(e) => {
props.setFieldValue("serviceType", e.target.value as ServiceType);
}}
error={props.touched.serviceType && !!props.errors.serviceType}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
>
{SERVICE_LIST.map((service) => (
<MenuItem key={service.serviceKey} value={service.serviceKey}>
{service.displayName}
</MenuItem>
))}
</Select>
<TextField
id="discount-min-value"
name="discountMinValueField"
label="Минимальное значение"
onBlur={props.handleBlur}
variant="filled"
onChange={(e) => {
props.setFieldValue("discountMinValueField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.discountMinValueField}
error={props.touched.discountMinValueField && !!props.errors.discountMinValueField}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.discountMinValueField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</>
)}
{props.values.discountType === "privilege" && (
<>
<FormControl
fullWidth
sx={{
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
name="privilegeIdField"
onBlur={props.handleBlur}
onChange={(e) => {
props.setFieldValue("privilegeIdField", e.target.value);
}}
error={props.touched.privilegeIdField && !!props.errors.privilegeIdField}
label="Привилегия"
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{ sx: { pt: "12px" } }}
>
{privileges.map((privilege, index) => (
<MenuItem key={index} value={privilege.privilegeId}>
{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
id="discount-min-value"
name="discountMinValueField"
label="Минимальное значение"
onBlur={props.handleBlur}
variant="filled"
onChange={(e) => {
props.setFieldValue("discountMinValueField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.discountMinValueField}
error={props.touched.discountMinValueField && !!props.errors.discountMinValueField}
sx={{
marginTop: "15px",
}}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.discountMinValueField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
</>
)}
<Box
sx={{
width: "90%",
marginTop: "55px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
variant="contained"
type="submit"
sx={{
backgroundColor: theme.palette.menu.main,
height: "52px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Создать
</Button>
</Box>
</Box>
</Form>
)}
</Formik>
);
}

@ -3,133 +3,133 @@ import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import { useState } from "react";
export default function DatePickers() {
const theme = useTheme();
const [isInfinite, setIsInfinite] = useState<boolean>(false);
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
const theme = useTheme();
const [isInfinite, setIsInfinite] = useState<boolean>(false);
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
return (
<>
<Typography
variant="h4"
sx={{
width: "90%",
height: "40px",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
marginTop: "55px",
}}
>
Дата действия:
</Typography>
<Box
sx={{
width: "100%",
display: "flex",
flexWrap: "wrap",
}}
>
<Typography
sx={{
width: "35px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "left",
}}
>
С
</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={startDate}
onChange={(e) => {
if (e) {
setStartDate(e);
}
}}
renderInput={(params) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
<Typography
sx={{
width: "65px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
по
</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={endDate}
onChange={(e) => {
if (e) {
setEndDate(e);
}
}}
renderInput={(params) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
</Box>
<Box
sx={{
display: "flex",
width: "90%",
marginTop: theme.spacing(2),
}}
>
<Box
sx={{
width: "20px",
height: "42px",
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginRight: theme.spacing(1),
}}
>
<Checkbox
sx={{
color: theme.palette.secondary.main,
"&.Mui-checked": {
color: theme.palette.secondary.main,
},
}}
checked={isInfinite}
onClick={() => setIsInfinite((p) => !p)}
/>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
Бессрочно
</Box>
</Box>
</>
);
return (
<>
<Typography
variant="h4"
sx={{
width: "90%",
height: "40px",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
marginTop: "55px",
}}
>
Дата действия:
</Typography>
<Box
sx={{
width: "100%",
display: "flex",
flexWrap: "wrap",
}}
>
<Typography
sx={{
width: "35px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "left",
}}
>
С
</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={startDate}
onChange={(e) => {
if (e) {
setStartDate(e);
}
}}
renderInput={(params) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
<Typography
sx={{
width: "65px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
по
</Typography>
<DesktopDatePicker
inputFormat="DD/MM/YYYY"
value={endDate}
onChange={(e) => {
if (e) {
setEndDate(e);
}
}}
renderInput={(params) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
</Box>
<Box
sx={{
display: "flex",
width: "90%",
marginTop: theme.spacing(2),
}}
>
<Box
sx={{
width: "20px",
height: "42px",
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginRight: theme.spacing(1),
}}
>
<Checkbox
sx={{
color: theme.palette.secondary.main,
"&.Mui-checked": {
color: theme.palette.secondary.main,
},
}}
checked={isInfinite}
onClick={() => setIsInfinite((p) => !p)}
/>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
Бессрочно
</Box>
</Box>
</>
);
}

@ -1,16 +1,11 @@
import { useEffect } from "react";
import { Box, IconButton, useTheme, Tooltip } from "@mui/material";
import { DataGrid, GridColDef, GridRowsProp, GridToolbar } from "@mui/x-data-grid";
import {
DataGrid,
GridColDef,
GridRowsProp,
GridToolbar,
} from "@mui/x-data-grid";
import {
openEditDiscountDialog,
setSelectedDiscountIds,
updateDiscount,
useDiscountStore,
openEditDiscountDialog,
setSelectedDiscountIds,
updateDiscount,
useDiscountStore,
} from "@root/stores/discounts";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
@ -22,180 +17,163 @@ import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
import { mutate } from "swr";
const columns: GridColDef[] = [
// {
// field: "id",
// headerName: "ID",
// width: 70,
// sortable: false,
// },
{
field: "name",
headerName: "Название скидки",
width: 150,
sortable: false,
renderCell: ({ row, value }) => (
<Box color={row.deleted && "#ff4545"}>{value}</Box>
),
},
{
field: "description",
headerName: "Описание",
width: 120,
sortable: false,
},
{
field: "conditionType",
headerName: "Тип условия",
width: 120,
sortable: false,
},
{
field: "factor",
headerName: "Процент скидки",
width: 120,
sortable: false,
},
{
field: "value",
headerName: "Значение",
width: 120,
sortable: false,
},
{
field: "active",
headerName: "Активна",
width: 80,
sortable: false,
},
{
field: "edit",
headerName: "Изменить",
width: 80,
sortable: false,
renderCell: ({ row }) => {
return (
<IconButton
onClick={() => {
openEditDiscountDialog(row.id);
}}
>
<EditIcon />
</IconButton>
);
},
},
{
field: "delete",
headerName: "Удалить",
width: 80,
sortable: false,
renderCell: ({ row }) => (
<IconButton
disabled={row.deleted}
onClick={() => {
deleteDiscount(row.id).then(([discount]) => {
mutate("discounts");
if (discount) {
updateDiscount(discount);
}
});
}}
>
<DeleteIcon />
</IconButton>
),
},
// {
// field: "id",
// headerName: "ID",
// width: 70,
// sortable: false,
// },
{
field: "name",
headerName: "Название скидки",
width: 150,
sortable: false,
renderCell: ({ row, value }) => <Box color={row.deleted && "#ff4545"}>{value}</Box>,
},
{
field: "description",
headerName: "Описание",
width: 120,
sortable: false,
},
{
field: "conditionType",
headerName: "Тип условия",
width: 120,
sortable: false,
},
{
field: "factor",
headerName: "Процент скидки",
width: 120,
sortable: false,
},
{
field: "value",
headerName: "Значение",
width: 120,
sortable: false,
},
{
field: "active",
headerName: "Активна",
width: 80,
sortable: false,
},
{
field: "edit",
headerName: "Изменить",
width: 80,
sortable: false,
renderCell: ({ row }) => {
return (
<IconButton
onClick={() => {
openEditDiscountDialog(row.id);
}}
>
<EditIcon />
</IconButton>
);
},
},
{
field: "delete",
headerName: "Удалить",
width: 80,
sortable: false,
renderCell: ({ row }) => (
<IconButton
disabled={row.deleted}
onClick={() => {
deleteDiscount(row.id).then(([discount]) => {
mutate("discounts");
if (discount) {
updateDiscount(discount);
}
});
}}
>
<DeleteIcon />
</IconButton>
),
},
];
const layerTranslate = ["", "Товар", "Сервис", "корзина", "лояльность"];
const layerValue = [
"",
"Term",
"PriceFrom",
"CartPurchasesAmount",
"PurchasesAmount",
];
const layerValue = ["", "Term", "PriceFrom", "CartPurchasesAmount", "PurchasesAmount"];
interface Props {
selectedRowsHC: (array: GridSelectionModel) => void;
selectedRowsHC: (array: GridSelectionModel) => void;
}
export default function DiscountDataGrid({ selectedRowsHC }: Props) {
const theme = useTheme();
const selectedDiscountIds = useDiscountStore(
(state) => state.selectedDiscountIds
);
const realDiscounts = useDiscountStore((state) => state.discounts);
const theme = useTheme();
const selectedDiscountIds = useDiscountStore((state) => state.selectedDiscountIds);
const realDiscounts = useDiscountStore((state) => state.discounts);
useEffect(() => {
requestDiscounts();
}, []);
useEffect(() => {
requestDiscounts();
}, []);
const rowBackDicounts: GridRowsProp = realDiscounts
.filter(({ Layer }) => Layer > 0)
.map((discount) => {
return {
id: discount.ID,
name: discount.Name,
description: discount.Description,
conditionType: layerTranslate[discount.Layer],
factor: formatDiscountFactor(discount.Target.Factor),
value: (discount.Layer === 1) ?
discount.Condition[
layerValue[discount.Layer] as keyof typeof discount.Condition
]: Number(discount.Condition[
layerValue[discount.Layer] as keyof typeof discount.Condition
])/100,
active: discount.Deprecated ? "🚫" : "✅",
deleted: discount.Audit.Deleted,
};
});
const rowBackDicounts: GridRowsProp = realDiscounts
.filter(({ Layer }) => Layer > 0)
.map((discount) => {
return {
id: discount.ID,
name: discount.Name,
description: discount.Description,
conditionType: layerTranslate[discount.Layer],
factor: formatDiscountFactor(discount.Target.Factor),
value:
discount.Layer === 1
? discount.Condition[layerValue[discount.Layer] as keyof typeof discount.Condition]
: Number(discount.Condition[layerValue[discount.Layer] as keyof typeof discount.Condition]) / 100,
active: discount.Deprecated ? "🚫" : "✅",
deleted: discount.Audit.Deleted,
};
});
return (
<Box
sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}
>
<Tooltip title="обновить список привилегий">
<IconButton
onClick={requestDiscounts}
style={{ display: "block", margin: "0 auto" }}
>
<AutorenewIcon sx={{ color: "white" }} />
</IconButton>
</Tooltip>
<Box sx={{ height: 600 }}>
<DataGrid
checkboxSelection={true}
rows={rowBackDicounts}
columns={columns}
selectionModel={selectedDiscountIds}
onSelectionModelChange={(array: GridSelectionModel) => {
selectedRowsHC(array);
setSelectedDiscountIds(array);
}}
disableSelectionOnClick
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none",
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main,
},
"& .MuiButton-text": {
color: theme.palette.secondary.main,
},
}}
components={{ Toolbar: GridToolbar }}
/>
</Box>
</Box>
);
return (
<Box sx={{ width: "100%", marginTop: "55px", p: "16px", maxWidth: "1000px" }}>
<Tooltip title="обновить список привилегий">
<IconButton onClick={requestDiscounts} style={{ display: "block", margin: "0 auto" }}>
<AutorenewIcon sx={{ color: "white" }} />
</IconButton>
</Tooltip>
<Box sx={{ height: 600 }}>
<DataGrid
checkboxSelection={true}
rows={rowBackDicounts}
columns={columns}
selectionModel={selectedDiscountIds}
onSelectionModelChange={(array: GridSelectionModel) => {
selectedRowsHC(array);
setSelectedDiscountIds(array);
}}
disableSelectionOnClick
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": {
display: "none",
},
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": {
color: theme.palette.secondary.main,
},
"& .MuiButton-text": {
color: theme.palette.secondary.main,
},
}}
components={{ Toolbar: GridToolbar }}
/>
</Box>
</Box>
);
}

@ -8,38 +8,35 @@ import ControlPanel from "./ControlPanel";
import { useState } from "react";
import { GridSelectionModel } from "@mui/x-data-grid";
const DiscountManagement: React.FC = () => {
const theme = useTheme();
const [selectedRows, setSelectedRows] = useState<GridSelectionModel>([])
const selectedRowsHC = (array:GridSelectionModel) => {
setSelectedRows(array)
}
const theme = useTheme();
const [selectedRows, setSelectedRows] = useState<GridSelectionModel>([]);
const selectedRowsHC = (array: GridSelectionModel) => {
setSelectedRows(array);
};
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main
}}>
СКИДКИ
</Typography>
<CreateDiscount />
<DiscountDataGrid
selectedRowsHC={selectedRowsHC}
/>
<EditDiscountDialog />
<ControlPanel selectedRows={selectedRows}/>
</LocalizationProvider>
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main,
}}
>
СКИДКИ
</Typography>
<CreateDiscount />
<DiscountDataGrid selectedRowsHC={selectedRowsHC} />
<EditDiscountDialog />
<ControlPanel selectedRows={selectedRows} />
</LocalizationProvider>
);
};
export default DiscountManagement;

@ -1,32 +1,25 @@
import {
Box,
Button,
Dialog,
FormControl,
FormControlLabel,
FormLabel,
InputLabel,
MenuItem,
Radio,
RadioGroup,
Select,
SelectChangeEvent,
Typography,
useTheme,
Box,
Button,
Dialog,
FormControl,
FormControlLabel,
FormLabel,
InputLabel,
MenuItem,
Radio,
RadioGroup,
Select,
SelectChangeEvent,
Typography,
useTheme,
} from "@mui/material";
import { patchDiscount } from "@root/api/discounts";
import { CustomTextField } from "@root/kitUI/CustomTextField";
import { DiscountType, discountTypes } from "@root/model/discount";
import { ServiceType, SERVICE_LIST } from "@root/model/tariff";
import {
closeEditDiscountDialog,
updateDiscount,
useDiscountStore,
} from "@root/stores/discounts";
import {
resetPrivilegeArray,
usePrivilegeStore,
} from "@root/stores/privilegesStore";
import { closeEditDiscountDialog, updateDiscount, useDiscountStore } from "@root/stores/discounts";
import { resetPrivilegeArray, usePrivilegeStore } from "@root/stores/privilegesStore";
import { getDiscountTypeFromLayer } from "@root/utils/discount";
import usePrivileges from "@root/utils/hooks/usePrivileges";
import { enqueueSnackbar } from "notistack";
@ -34,359 +27,336 @@ import { useEffect, useState } from "react";
import { mutate } from "swr";
export default function EditDiscountDialog() {
const theme = useTheme();
const editDiscountId = useDiscountStore((state) => state.editDiscountId);
const discounts = useDiscountStore((state) => state.discounts);
const privileges = usePrivilegeStore((state) => state.privileges);
const [serviceType, setServiceType] = useState<string>("templategen");
const [discountType, setDiscountType] =
useState<DiscountType>("purchasesAmount");
const [discountNameField, setDiscountNameField] = useState<string>("");
const [discountDescriptionField, setDiscountDescriptionField] =
useState<string>("");
const [privilegeIdField, setPrivilegeIdField] = useState<string | "">("");
const [discountFactorField, setDiscountFactorField] = useState<string>("0");
const [purchasesAmountField, setPurchasesAmountField] = useState<string>("0");
const [cartPurchasesAmountField, setCartPurchasesAmountField] =
useState<string>("0");
const [discountMinValueField, setDiscountMinValueField] =
useState<string>("0");
const theme = useTheme();
const editDiscountId = useDiscountStore((state) => state.editDiscountId);
const discounts = useDiscountStore((state) => state.discounts);
const privileges = usePrivilegeStore((state) => state.privileges);
const [serviceType, setServiceType] = useState<string>("templategen");
const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
const [discountNameField, setDiscountNameField] = useState<string>("");
const [discountDescriptionField, setDiscountDescriptionField] = useState<string>("");
const [privilegeIdField, setPrivilegeIdField] = useState<string | "">("");
const [discountFactorField, setDiscountFactorField] = useState<string>("0");
const [purchasesAmountField, setPurchasesAmountField] = useState<string>("0");
const [cartPurchasesAmountField, setCartPurchasesAmountField] = useState<string>("0");
const [discountMinValueField, setDiscountMinValueField] = useState<string>("0");
const discount = discounts.find((discount) => discount.ID === editDiscountId);
const discount = discounts.find((discount) => discount.ID === editDiscountId);
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
usePrivileges({ onNewPrivileges: resetPrivilegeArray });
useEffect(
function setDiscountFields() {
if (!discount) return;
useEffect(
function setDiscountFields() {
if (!discount) return;
setServiceType(discount.Condition.Group ?? "");
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
setDiscountNameField(discount.Name);
setDiscountDescriptionField(discount.Description);
setPrivilegeIdField(discount.Condition.Product ?? "");
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
setPurchasesAmountField(discount.Condition.PurchasesAmount ?? "");
setCartPurchasesAmountField(
discount.Condition.CartPurchasesAmount ?? ""
);
setDiscountMinValueField(discount.Condition.PriceFrom ?? "");
},
[discount]
);
setServiceType(discount.Condition.Group ?? "");
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
setDiscountNameField(discount.Name);
setDiscountDescriptionField(discount.Description);
setPrivilegeIdField(discount.Condition.Product ?? "");
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
setPurchasesAmountField(discount.Condition.PurchasesAmount ?? "");
setCartPurchasesAmountField(discount.Condition.CartPurchasesAmount ?? "");
setDiscountMinValueField(discount.Condition.PriceFrom ?? "");
},
[discount]
);
const handleDiscountTypeChange = (
event: React.ChangeEvent<HTMLInputElement>
) => {
setDiscountType(event.target.value as DiscountType);
};
const handleDiscountTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setDiscountType(event.target.value as DiscountType);
};
const handleServiceTypeChange = (event: SelectChangeEvent) => {
setServiceType(event.target.value as ServiceType);
};
const handleServiceTypeChange = (event: SelectChangeEvent) => {
setServiceType(event.target.value as ServiceType);
};
async function handleSaveDiscount() {
if (!discount) return;
async function handleSaveDiscount() {
if (!discount) return;
const purchasesAmount = parseFloat(purchasesAmountField.replace(",", "."));
const discountFactor =
(100 - parseFloat(discountFactorField.replace(",", "."))) / 100;
const cartPurchasesAmount = parseFloat(
cartPurchasesAmountField.replace(",", ".")
);
const discountMinValue = parseFloat(
discountMinValueField.replace(",", ".")
);
const purchasesAmount = parseFloat(purchasesAmountField.replace(",", "."));
const discountFactor = (100 - parseFloat(discountFactorField.replace(",", "."))) / 100;
const cartPurchasesAmount = parseFloat(cartPurchasesAmountField.replace(",", "."));
const discountMinValue = parseFloat(discountMinValueField.replace(",", "."));
if (!isFinite(purchasesAmount))
return enqueueSnackbar("Поле purchasesAmount не число");
if (!isFinite(discountFactor))
return enqueueSnackbar("Поле discountFactor не число");
if (!isFinite(cartPurchasesAmount))
return enqueueSnackbar("Поле cartPurchasesAmount не число");
if (!isFinite(discountMinValue))
return enqueueSnackbar("Поле discountMinValue не число");
if (discountType === "privilege" && !privilegeIdField)
return enqueueSnackbar("Привилегия не выбрана");
if (!discountNameField) return enqueueSnackbar('Поле "Имя" пустое');
if (!discountDescriptionField)
return enqueueSnackbar('Поле "Описание" пустое');
if (discountFactor < 0)
return enqueueSnackbar("Процент скидки не может быть больше 100");
if (!isFinite(purchasesAmount)) return enqueueSnackbar("Поле purchasesAmount не число");
if (!isFinite(discountFactor)) return enqueueSnackbar("Поле discountFactor не число");
if (!isFinite(cartPurchasesAmount)) return enqueueSnackbar("Поле cartPurchasesAmount не число");
if (!isFinite(discountMinValue)) return enqueueSnackbar("Поле discountMinValue не число");
if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана");
if (!discountNameField) return enqueueSnackbar('Поле "Имя" пустое');
if (!discountDescriptionField) return enqueueSnackbar('Поле "Описание" пустое');
if (discountFactor < 0) return enqueueSnackbar("Процент скидки не может быть больше 100");
const [patchedDiscountResponse, patchedDiscountError] = await patchDiscount(
discount.ID,
{
cartPurchasesAmount,
discountFactor,
discountMinValue,
purchasesAmount,
discountDescription: discountDescriptionField,
discountName: discountNameField,
startDate: new Date().toISOString(),
endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
serviceType,
discountType,
privilegeId: privilegeIdField,
}
);
const [patchedDiscountResponse, patchedDiscountError] = await patchDiscount(discount.ID, {
cartPurchasesAmount,
discountFactor,
discountMinValue,
purchasesAmount,
discountDescription: discountDescriptionField,
discountName: discountNameField,
startDate: new Date().toISOString(),
endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
serviceType,
discountType,
privilegeId: privilegeIdField,
});
if (patchedDiscountError) {
console.error("Error patching discount", patchedDiscountError);
if (patchedDiscountError) {
console.error("Error patching discount", patchedDiscountError);
return enqueueSnackbar(patchedDiscountError);
}
return enqueueSnackbar(patchedDiscountError);
}
if (patchedDiscountResponse) {
mutate("discounts");
updateDiscount(patchedDiscountResponse);
closeEditDiscountDialog();
}
}
if (patchedDiscountResponse) {
mutate("discounts");
updateDiscount(patchedDiscountResponse);
closeEditDiscountDialog();
}
}
return (
<Dialog
open={editDiscountId !== null}
onClose={closeEditDiscountDialog}
PaperProps={{
sx: {
width: "600px",
maxWidth: "600px",
backgroundColor: theme.palette.grayMedium.main,
position: "relative",
display: "flex",
flexDirection: "column",
p: "20px",
gap: "20px",
borderRadius: "12px",
boxShadow: "none",
},
}}
slotProps={{
backdrop: { style: { backgroundColor: "rgb(0 0 0 / 0.7)" } },
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginTop: "15px",
width: "100%",
padding: "16px",
maxWidth: "600px",
gap: "1em",
}}
>
<CustomTextField
id="discount-name"
label="Название"
value={discountNameField}
onChange={(e) => setDiscountNameField(e.target.value)}
/>
<CustomTextField
id="discount-desc"
label="Описание"
value={discountDescriptionField}
onChange={(e) => setDiscountDescriptionField(e.target.value)}
/>
<Typography
variant="h4"
sx={{
width: "90%",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
paddingLeft: "10px",
}}
>
Условия:
</Typography>
<CustomTextField
id="discount-factor"
label="Процент скидки"
value={discountFactorField}
type="number"
onChange={(e) => setDiscountFactorField(e.target.value)}
/>
<FormControl>
<FormLabel
id="discount-type"
sx={{
color: "white",
"&.Mui-focused": {
color: "white",
},
}}
>
Тип скидки
</FormLabel>
<RadioGroup
row
aria-labelledby="discount-type"
name="discount-type"
value={discountType}
onChange={handleDiscountTypeChange}
>
{Object.keys(discountTypes).map((type) => (
<FormControlLabel
key={type}
value={type}
control={<Radio color="secondary" />}
label={discountTypes[type as DiscountType]}
sx={{ color: "white" }}
/>
))}
</RadioGroup>
</FormControl>
{discountType === "purchasesAmount" && (
<CustomTextField
id="discount-purchases"
label="Внесено больше"
type="number"
sx={{
marginTop: "15px",
}}
value={purchasesAmountField}
onChange={(e) => setPurchasesAmountField(e.target.value)}
/>
)}
{discountType === "cartPurchasesAmount" && (
<CustomTextField
id="discount-cart-purchases"
label="Объем в корзине"
type="number"
sx={{
marginTop: "15px",
}}
value={cartPurchasesAmountField}
onChange={(e) => setCartPurchasesAmountField(e.target.value)}
/>
)}
{discountType === "service" && (
<>
<Select
labelId="discount-service-label"
id="discount-service"
value={serviceType}
onChange={handleServiceTypeChange}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
>
{SERVICE_LIST.map((service) => (
<MenuItem key={service.serviceKey} value={service.serviceKey}>
{service.displayName}
</MenuItem>
))}
</Select>
<CustomTextField
id="discount-min-value"
label="Минимальное значение"
type="number"
sx={{
marginTop: "15px",
}}
value={discountMinValueField}
onChange={(e) => setDiscountMinValueField(e.target.value)}
/>
</>
)}
{discountType === "privilege" && (
<>
<FormControl
fullWidth
sx={{
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
value={privilegeIdField}
label="Привилегия"
onChange={(e) => setPrivilegeIdField(e.target.value)}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{ sx: { pt: "12px" } }}
>
{privileges.map((privilege, index) => (
<MenuItem key={index} value={privilege.privilegeId}>
{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
<CustomTextField
id="discount-min-value"
label="Минимальное значение"
type="number"
sx={{
marginTop: "15px",
}}
value={discountMinValueField}
onChange={(e) => setDiscountMinValueField(e.target.value)}
/>
</>
)}
<Box
sx={{
width: "90%",
marginTop: "55px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
variant="contained"
sx={{
backgroundColor: theme.palette.menu.main,
height: "52px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
onClick={handleSaveDiscount}
>
Сохранить
</Button>
</Box>
</Box>
</Dialog>
);
return (
<Dialog
open={editDiscountId !== null}
onClose={closeEditDiscountDialog}
PaperProps={{
sx: {
width: "600px",
maxWidth: "600px",
backgroundColor: theme.palette.grayMedium.main,
position: "relative",
display: "flex",
flexDirection: "column",
p: "20px",
gap: "20px",
borderRadius: "12px",
boxShadow: "none",
},
}}
slotProps={{
backdrop: { style: { backgroundColor: "rgb(0 0 0 / 0.7)" } },
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent: "left",
alignItems: "left",
marginTop: "15px",
width: "100%",
padding: "16px",
maxWidth: "600px",
gap: "1em",
}}
>
<CustomTextField
id="discount-name"
label="Название"
value={discountNameField}
onChange={(e) => setDiscountNameField(e.target.value)}
/>
<CustomTextField
id="discount-desc"
label="Описание"
value={discountDescriptionField}
onChange={(e) => setDiscountDescriptionField(e.target.value)}
/>
<Typography
variant="h4"
sx={{
width: "90%",
fontWeight: "normal",
color: theme.palette.grayDisabled.main,
paddingLeft: "10px",
}}
>
Условия:
</Typography>
<CustomTextField
id="discount-factor"
label="Процент скидки"
value={discountFactorField}
type="number"
onChange={(e) => setDiscountFactorField(e.target.value)}
/>
<FormControl>
<FormLabel
id="discount-type"
sx={{
color: "white",
"&.Mui-focused": {
color: "white",
},
}}
>
Тип скидки
</FormLabel>
<RadioGroup
row
aria-labelledby="discount-type"
name="discount-type"
value={discountType}
onChange={handleDiscountTypeChange}
>
{Object.keys(discountTypes).map((type) => (
<FormControlLabel
key={type}
value={type}
control={<Radio color="secondary" />}
label={discountTypes[type as DiscountType]}
sx={{ color: "white" }}
/>
))}
</RadioGroup>
</FormControl>
{discountType === "purchasesAmount" && (
<CustomTextField
id="discount-purchases"
label="Внесено больше"
type="number"
sx={{
marginTop: "15px",
}}
value={purchasesAmountField}
onChange={(e) => setPurchasesAmountField(e.target.value)}
/>
)}
{discountType === "cartPurchasesAmount" && (
<CustomTextField
id="discount-cart-purchases"
label="Объем в корзине"
type="number"
sx={{
marginTop: "15px",
}}
value={cartPurchasesAmountField}
onChange={(e) => setCartPurchasesAmountField(e.target.value)}
/>
)}
{discountType === "service" && (
<>
<Select
labelId="discount-service-label"
id="discount-service"
value={serviceType}
onChange={handleServiceTypeChange}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
>
{SERVICE_LIST.map((service) => (
<MenuItem key={service.serviceKey} value={service.serviceKey}>
{service.displayName}
</MenuItem>
))}
</Select>
<CustomTextField
id="discount-min-value"
label="Минимальное значение"
type="number"
sx={{
marginTop: "15px",
}}
value={discountMinValueField}
onChange={(e) => setDiscountMinValueField(e.target.value)}
/>
</>
)}
{discountType === "privilege" && (
<>
<FormControl
fullWidth
sx={{
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
value={privilegeIdField}
label="Привилегия"
onChange={(e) => setPrivilegeIdField(e.target.value)}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{ sx: { pt: "12px" } }}
>
{privileges.map((privilege, index) => (
<MenuItem key={index} value={privilege.privilegeId}>
{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
<CustomTextField
id="discount-min-value"
label="Минимальное значение"
type="number"
sx={{
marginTop: "15px",
}}
value={discountMinValueField}
onChange={(e) => setDiscountMinValueField(e.target.value)}
/>
</>
)}
<Box
sx={{
width: "90%",
marginTop: "55px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
variant="contained"
sx={{
backgroundColor: theme.palette.menu.main,
height: "52px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
onClick={handleSaveDiscount}
>
Сохранить
</Button>
</Box>
</Box>
</Dialog>
);
}

@ -1,142 +1,169 @@
import * as React from "react";
import { useNavigate } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { Typography } from "@mui/material";
import Table from '@mui/material/Table';
import TableHead from '@mui/material/TableHead';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableRow from '@mui/material/TableRow';
import Table from "@mui/material/Table";
import TableHead from "@mui/material/TableHead";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableRow from "@mui/material/TableRow";
import theme from "../../../theme";
const Users: React.FC = () => {
const [selectedValue, setSelectedValue] = React.useState("a");
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedValue(event.target.value);
};
const Users: React.FC = () => {
const [selectedValue, setSelectedValue] = React.useState('a');
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSelectedValue(event.target.value);
};
const navigate = useNavigate();
const navigate = useNavigate();
return (
<React.Fragment>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main,
}}
>
Юридические лица
</Typography>
return (
<React.Fragment>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main
}}>
Юридические лица
</Typography>
<Table
sx={{
width: "90%",
border: "2px solid",
borderColor: theme.palette.grayLight.main,
marginTop: "35px",
}}
aria-label="simple table"
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ textAlign: "center" }}>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
ID
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}
>
Дата / время регистрации
</Typography>
</TableCell>
</TableRow>
</TableHead>
<Table sx={{
width: "90%",
border: "2px solid",
borderColor: theme.palette.grayLight.main,
marginTop: "35px",
}} aria-label="simple table">
<TableHead>
<TableRow sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px"
}}>
<TableCell sx={{ textAlign: "center" }}>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}>
ID
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography
variant="h4"
sx={{
color: theme.palette.secondary.main,
}}>
Дата / время регистрации
</Typography>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
cursor: "pointer",
}}
onClick={() => navigate("/modalEntities")}
>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
1
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
2022
</Typography>
</TableCell>
</TableRow>
<TableBody>
<TableRow sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
cursor: "pointer"
}} onClick={ () => navigate("/modalEntities") }>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
1
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
2022
</Typography>
</TableCell>
</TableRow>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
cursor: "pointer",
}}
onClick={() => navigate("/modalEntities")}
>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
2
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
2021
</Typography>
</TableCell>
</TableRow>
<TableRow sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
cursor: "pointer"
}} onClick={ () => navigate("/modalEntities") }>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
2
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
2021
</Typography>
</TableCell>
</TableRow>
<TableRow
sx={{
borderBottom: "1px solid",
border: theme.palette.secondary.main,
height: "100px",
cursor: "pointer",
}}
onClick={() => navigate("/modalEntities")}
>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
3
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography
sx={{
color: theme.palette.secondary.main,
}}
>
2020
</Typography>
</TableCell>
</TableRow>
</TableBody>
</Table>
</React.Fragment>
);
};
<TableRow sx={{
borderBottom: "1px solid",
border: theme.palette.secondary.main,
height: "100px",
cursor: "pointer"
}} onClick={ () => navigate("/modalEntities") }>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
3
</Typography>
</TableCell>
<TableCell sx={{ textAlign: "center" }}>
<Typography sx={{
color: theme.palette.secondary.main
}}>
2020
</Typography>
</TableCell>
</TableRow>
</TableBody>
</Table>
</React.Fragment>
);
}
export default Users;
export default Users;

@ -1,13 +1,4 @@
import {
Button,
FormControlLabel,
MenuItem,
Radio,
RadioGroup,
Select,
TextField,
Typography,
} from "@mui/material";
import { Button, FormControlLabel, MenuItem, Radio, RadioGroup, Select, TextField, Typography } from "@mui/material";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import { Field, Form, Formik } from "formik";
import { useEffect, useState } from "react";
@ -26,406 +17,347 @@ import { enqueueSnackbar } from "notistack";
type BonusType = "discount" | "privilege";
type FormValues = {
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
privilegeId: string;
amount: number;
layer: 1 | 2;
factor: number;
target: string;
threshold: number;
serviceKey: string;
codeword: string;
description: string;
greetings: string;
dueTo: number;
activationCount: number;
privilegeId: string;
amount: number;
layer: 1 | 2;
factor: number;
target: string;
threshold: number;
serviceKey: string;
};
type SelectChangeProps = {
target: {
name: string;
value: string;
};
target: {
name: string;
value: string;
};
};
const initialValues: FormValues = {
codeword: "",
description: "",
greetings: "",
dueTo: 0,
activationCount: 0,
privilegeId: "",
amount: 0,
layer: 1,
factor: 0,
target: "",
threshold: 0,
serviceKey: "",
codeword: "",
description: "",
greetings: "",
dueTo: 0,
activationCount: 0,
privilegeId: "",
amount: 0,
layer: 1,
factor: 0,
target: "",
threshold: 0,
serviceKey: "",
};
type Props = {
createPromocode: (body: CreatePromocodeBody) => Promise<void>;
createPromocode: (body: CreatePromocodeBody) => Promise<void>;
};
export const CreatePromocodeForm = ({ createPromocode }: Props) => {
const [bonusType, setBonusType] = useState<BonusType>("discount");
const { privileges } = usePrivilegeStore();
const [bonusType, setBonusType] = useState<BonusType>("discount");
const { privileges } = usePrivilegeStore();
useEffect(() => {
requestPrivileges();
}, []);
useEffect(() => {
requestPrivileges();
}, []);
const submitForm = (values: FormValues) => {
const currentPrivilege = privileges.find(
(item) => item.privilegeId === values.privilegeId
);
const submitForm = (values: FormValues) => {
const currentPrivilege = privileges.find((item) => item.privilegeId === values.privilegeId);
const body = { ...values };
const body = { ...values };
if (
(body.layer === 1 && bonusType === "discount") ||
bonusType === "privilege"
) {
if (currentPrivilege === undefined) {
enqueueSnackbar("Привилегия не выбрана");
if ((body.layer === 1 && bonusType === "discount") || bonusType === "privilege") {
if (currentPrivilege === undefined) {
enqueueSnackbar("Привилегия не выбрана");
return;
}
return;
}
body.serviceKey = currentPrivilege?.serviceKey;
body.target = body.privilegeId;
}
if (body.layer === 2 && bonusType === "discount") {
if (!body.serviceKey) {
enqueueSnackbar("Сервис не выбран");
body.serviceKey = currentPrivilege?.serviceKey;
body.target = body.privilegeId;
}
if (body.layer === 2 && bonusType === "discount") {
if (!body.serviceKey) {
enqueueSnackbar("Сервис не выбран");
return;
}
return;
}
body.target = body.serviceKey;
}
body.target = body.serviceKey;
}
const factorFromDiscountValue = 1 - body.factor / 100;
const factorFromDiscountValue = 1 - body.factor / 100;
return createPromocode({
codeword: body.codeword,
description: body.description,
greetings: body.greetings,
dueTo: body.dueTo,
activationCount: body.activationCount,
bonus: {
privilege: {
privilegeID: body.privilegeId,
amount: body.amount,
serviceKey: body.serviceKey,
},
discount: {
layer: body.layer,
factor: factorFromDiscountValue,
target: body.target,
threshold: body.threshold,
},
},
});
};
return createPromocode({
codeword: body.codeword,
description: body.description,
greetings: body.greetings,
dueTo: body.dueTo,
activationCount: body.activationCount,
bonus: {
privilege: {
privilegeID: body.privilegeId,
amount: body.amount,
serviceKey: body.serviceKey,
},
discount: {
layer: body.layer,
factor: factorFromDiscountValue,
target: body.target,
threshold: body.threshold,
},
},
});
};
return (
<Formik initialValues={initialValues} onSubmit={submitForm}>
{({ values, handleChange, handleBlur, setFieldValue }) => (
<Form
style={{
width: "100%",
maxWidth: "600px",
padding: "0 10px",
}}
>
<CustomTextField
name="codeword"
label="Кодовое слово"
required
onChange={handleChange}
/>
<CustomTextField
name="description"
label="Описание"
required
onChange={handleChange}
/>
<CustomTextField
name="greetings"
label="Приветственное сообщение"
required
onChange={handleChange}
/>
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
color: theme.palette.secondary.main,
}}
>
Время существования промокода
</Typography>
<Field
name="dueTo"
as={DesktopDatePicker}
inputFormat="DD/MM/YYYY"
value={values.dueTo ? new Date(Number(values.dueTo) * 1000) : null}
onChange={(event: any) => {
setFieldValue("dueTo", event.$d.getTime() / 1000 || null);
}}
renderInput={(params: TextFieldProps) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
<CustomTextField
name="activationCount"
label="Количество активаций промокода"
required
onChange={({ target }) =>
setFieldValue(
"activationCount",
Number(target.value.replace(/\D/g, ""))
)
}
/>
<RadioGroup
row
name="bonusType"
value={bonusType}
sx={{ marginTop: "15px" }}
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
setBonusType(target.value as BonusType);
}}
onBlur={handleBlur}
>
<FormControlLabel
value="discount"
control={<Radio color="secondary" />}
label="Скидка"
/>
<FormControlLabel
value="privilege"
control={<Radio color="secondary" />}
label="Привилегия"
/>
</RadioGroup>
{bonusType === "discount" && (
<>
<RadioGroup
row
name="layer"
value={values.layer}
sx={{ marginTop: "15px" }}
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
setFieldValue("target", "");
setFieldValue("layer", Number(target.value));
}}
onBlur={handleBlur}
>
<FormControlLabel
value="1"
control={<Radio color="secondary" />}
label="Привилегия"
/>
<FormControlLabel
value="2"
control={<Radio color="secondary" />}
label="Сервис"
/>
</RadioGroup>
<CustomTextField
name="factor"
label="Процент скидки"
required
onChange={({ target }) => {
setFieldValue(
"factor",
Number(target.value.replace(/\D/g, ""))
);
}}
/>
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
padding: "0 12px",
color: theme.palette.secondary.main,
}}
>
{values.layer === 1 ? "Выбор привилегии" : "Выбор сервиса"}
</Typography>
{values.layer === 1 ? (
<Field
name="privilegeId"
as={Select}
label={"Привилегия"}
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
onChange={({ target }: SelectChangeProps) => {
setFieldValue("target", target.value);
setFieldValue("privilegeId", target.value);
}}
children={privileges.map(({ name, privilegeId }) => (
<MenuItem key={privilegeId} value={privilegeId}>
{name}
</MenuItem>
))}
/>
) : (
<Field
name="serviceKey"
as={Select}
label={"Сервис"}
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
onChange={({ target }: SelectChangeProps) => {
setFieldValue("target", target.value);
setFieldValue("serviceKey", target.value);
}}
children={SERVICE_LIST.map(({ displayName, serviceKey }) => (
<MenuItem key={serviceKey} value={serviceKey}>
{displayName}
</MenuItem>
))}
/>
)}
<CustomTextField
name="threshold"
label="При каком значении применяется скидка"
onChange={({ target }) =>
setFieldValue(
"threshold",
Number(target.value.replace(/\D/g, ""))
)
}
/>
</>
)}
{bonusType === "privilege" && (
<>
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
padding: "0 12px",
color: theme.palette.secondary.main,
}}
>
Выбор привилегии
</Typography>
<Field
name="privilegeId"
as={Select}
label="Привилегия"
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
children={privileges.map(({ name, privilegeId }) => (
<MenuItem key={privilegeId} value={privilegeId}>
{name}
</MenuItem>
))}
/>
<CustomTextField
name="amount"
label="Количество"
required
onChange={({ target }) =>
setFieldValue(
"amount",
Number(target.value.replace(/\D/g, ""))
)
}
/>
</>
)}
<Button
variant="contained"
sx={{
display: "block",
padding: "10px",
margin: "15px auto 0",
fontWeight: "normal",
fontSize: "18px",
backgroundColor: theme.palette.menu.main,
"&:hover": { backgroundColor: theme.palette.grayMedium.main },
}}
type="submit"
>
Создать
</Button>
</Form>
)}
</Formik>
);
return (
<Formik initialValues={initialValues} onSubmit={submitForm}>
{({ values, handleChange, handleBlur, setFieldValue }) => (
<Form
style={{
width: "100%",
maxWidth: "600px",
padding: "0 10px",
}}
>
<CustomTextField name="codeword" label="Кодовое слово" required onChange={handleChange} />
<CustomTextField name="description" label="Описание" required onChange={handleChange} />
<CustomTextField name="greetings" label="Приветственное сообщение" required onChange={handleChange} />
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
color: theme.palette.secondary.main,
}}
>
Время существования промокода
</Typography>
<Field
name="dueTo"
as={DesktopDatePicker}
inputFormat="DD/MM/YYYY"
value={values.dueTo ? new Date(Number(values.dueTo) * 1000) : null}
onChange={(event: any) => {
setFieldValue("dueTo", event.$d.getTime() / 1000 || null);
}}
renderInput={(params: TextFieldProps) => <TextField {...params} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
<CustomTextField
name="activationCount"
label="Количество активаций промокода"
required
onChange={({ target }) => setFieldValue("activationCount", Number(target.value.replace(/\D/g, "")))}
/>
<RadioGroup
row
name="bonusType"
value={bonusType}
sx={{ marginTop: "15px" }}
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
setBonusType(target.value as BonusType);
}}
onBlur={handleBlur}
>
<FormControlLabel value="discount" control={<Radio color="secondary" />} label="Скидка" />
<FormControlLabel value="privilege" control={<Radio color="secondary" />} label="Привилегия" />
</RadioGroup>
{bonusType === "discount" && (
<>
<RadioGroup
row
name="layer"
value={values.layer}
sx={{ marginTop: "15px" }}
onChange={({ target }: React.ChangeEvent<HTMLInputElement>) => {
setFieldValue("target", "");
setFieldValue("layer", Number(target.value));
}}
onBlur={handleBlur}
>
<FormControlLabel value="1" control={<Radio color="secondary" />} label="Привилегия" />
<FormControlLabel value="2" control={<Radio color="secondary" />} label="Сервис" />
</RadioGroup>
<CustomTextField
name="factor"
label="Процент скидки"
required
onChange={({ target }) => {
setFieldValue("factor", Number(target.value.replace(/\D/g, "")));
}}
/>
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
padding: "0 12px",
color: theme.palette.secondary.main,
}}
>
{values.layer === 1 ? "Выбор привилегии" : "Выбор сервиса"}
</Typography>
{values.layer === 1 ? (
<Field
name="privilegeId"
as={Select}
label={"Привилегия"}
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
onChange={({ target }: SelectChangeProps) => {
setFieldValue("target", target.value);
setFieldValue("privilegeId", target.value);
}}
children={privileges.map(({ name, privilegeId }) => (
<MenuItem key={privilegeId} value={privilegeId}>
{name}
</MenuItem>
))}
/>
) : (
<Field
name="serviceKey"
as={Select}
label={"Сервис"}
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
onChange={({ target }: SelectChangeProps) => {
setFieldValue("target", target.value);
setFieldValue("serviceKey", target.value);
}}
children={SERVICE_LIST.map(({ displayName, serviceKey }) => (
<MenuItem key={serviceKey} value={serviceKey}>
{displayName}
</MenuItem>
))}
/>
)}
<CustomTextField
name="threshold"
label="При каком значении применяется скидка"
onChange={({ target }) => setFieldValue("threshold", Number(target.value.replace(/\D/g, "")))}
/>
</>
)}
{bonusType === "privilege" && (
<>
<Typography
variant="h4"
sx={{
height: "40px",
fontWeight: "normal",
marginTop: "15px",
padding: "0 12px",
color: theme.palette.secondary.main,
}}
>
Выбор привилегии
</Typography>
<Field
name="privilegeId"
as={Select}
label="Привилегия"
sx={{
width: "100%",
border: "2px solid",
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
border: "none",
},
".MuiSvgIcon-root ": { fill: theme.palette.secondary.main },
}}
children={privileges.map(({ name, privilegeId }) => (
<MenuItem key={privilegeId} value={privilegeId}>
{name}
</MenuItem>
))}
/>
<CustomTextField
name="amount"
label="Количество"
required
onChange={({ target }) => setFieldValue("amount", Number(target.value.replace(/\D/g, "")))}
/>
</>
)}
<Button
variant="contained"
sx={{
display: "block",
padding: "10px",
margin: "15px auto 0",
fontWeight: "normal",
fontSize: "18px",
backgroundColor: theme.palette.menu.main,
"&:hover": { backgroundColor: theme.palette.grayMedium.main },
}}
type="submit"
>
Создать
</Button>
</Form>
)}
</Formik>
);
};
type CustomTextFieldProps = {
name: string;
label: string;
required?: boolean;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
name: string;
label: string;
required?: boolean;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
};
const CustomTextField = ({
name,
label,
required = false,
onChange,
}: CustomTextFieldProps) => (
<Field
name={name}
label={label}
required={required}
variant="filled"
color="secondary"
as={TextField}
onChange={onChange}
sx={{ width: "100%", marginTop: "15px" }}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: { color: theme.palette.secondary.main },
}}
/>
const CustomTextField = ({ name, label, required = false, onChange }: CustomTextFieldProps) => (
<Field
name={name}
label={label}
required={required}
variant="filled"
color="secondary"
as={TextField}
onChange={onChange}
sx={{ width: "100%", marginTop: "15px" }}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: { color: theme.palette.secondary.main },
}}
/>
);

@ -1,59 +1,54 @@
import * as React from 'react';
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
import Button from '@mui/material/Button';
import { Typography } from '@mui/material';
import * as React from "react";
import Box from "@mui/material/Box";
import Modal from "@mui/material/Modal";
import Button from "@mui/material/Button";
import { Typography } from "@mui/material";
const style = {
position: 'absolute' as 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: '#c1c1c1',
border: '2px solid #000',
boxShadow: 24,
pt: 2,
px: 4,
pb: 3,
position: "absolute" as const,
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "#c1c1c1",
border: "2px solid #000",
boxShadow: 24,
pt: 2,
px: 4,
pb: 3,
};
interface Props {
id: string;
setModal: (id: string) => void;
deletePromocode: (id: string) => Promise<void>;
id: string;
setModal: (id: string) => void;
deletePromocode: (id: string) => Promise<void>;
}
export default function ({
id,
setModal,
deletePromocode
}: Props) {
return (
<Modal
open={Boolean(id)}
onClose={() => setModal("")}
>
<Box sx={{ ...style, width: 400 }}>
<Typography
variant='h5'
textAlign="center"
>Точно удалить промокод?</Typography>
<Box
sx={{
display: "flex",
justifyContent: "space-evenly",
mt: "15px"
}}
>
<Button
onClick={() => { deletePromocode(id); setModal("") }}
>Да</Button>
<Button
onClick={() => setModal("")}
>Нет</Button>
</Box>
</Box>
</Modal>
);
export default function ({ id, setModal, deletePromocode }: Props) {
return (
<Modal open={Boolean(id)} onClose={() => setModal("")}>
<Box sx={{ ...style, width: 400 }}>
<Typography variant="h5" textAlign="center">
Точно удалить промокод?
</Typography>
<Box
sx={{
display: "flex",
justifyContent: "space-evenly",
mt: "15px",
}}
>
<Button
onClick={() => {
deletePromocode(id);
setModal("");
}}
>
Да
</Button>
<Button onClick={() => setModal("")}>Нет</Button>
</Box>
</Box>
</Modal>
);
}

@ -1,14 +1,5 @@
import { useEffect, useState } from "react";
import {
Box,
Button,
Typography,
Modal,
TextField,
useTheme,
useMediaQuery,
IconButton,
} from "@mui/material";
import { Box, Button, Typography, Modal, TextField, useTheme, useMediaQuery, IconButton } from "@mui/material";
import { DataGrid, GridLoadingOverlay, GridToolbar } from "@mui/x-data-grid";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
@ -21,318 +12,293 @@ import type { GridColDef } from "@mui/x-data-grid";
import type { Promocode, PromocodeStatistics } from "@root/model/promocodes";
const host = window.location.hostname;
let isTest = host.includes("s");
const isTest = host.includes("s");
type StatisticsModalProps = {
id: string;
to: number;
from: number;
setId: (id: string) => void;
setTo: (date: number) => void;
setFrom: (date: number) => void;
promocodes: Promocode[];
promocodeStatistics: PromocodeStatistics | null | undefined;
createFastLink: (id: string) => Promise<void>;
id: string;
to: number;
from: number;
setId: (id: string) => void;
setTo: (date: number) => void;
setFrom: (date: number) => void;
promocodes: Promocode[];
promocodeStatistics: PromocodeStatistics | null | undefined;
createFastLink: (id: string) => Promise<void>;
};
type Row = {
id: number;
link: string;
useCount: number;
id: number;
link: string;
useCount: number;
};
const COLUMNS: GridColDef<Row, string>[] = [
{
field: "copy",
headerName: "копировать",
width: 50,
sortable: false,
valueGetter: ({ row }) => String(row.useCount),
renderCell: (params) => {
return (
<IconButton
onClick={() => navigator.clipboard.writeText(`https://${isTest ? "s" : ""}quiz.pena.digital/?fl=${params.row.link}`)}
>
<ContentCopyIcon />
</IconButton>
);
},
},
{
field: "link",
headerName: "Ссылка",
width: 320,
sortable: false,
valueGetter: ({ row }) => row.link,
renderCell: ({ value }) =>
value?.split("|").map((link) => <Typography>{link}</Typography>),
},
{
field: "useCount",
headerName: "Использований",
width: 120,
sortable: false,
valueGetter: ({ row }) => String(row.useCount),
},
{
field: "purchasesCount",
headerName: "Покупок",
width: 70,
sortable: false,
valueGetter: ({ row }) => String(0),
},
{
field: "copy",
headerName: "копировать",
width: 50,
sortable: false,
valueGetter: ({ row }) => String(row.useCount),
renderCell: (params) => {
return (
<IconButton
onClick={() =>
navigator.clipboard.writeText(`https://${isTest ? "s" : ""}quiz.pena.digital/?fl=${params.row.link}`)
}
>
<ContentCopyIcon />
</IconButton>
);
},
},
{
field: "link",
headerName: "Ссылка",
width: 320,
sortable: false,
valueGetter: ({ row }) => row.link,
renderCell: ({ value }) => value?.split("|").map((link) => <Typography>{link}</Typography>),
},
{
field: "useCount",
headerName: "Использований",
width: 120,
sortable: false,
valueGetter: ({ row }) => String(row.useCount),
},
{
field: "purchasesCount",
headerName: "Покупок",
width: 70,
sortable: false,
valueGetter: ({ row }) => String(0),
},
];
export const StatisticsModal = ({
id,
setId,
setFrom,
from,
to,
setTo,
promocodeStatistics,
promocodes,
createFastLink,
id,
setId,
setFrom,
from,
to,
setTo,
promocodeStatistics,
promocodes,
createFastLink,
}: StatisticsModalProps) => {
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(550));
const [rows, setRows] = useState<Row[]>([]);
const { privileges } = usePrivilegeStore();
const currentPrivilegeId = promocodes.find((promocode) => promocode.id === id)
?.bonus.privilege.privilegeID;
const privilege = privileges.find(
(item) => item.privilegeId === currentPrivilegeId
);
const promocode = promocodes.find((item) => item.id === id);
const createFastlink = async () => {
await createFastLink(id);
};
const [startDate, setStartDate] = useState<Date>(new Date());
const [endDate, setEndDate] = useState<Date>(new Date());
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(550));
const [rows, setRows] = useState<Row[]>([]);
const { privileges } = usePrivilegeStore();
const currentPrivilegeId = promocodes.find((promocode) => promocode.id === id)?.bonus.privilege.privilegeID;
const privilege = privileges.find((item) => item.privilegeId === currentPrivilegeId);
const promocode = promocodes.find((item) => item.id === id);
const createFastlink = async () => {
await createFastLink(id);
};
const getParseData = () => {
const rows = promocodes
.find((promocode) => promocode.id === id)
?.fastLinks?.map((link, index) => ({
link,
id: index,
useCount: promocodeStatistics?.usageMap[link] ?? 0,
})) as Row[];
const getParseData = () => {
const rows = promocodes
.find((promocode) => promocode.id === id)
?.fastLinks?.map((link, index) => ({
link,
id: index,
useCount: promocodeStatistics?.usageMap[link] ?? 0,
})) as Row[];
setRows(rows);
};
setRows(rows);
};
useEffect(() => {
if (id.length > 0) {
getParseData();
}
useEffect(() => {
if (id.length > 0) {
getParseData();
}
if (!id) {
setRows([]);
}
}, [id, promocodes]);
if (!id) {
setRows([]);
}
}, [id, promocodes]);
// const formatTo = to === null ? 0 : moment(to).unix()
// const formatFrom = from === null ? 0 : moment(from).unix()
// useEffect(() => {
// (async () => {
// const gottenGeneral = await promocodeStatistics(id, startDate, endDate)
// setGeneral(gottenGeneral[0])
// })()
// }, [to, from]);
return (
<Modal
open={Boolean(id)}
onClose={() => {
setId("");
setStartDate(new Date());
setEndDate(new Date());
}}
sx={{
"& > .MuiBox-root": { outline: "none", padding: "32px 32px 16px" },
}}
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: "95%",
maxWidth: "600px",
background: "#1F2126",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
flexDirection: isMobile ? "column" : "row",
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
}}
>
<Button sx={{ maxWidth: "100px" }} onClick={createFastlink}>
Создать короткую ссылку
</Button>
<Button sx={{ maxWidth: "100px" }} onClick={getParseData}>
Обновить статистику
</Button>
</Box>
<Box sx={{ minWidth: "200px" }}>
<Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
<Typography sx={{ minWidth: "20px", color: "#FFFFFF" }}>
от
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={startDate}
onChange={(date) => date && setStartDate(date)}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
marginTop: "10px",
}}
>
<Typography sx={{ minWidth: "20px", color: "#FFFFFF" }}>
до
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={endDate}
onChange={(date) => date && setEndDate(date)}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
</Box>
</Box>
<DataGrid
disableSelectionOnClick={true}
rows={rows}
columns={COLUMNS}
sx={{
marginTop: "30px",
background: "#1F2126",
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": { display: "none" },
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
"& .MuiButton-text": { color: theme.palette.secondary.main },
"& .MuiDataGrid-overlay": {
backgroundColor: "rgba(255, 255, 255, 0.1)",
animation: `${fadeIn} 0.5s ease-out`,
},
"& .MuiDataGrid-virtualScrollerContent": { maxHeight: "200px" },
"& .MuiDataGrid-virtualScrollerRenderZone": {
maxHeight: "200px",
overflowY: "auto",
},
}}
components={{
Toolbar: GridToolbar,
LoadingOverlay: GridLoadingOverlay,
}}
rowsPerPageOptions={[10, 25, 50, 100]}
autoHeight
/>
{privilege === undefined ? (
<Typography
sx={{
margin: "10px 0 0",
textAlign: "center",
color: theme.palette.secondary.main,
}}
>
Нет привилегии
</Typography>
) : (
<Box
sx={{
color: "#e6e8ec",
display: "flex",
flexDirection: "column",
margin: "20px 0",
}}
>
<Typography>название привилегии: {privilege.name}</Typography>
<Typography>
{promocode?.activationCount} активаций из{" "}
{promocode?.activationLimit}
</Typography>
<Typography>приветствие: "{promocode?.greetings}"</Typography>
{promocode?.bonus?.discount?.factor !== undefined && (
<Typography>
скидка: {100 - promocode?.bonus?.discount?.factor * 100}%
</Typography>
)}
{
<Typography>
количество привилегии: {promocode?.bonus?.privilege?.amount}
</Typography>
}
{promocode?.dueTo !== undefined && promocode.dueTo > 0 && (
<Typography>
действует до: {new Date(promocode.dueTo).toLocaleString()}
</Typography>
)}
</Box>
)}
</Box>
</Modal>
);
// const formatTo = to === null ? 0 : moment(to).unix()
// const formatFrom = from === null ? 0 : moment(from).unix()
// useEffect(() => {
// (async () => {
// const gottenGeneral = await promocodeStatistics(id, startDate, endDate)
// setGeneral(gottenGeneral[0])
// })()
// }, [to, from]);
return (
<Modal
open={Boolean(id)}
onClose={() => {
setId("");
setStartDate(new Date());
setEndDate(new Date());
}}
sx={{
"& > .MuiBox-root": { outline: "none", padding: "32px 32px 16px" },
}}
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: "95%",
maxWidth: "600px",
background: "#1F2126",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
flexDirection: isMobile ? "column" : "row",
}}
>
<Box
sx={{
display: "flex",
gap: "30px",
justifyContent: "center",
alignItems: "center",
}}
>
<Button sx={{ maxWidth: "100px" }} onClick={createFastlink}>
Создать короткую ссылку
</Button>
<Button sx={{ maxWidth: "100px" }} onClick={getParseData}>
Обновить статистику
</Button>
</Box>
<Box sx={{ minWidth: "200px" }}>
<Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
<Typography sx={{ minWidth: "20px", color: "#FFFFFF" }}>от</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={startDate}
onChange={(date) => date && setStartDate(date)}
renderInput={(params) => <TextField {...params} sx={{ background: "#1F2126", borderRadius: "5px" }} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
gap: "10px",
marginTop: "10px",
}}
>
<Typography sx={{ minWidth: "20px", color: "#FFFFFF" }}>до</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={endDate}
onChange={(date) => date && setEndDate(date)}
renderInput={(params) => <TextField {...params} sx={{ background: "#1F2126", borderRadius: "5px" }} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
</Box>
</Box>
<DataGrid
disableSelectionOnClick={true}
rows={rows}
columns={COLUMNS}
sx={{
marginTop: "30px",
background: "#1F2126",
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": { display: "none" },
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
"& .MuiButton-text": { color: theme.palette.secondary.main },
"& .MuiDataGrid-overlay": {
backgroundColor: "rgba(255, 255, 255, 0.1)",
animation: `${fadeIn} 0.5s ease-out`,
},
"& .MuiDataGrid-virtualScrollerContent": { maxHeight: "200px" },
"& .MuiDataGrid-virtualScrollerRenderZone": {
maxHeight: "200px",
overflowY: "auto",
},
}}
components={{
Toolbar: GridToolbar,
LoadingOverlay: GridLoadingOverlay,
}}
rowsPerPageOptions={[10, 25, 50, 100]}
autoHeight
/>
{privilege === undefined ? (
<Typography
sx={{
margin: "10px 0 0",
textAlign: "center",
color: theme.palette.secondary.main,
}}
>
Нет привилегии
</Typography>
) : (
<Box
sx={{
color: "#e6e8ec",
display: "flex",
flexDirection: "column",
margin: "20px 0",
}}
>
<Typography>название привилегии: {privilege.name}</Typography>
<Typography>
{promocode?.activationCount} активаций из {promocode?.activationLimit}
</Typography>
<Typography>приветствие: "{promocode?.greetings}"</Typography>
{promocode?.bonus?.discount?.factor !== undefined && (
<Typography>скидка: {100 - promocode?.bonus?.discount?.factor * 100}%</Typography>
)}
{<Typography>количество привилегии: {promocode?.bonus?.privilege?.amount}</Typography>}
{promocode?.dueTo !== undefined && promocode.dueTo > 0 && (
<Typography>действует до: {new Date(promocode.dueTo).toLocaleString()}</Typography>
)}
</Box>
)}
</Box>
</Modal>
);
};

@ -11,104 +11,96 @@ import { StatisticsModal } from "./StatisticsModal";
import DeleteModal from "./DeleteModal";
export const PromocodeManagement = () => {
const theme = useTheme();
const theme = useTheme();
const [deleteModal, setDeleteModal] = useState<string>("");
const deleteModalHC = (id: string) => setDeleteModal(id);
const [deleteModal, setDeleteModal] = useState<string>("");
const deleteModalHC = (id: string) => setDeleteModal(id);
const [showStatisticsModalId, setShowStatisticsModalId] =
useState<string>("");
const [page, setPage] = useState<number>(0);
const [to, setTo] = useState(0);
const [from, setFrom] = useState(0);
const [pageSize, setPageSize] = useState<number>(10);
const {
data,
error,
isValidating,
promocodesCount,
promocodeStatistics,
deletePromocode,
createPromocode,
createFastLink,
} = usePromocodes(page, pageSize, showStatisticsModalId, to, from);
const columns = usePromocodeGridColDef(
setShowStatisticsModalId,
deleteModalHC
);
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
const [showStatisticsModalId, setShowStatisticsModalId] = useState<string>("");
const [page, setPage] = useState<number>(0);
const [to, setTo] = useState(0);
const [from, setFrom] = useState(0);
const [pageSize, setPageSize] = useState<number>(10);
const {
data,
error,
isValidating,
promocodesCount,
promocodeStatistics,
deletePromocode,
createPromocode,
createFastLink,
} = usePromocodes(page, pageSize, showStatisticsModalId, to, from);
const columns = usePromocodeGridColDef(setShowStatisticsModalId, deleteModalHC);
if (error) return <Typography>Ошибка загрузки промокодов</Typography>;
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
textTransform: "uppercase",
color: theme.palette.secondary.main,
}}
>
Создание промокода
</Typography>
<CreatePromocodeForm createPromocode={createPromocode} />
<Box style={{ width: "80%", marginTop: "55px" }}>
<DataGrid
disableSelectionOnClick={true}
rows={data?.items ?? []}
columns={columns}
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": { display: "none" },
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
"& .MuiButton-text": { color: theme.palette.secondary.main },
"& .MuiDataGrid-overlay": {
backgroundColor: "rgba(255, 255, 255, 0.1)",
animation: `${fadeIn} 0.5s ease-out`,
},
}}
components={{
Toolbar: GridToolbar,
LoadingOverlay: GridLoadingOverlay,
}}
loading={isValidating}
paginationMode="server"
page={page}
onPageChange={setPage}
rowCount={promocodesCount}
pageSize={pageSize}
onPageSizeChange={setPageSize}
rowsPerPageOptions={[10, 25, 50, 100]}
autoHeight
/>
</Box>
<StatisticsModal
id={showStatisticsModalId}
setId={setShowStatisticsModalId}
promocodeStatistics={promocodeStatistics}
to={to}
setTo={setTo}
from={from}
setFrom={setFrom}
promocodes={data?.items ?? []}
createFastLink={createFastLink}
/>
<DeleteModal
id={deleteModal}
setModal={setDeleteModal}
deletePromocode={deletePromocode}
/>
</LocalizationProvider>
);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
textTransform: "uppercase",
color: theme.palette.secondary.main,
}}
>
Создание промокода
</Typography>
<CreatePromocodeForm createPromocode={createPromocode} />
<Box style={{ width: "80%", marginTop: "55px" }}>
<DataGrid
disableSelectionOnClick={true}
rows={data?.items ?? []}
columns={columns}
sx={{
color: theme.palette.secondary.main,
"& .MuiDataGrid-iconSeparator": { display: "none" },
"& .css-levciy-MuiTablePagination-displayedRows": {
color: theme.palette.secondary.main,
},
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
"& .MuiTablePagination-selectLabel": {
color: theme.palette.secondary.main,
},
"& .MuiInputBase-root": { color: theme.palette.secondary.main },
"& .MuiButton-text": { color: theme.palette.secondary.main },
"& .MuiDataGrid-overlay": {
backgroundColor: "rgba(255, 255, 255, 0.1)",
animation: `${fadeIn} 0.5s ease-out`,
},
}}
components={{
Toolbar: GridToolbar,
LoadingOverlay: GridLoadingOverlay,
}}
loading={isValidating}
paginationMode="server"
page={page}
onPageChange={setPage}
rowCount={promocodesCount}
pageSize={pageSize}
onPageSizeChange={setPageSize}
rowsPerPageOptions={[10, 25, 50, 100]}
autoHeight
/>
</Box>
<StatisticsModal
id={showStatisticsModalId}
setId={setShowStatisticsModalId}
promocodeStatistics={promocodeStatistics}
to={to}
setTo={setTo}
from={from}
setFrom={setFrom}
promocodes={data?.items ?? []}
createFastLink={createFastLink}
/>
<DeleteModal id={deleteModal} setModal={setDeleteModal} deletePromocode={deletePromocode} />
</LocalizationProvider>
);
};

@ -6,96 +6,92 @@ import { useMemo, useState } from "react";
import { BarChart, Delete } from "@mui/icons-material";
import { promocodeApi } from "@root/api/promocode/requests";
export function usePromocodeGridColDef(
setStatistics: (id: string) => void,
deletePromocode: (id: string) => void
) {
const validity = (value: string | number) => {
if (value === 0) {
return "неоганичен";
} else {
return new Date(value).toLocaleString();
}
};
return useMemo<GridColDef<Promocode, string | number, string>[]>(
() => [
{
field: "id",
headerName: "ID",
width: 30,
sortable: false,
valueGetter: ({ row }) => row.id,
},
{
field: "codeword",
headerName: "Кодовое слово",
width: 160,
sortable: false,
valueGetter: ({ row }) => row.codeword,
},
{
field: "factor",
headerName: "Коэф. скидки",
width: 120,
sortable: false,
valueGetter: ({ row }) =>
Math.round(row.bonus.discount.factor * 1000) / 1000,
},
{
field: "activationCount",
headerName: "Кол-во активаций",
width: 140,
sortable: false,
valueGetter: ({ row }) => row.activationCount,
},
{
field: "dueTo",
headerName: "Истекает",
width: 160,
sortable: false,
valueGetter: ({ row }) => row.dueTo * 1000,
valueFormatter: ({ value }) => `${validity(value)}`,
},
{
field: "description",
headerName: "Описание",
minWidth: 200,
flex: 1,
sortable: false,
valueGetter: ({ row }) => row.description,
},
{
field: "settings",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton
onClick={() => {
setStatistics(params.row.id);
promocodeApi.getPromocodeStatistics(params.row.id, 0, 0);
}}
>
<BarChart />
</IconButton>
);
},
},
{
field: "delete",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton onClick={() => deletePromocode(params.row.id)}>
<Delete />
</IconButton>
);
},
},
],
[deletePromocode, setStatistics]
);
export function usePromocodeGridColDef(setStatistics: (id: string) => void, deletePromocode: (id: string) => void) {
const validity = (value: string | number) => {
if (value === 0) {
return "неоганичен";
} else {
return new Date(value).toLocaleString();
}
};
return useMemo<GridColDef<Promocode, string | number, string>[]>(
() => [
{
field: "id",
headerName: "ID",
width: 30,
sortable: false,
valueGetter: ({ row }) => row.id,
},
{
field: "codeword",
headerName: "Кодовое слово",
width: 160,
sortable: false,
valueGetter: ({ row }) => row.codeword,
},
{
field: "factor",
headerName: "Коэф. скидки",
width: 120,
sortable: false,
valueGetter: ({ row }) => Math.round(row.bonus.discount.factor * 1000) / 1000,
},
{
field: "activationCount",
headerName: "Кол-во активаций",
width: 140,
sortable: false,
valueGetter: ({ row }) => row.activationCount,
},
{
field: "dueTo",
headerName: "Истекает",
width: 160,
sortable: false,
valueGetter: ({ row }) => row.dueTo * 1000,
valueFormatter: ({ value }) => `${validity(value)}`,
},
{
field: "description",
headerName: "Описание",
minWidth: 200,
flex: 1,
sortable: false,
valueGetter: ({ row }) => row.description,
},
{
field: "settings",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton
onClick={() => {
setStatistics(params.row.id);
promocodeApi.getPromocodeStatistics(params.row.id, 0, 0);
}}
>
<BarChart />
</IconButton>
);
},
},
{
field: "delete",
headerName: "",
width: 60,
sortable: false,
renderCell: (params) => {
return (
<IconButton onClick={() => deletePromocode(params.row.id)}>
<Delete />
</IconButton>
);
},
},
],
[deletePromocode, setStatistics]
);
}

@ -4,83 +4,73 @@ import { DatePicker } from "@mui/x-date-pickers";
import type { Moment } from "moment";
type DateFilterProps = {
from: Moment | null;
to: Moment | null;
setFrom: (date: Moment | null) => void;
setTo: (date: Moment | null) => void;
from: Moment | null;
to: Moment | null;
setFrom: (date: Moment | null) => void;
setTo: (date: Moment | null) => void;
};
export const DateFilter = ({ to, setTo, from, setFrom }: DateFilterProps) => {
const theme = useTheme();
const theme = useTheme();
return (
<>
<Box>
<Typography
sx={{
fontSize: "16px",
marginBottom: "5px",
fontWeight: 500,
color: "4D4D4D",
}}
>
Дата начала
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={from}
onChange={(date) => date && setFrom(date.startOf('day'))}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
</Box>
<Box>
<Typography
sx={{
fontSize: "16px",
marginBottom: "5px",
fontWeight: 500,
color: "4D4D4D",
}}
>
Дата окончания
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={to}
onChange={(date) => date && setTo(date.endOf('day'))}
renderInput={(params) => (
<TextField
{...params}
sx={{ background: "#1F2126", borderRadius: "5px" }}
/>
)}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
</>
);
return (
<>
<Box>
<Typography
sx={{
fontSize: "16px",
marginBottom: "5px",
fontWeight: 500,
color: "4D4D4D",
}}
>
Дата начала
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={from}
onChange={(date) => date && setFrom(date.startOf("day"))}
renderInput={(params) => <TextField {...params} sx={{ background: "#1F2126", borderRadius: "5px" }} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": { color: theme.palette.secondary.main },
},
}}
/>
</Box>
<Box>
<Typography
sx={{
fontSize: "16px",
marginBottom: "5px",
fontWeight: 500,
color: "4D4D4D",
}}
>
Дата окончания
</Typography>
<DatePicker
inputFormat="DD/MM/YYYY"
value={to}
onChange={(date) => date && setTo(date.endOf("day"))}
renderInput={(params) => <TextField {...params} sx={{ background: "#1F2126", borderRadius: "5px" }} />}
InputProps={{
sx: {
height: "40px",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.secondary.main,
"& .MuiSvgIcon-root": {
color: theme.palette.secondary.main,
},
},
}}
/>
</Box>
</>
);
};

@ -1,14 +1,6 @@
import { useState } from "react";
import moment from "moment";
import {
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Button,
useTheme,
} from "@mui/material";
import { Table, TableBody, TableCell, TableHead, TableRow, Button, useTheme } from "@mui/material";
import { DateFilter } from "./DateFilter";
@ -17,67 +9,67 @@ import { useQuizStatistic } from "@root/utils/hooks/useQuizStatistic";
import type { Moment } from "moment";
export const QuizInfo = () => {
const [from, setFrom] = useState<Moment | null>(null);
const [to, setTo] = useState<Moment | null>(moment());
const theme = useTheme();
const { Registrations, Quizes, Results } = useQuizStatistic({
from,
to,
});
const [from, setFrom] = useState<Moment | null>(null);
const [to, setTo] = useState<Moment | null>(moment());
const theme = useTheme();
const { Registrations, Quizes, Results } = useQuizStatistic({
from,
to,
});
const resetTime = () => {
setFrom(moment());
setTo(moment());
};
const resetTime = () => {
setFrom(moment());
setTo(moment());
};
return (
<>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<Button sx={{ m: "10px 0" }} onClick={resetTime}>
Сбросить даты
</Button>
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
Регистраций
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Quiz
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Результаты
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell sx={{ color: "inherit" }} align="center">
{Registrations}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Quizes}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Results}
</TableCell>
</TableRow>
</TableBody>
</Table>
</>
);
return (
<>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<Button sx={{ m: "10px 0" }} onClick={resetTime}>
Сбросить даты
</Button>
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
Регистраций
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Quiz
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Результаты
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell sx={{ color: "inherit" }} align="center">
{Registrations}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Quizes}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Results}
</TableCell>
</TableRow>
</TableBody>
</Table>
</>
);
};

@ -1,14 +1,6 @@
import { useState } from "react";
import moment from "moment";
import {
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
useTheme,
} from "@mui/material";
import { Table, TableBody, TableCell, TableHead, TableRow, Typography, useTheme } from "@mui/material";
import { DateFilter } from "./DateFilter";
@ -18,63 +10,61 @@ import { usePromocodeStatistics } from "@root/utils/hooks/usePromocodeStatistics
import type { Moment } from "moment";
export const StatisticsPromocode = () => {
const [from, setFrom] = useState<Moment | null>(
moment(moment().subtract(4, "weeks"))
);
const [to, setTo] = useState<Moment | null>(moment());
const promocodes = useAllPromocodes();
const promocodeStatistics = usePromocodeStatistics({ to, from });
const theme = useTheme();
const [from, setFrom] = useState<Moment | null>(moment(moment().subtract(4, "weeks")));
const [to, setTo] = useState<Moment | null>(moment());
const promocodes = useAllPromocodes();
const promocodeStatistics = usePromocodeStatistics({ to, from });
const theme = useTheme();
return (
<>
<Typography sx={{ marginTop: "30px" }}>Статистика промокодов</Typography>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
marginTop: "30px",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
Промокод
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Регистации
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Внесено
</TableCell>
</TableRow>
</TableHead>
{Object.entries(promocodeStatistics).map(([key, { Regs, Money }]) => (
<TableBody key={key}>
<TableRow>
<TableCell sx={{ color: "inherit" }} align="center">
{promocodes.find(({ id }) => id === key)?.codeword ?? ""}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Regs}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{(Money / 100).toFixed(2)}
</TableCell>
</TableRow>
</TableBody>
))}
</Table>
</>
);
return (
<>
<Typography sx={{ marginTop: "30px" }}>Статистика промокодов</Typography>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
marginTop: "30px",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
Промокод
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Регистации
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Внесено
</TableCell>
</TableRow>
</TableHead>
{Object.entries(promocodeStatistics).map(([key, { Regs, Money }]) => (
<TableBody key={key}>
<TableRow>
<TableCell sx={{ color: "inherit" }} align="center">
{promocodes.find(({ id }) => id === key)?.codeword ?? ""}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Regs}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{(Money / 100).toFixed(2)}
</TableCell>
</TableRow>
</TableBody>
))}
</Table>
</>
);
};

@ -1,17 +1,17 @@
import moment from "moment";
import { useEffect, useState } from "react";
import {
Accordion,
AccordionDetails,
AccordionSummary,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
Button,
useTheme,
Accordion,
AccordionDetails,
AccordionSummary,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
Button,
useTheme,
} from "@mui/material";
import { GridToolbar } from "@mui/x-data-grid";
import { enqueueSnackbar } from "notistack";
@ -29,168 +29,154 @@ import type { QuizStatisticsItem } from "@root/api/quizStatistics/types";
import type { GridColDef } from "@mui/x-data-grid";
const COLUMNS: GridColDef<QuizStatisticsItem, string>[] = [
{
field: "user",
headerName: "Пользователь",
width: 250,
valueGetter: ({ row }) => row.ID,
},
{
field: "regs",
headerName: "Регистраций",
width: 200,
valueGetter: ({ row }) => String(row.Regs),
},
{
field: "money",
headerName: "Деньги",
width: 200,
valueGetter: ({ row }) => String(row.Money),
},
{
field: "user",
headerName: "Пользователь",
width: 250,
valueGetter: ({ row }) => row.ID,
},
{
field: "regs",
headerName: "Регистраций",
width: 200,
valueGetter: ({ row }) => String(row.Regs),
},
{
field: "money",
headerName: "Деньги",
width: 200,
valueGetter: ({ row }) => String(row.Money),
},
];
export const StatisticsSchild = () => {
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
const [activeUserId, setActiveUserId] = useState<string>("");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
const [activeUserId, setActiveUserId] = useState<string>("");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [from, setFrom] = useState<Moment | null>(
moment(moment().subtract(4, "weeks"))
);
const [to, setTo] = useState<Moment | null>(moment());
const [from, setFrom] = useState<Moment | null>(moment(moment().subtract(4, "weeks")));
const [to, setTo] = useState<Moment | null>(moment());
const theme = useTheme();
const statistics = useSchildStatistics(from, to)
.map((obj) => ({...obj, Money: Number((obj.Money / 100).toFixed(2))}));
const theme = useTheme();
const statistics = useSchildStatistics(from, to).map((obj) => ({
...obj,
Money: Number((obj.Money / 100).toFixed(2)),
}));
useEffect(() => {
if (!openUserModal) {
setActiveUserId("");
}
}, [openUserModal]);
useEffect(() => {
if (!openUserModal) {
setActiveUserId("");
}
}, [openUserModal]);
useEffect(() => {
if (activeUserId) {
setOpenUserModal(true);
useEffect(() => {
if (activeUserId) {
setOpenUserModal(true);
return;
}
return;
}
setOpenUserModal(false);
}, [activeUserId]);
setOpenUserModal(false);
}, [activeUserId]);
const copyQuizLink = (quizId: string) => {
navigator.clipboard.writeText(
`https://${
window.location.href.includes("/admin.") ? "" : "s."
}hbpn.link/${quizId}`
);
const copyQuizLink = (quizId: string) => {
navigator.clipboard.writeText(`https://${window.location.href.includes("/admin.") ? "" : "s."}hbpn.link/${quizId}`);
enqueueSnackbar("Ссылка успешно скопирована");
};
enqueueSnackbar("Ссылка успешно скопирована");
};
return (
<>
<Typography sx={{ mt: "20px", mb: "20px" }}>
Статистика переходов с шильдика
</Typography>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<DataGrid
sx={{ marginTop: "30px", width: "80%" }}
getRowId={({ ID }) => ID}
checkboxSelection={true}
rows={statistics}
components={{ Toolbar: GridToolbar }}
rowCount={statistics.length}
rowsPerPageOptions={[1, 10, 25, 50, 100]}
paginationMode="client"
disableSelectionOnClick
page={page}
pageSize={pageSize}
onPageChange={setPage}
onPageSizeChange={setPageSize}
onCellClick={({ id, field }) =>
field === "user" && setActiveUserId(String(id))
}
getRowHeight={() => "auto"}
columns={[
...COLUMNS,
{
field: "quizes",
headerName: "Квизы",
flex: 1,
minWidth: 220,
valueGetter: ({ row }) => String(row.Quizes.length),
renderCell: ({ row }) => (
<Accordion sx={{ width: "100%" }}>
<AccordionSummary
sx={{ backgroundColor: "#26272c", color: "#FFFFFF" }}
expandIcon={<ExpandMoreIcon sx={{ color: "#FFFFFF" }} />}
aria-controls="panel1-content"
id="panel1-header"
>
Статистика по квизам
</AccordionSummary>
<AccordionDetails sx={{ backgroundColor: "#26272c" }}>
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
QuizID
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Регистрации
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Деньги
</TableCell>
</TableRow>
</TableHead>
return (
<>
<Typography sx={{ mt: "20px", mb: "20px" }}>Статистика переходов с шильдика</Typography>
<DateFilter from={from} to={to} setFrom={setFrom} setTo={setTo} />
<DataGrid
sx={{ marginTop: "30px", width: "80%" }}
getRowId={({ ID }) => ID}
checkboxSelection={true}
rows={statistics}
components={{ Toolbar: GridToolbar }}
rowCount={statistics.length}
rowsPerPageOptions={[1, 10, 25, 50, 100]}
paginationMode="client"
disableSelectionOnClick
page={page}
pageSize={pageSize}
onPageChange={setPage}
onPageSizeChange={setPageSize}
onCellClick={({ id, field }) => field === "user" && setActiveUserId(String(id))}
getRowHeight={() => "auto"}
columns={[
...COLUMNS,
{
field: "quizes",
headerName: "Квизы",
flex: 1,
minWidth: 220,
valueGetter: ({ row }) => String(row.Quizes.length),
renderCell: ({ row }) => (
<Accordion sx={{ width: "100%" }}>
<AccordionSummary
sx={{ backgroundColor: "#26272c", color: "#FFFFFF" }}
expandIcon={<ExpandMoreIcon sx={{ color: "#FFFFFF" }} />}
aria-controls="panel1-content"
id="panel1-header"
>
Статистика по квизам
</AccordionSummary>
<AccordionDetails sx={{ backgroundColor: "#26272c" }}>
<Table
sx={{
width: "80%",
border: "2px solid",
borderColor: theme.palette.secondary.main,
bgcolor: theme.palette.content.main,
color: "white",
}}
>
<TableHead>
<TableRow
sx={{
borderBottom: "2px solid",
borderColor: theme.palette.grayLight.main,
height: "100px",
}}
>
<TableCell sx={{ color: "inherit" }} align="center">
QuizID
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Регистрации
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
Деньги
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{row.Quizes.map(({ QuizID, Regs, Money }) => (
<TableRow key={QuizID}>
<TableCell sx={{ color: "inherit" }} align="center">
<Button onClick={() => copyQuizLink(QuizID)}>
{QuizID}
</Button>
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Regs}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{(Money / 100).toFixed(2)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</AccordionDetails>
</Accordion>
),
},
]}
/>
<ModalUser
open={openUserModal}
onClose={() => setOpenUserModal(false)}
userId={activeUserId}
/>
</>
);
<TableBody>
{row.Quizes.map(({ QuizID, Regs, Money }) => (
<TableRow key={QuizID}>
<TableCell sx={{ color: "inherit" }} align="center">
<Button onClick={() => copyQuizLink(QuizID)}>{QuizID}</Button>
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{Regs}
</TableCell>
<TableCell sx={{ color: "inherit" }} align="center">
{(Money / 100).toFixed(2)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</AccordionDetails>
</Accordion>
),
},
]}
/>
<ModalUser open={openUserModal} onClose={() => setOpenUserModal(false)} userId={activeUserId} />
</>
);
};

@ -8,11 +8,11 @@ import { StatisticsSchild } from "./StatisticsSchild";
import { StatisticsPromocode } from "./StastisticsPromocode";
export const QuizStatistics = () => (
<LocalizationProvider dateAdapter={AdapterMoment}>
<QuizInfo />
<StatisticsSchild />
<Suspense fallback={<Box>Loading...</Box>}>
<StatisticsPromocode />
</Suspense>
</LocalizationProvider>
<LocalizationProvider dateAdapter={AdapterMoment}>
<QuizInfo />
<StatisticsSchild />
<Suspense fallback={<Box>Loading...</Box>}>
<StatisticsPromocode />
</Suspense>
</LocalizationProvider>
);

@ -7,86 +7,86 @@ import DataGrid from "@kitUI/datagrid";
import type { UserType } from "@root/api/roles";
const columns: GridColDef<UserType, string>[] = [
{
field: "login",
headerName: "Логин",
width: 200,
valueGetter: ({ row }) => row.login,
},
{
field: "email",
headerName: "E-mail",
width: 200,
valueGetter: ({ row }) => row.email,
},
{
field: "phoneNumber",
headerName: "Номер телефона",
width: 200,
valueGetter: ({ row }) => row.phoneNumber,
},
{
field: "isDeleted",
headerName: "Удалено",
width: 100,
valueGetter: ({ row }) => `${row.isDeleted ? "true" : "false"}`,
},
{
field: "createdAt",
headerName: "Дата создания",
width: 200,
valueGetter: ({ row }) => row.createdAt,
},
{
field: "login",
headerName: "Логин",
width: 200,
valueGetter: ({ row }) => row.login,
},
{
field: "email",
headerName: "E-mail",
width: 200,
valueGetter: ({ row }) => row.email,
},
{
field: "phoneNumber",
headerName: "Номер телефона",
width: 200,
valueGetter: ({ row }) => row.phoneNumber,
},
{
field: "isDeleted",
headerName: "Удалено",
width: 100,
valueGetter: ({ row }) => `${row.isDeleted ? "true" : "false"}`,
},
{
field: "createdAt",
headerName: "Дата создания",
width: 200,
valueGetter: ({ row }) => row.createdAt,
},
];
interface Props {
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
users: UserType[];
page: number;
setPage: (page: number) => void;
pageSize: number;
pagesCount: number;
onPageSizeChange?: (count: number) => void;
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
users: UserType[];
page: number;
setPage: (page: number) => void;
pageSize: number;
pagesCount: number;
onPageSizeChange?: (count: number) => void;
}
export default function ServiceUsersDG({
handleSelectionChange,
users = [],
page,
setPage,
pageSize = 10,
pagesCount = 1,
onPageSizeChange,
handleSelectionChange,
users = [],
page,
setPage,
pageSize = 10,
pagesCount = 1,
onPageSizeChange,
}: Props) {
const navigate = useNavigate();
const navigate = useNavigate();
return (
<>
{users.length ? (
<DataGrid
sx={{ maxWidth: "90%", mt: "30px" }}
getRowId={(users) => users._id}
checkboxSelection={true}
rows={users}
columns={columns}
components={{ Toolbar: GridToolbar }}
rowCount={pageSize * pagesCount}
rowsPerPageOptions={[10, 25, 50, 100]}
paginationMode="server"
page={page}
pageSize={pageSize}
onPageChange={setPage}
onPageSizeChange={onPageSizeChange}
onSelectionModelChange={handleSelectionChange}
onCellClick={({ row }, event) => {
event.stopPropagation();
return (
<>
{users.length ? (
<DataGrid
sx={{ maxWidth: "90%", mt: "30px" }}
getRowId={(users) => users._id}
checkboxSelection={true}
rows={users}
columns={columns}
components={{ Toolbar: GridToolbar }}
rowCount={pageSize * pagesCount}
rowsPerPageOptions={[10, 25, 50, 100]}
paginationMode="server"
page={page}
pageSize={pageSize}
onPageChange={setPage}
onPageSizeChange={onPageSizeChange}
onSelectionModelChange={handleSelectionChange}
onCellClick={({ row }, event) => {
event.stopPropagation();
navigate(row._id);
}}
/>
) : (
<Skeleton>Loading...</Skeleton>
)}
</>
);
navigate(row._id);
}}
/>
) : (
<Skeleton>Loading...</Skeleton>
)}
</>
);
}

@ -1,5 +1,12 @@
import { Box, IconButton, InputAdornment, TextField, Typography, useMediaQuery, useTheme } from "@mui/material";
import { addOrUpdateMessages, clearMessageState, incrementMessageApiPage, setIsPreventAutoscroll, setTicketMessagesFetchState, useMessageStore } from "@root/stores/messages";
import {
addOrUpdateMessages,
clearMessageState,
incrementMessageApiPage,
setIsPreventAutoscroll,
setTicketMessagesFetchState,
useMessageStore,
} from "@root/stores/messages";
import Message from "./Message";
import SendIcon from "@mui/icons-material/Send";
import AttachFileIcon from "@mui/icons-material/AttachFile";
@ -9,7 +16,14 @@ import { TicketMessage } from "@root/model/ticket";
import { sendTicketMessage } from "@root/api/tickets";
import { enqueueSnackbar } from "notistack";
import { useTicketStore } from "@root/stores/tickets";
import { getMessageFromFetchError, throttle, useEventListener, useSSESubscription, useTicketMessages, useToken } from "@frontend/kitui";
import {
getMessageFromFetchError,
throttle,
useEventListener,
useSSESubscription,
useTicketMessages,
useToken,
} from "@frontend/kitui";
import makeRequest from "@root/api/makeRequest";
import ChatImage from "./ChatImage";
import ChatDocument from "./ChatDocument";
@ -17,319 +31,334 @@ import ChatVideo from "./ChatVideo";
import ChatMessage from "./ChatMessage";
import { ACCEPT_SEND_MEDIA_TYPES_MAP, MAX_FILE_SIZE, MAX_PHOTO_SIZE, MAX_VIDEO_SIZE } from "./fileUpload";
const tooLarge = "Файл слишком большой"
const tooLarge = "Файл слишком большой";
const checkAcceptableMediaType = (file: File) => {
if (file === null) return ""
const segments = file?.name.split('.');
const extension = segments[segments.length - 1];
const type = extension.toLowerCase();
switch (type) {
case ACCEPT_SEND_MEDIA_TYPES_MAP.document.find(name => name === type):
if (file.size > MAX_FILE_SIZE) return tooLarge
return ""
case ACCEPT_SEND_MEDIA_TYPES_MAP.picture.find(name => name === type):
if (file.size > MAX_PHOTO_SIZE) return tooLarge
return ""
case ACCEPT_SEND_MEDIA_TYPES_MAP.video.find(name => name === type):
if (file.size > MAX_VIDEO_SIZE) return tooLarge
return ""
default:
return "Не удалось отправить файл. Недопустимый тип"
}
}
if (file === null) return "";
const segments = file?.name.split(".");
const extension = segments[segments.length - 1];
const type = extension.toLowerCase();
switch (type) {
case ACCEPT_SEND_MEDIA_TYPES_MAP.document.find((name) => name === type):
if (file.size > MAX_FILE_SIZE) return tooLarge;
return "";
case ACCEPT_SEND_MEDIA_TYPES_MAP.picture.find((name) => name === type):
if (file.size > MAX_PHOTO_SIZE) return tooLarge;
return "";
case ACCEPT_SEND_MEDIA_TYPES_MAP.video.find((name) => name === type):
if (file.size > MAX_VIDEO_SIZE) return tooLarge;
return "";
default:
return "Не удалось отправить файл. Недопустимый тип";
}
};
export default function Chat() {
const token = useToken();
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const tickets = useTicketStore(state => state.tickets);
const messages = useMessageStore(state => state.messages);
const [messageField, setMessageField] = useState<string>("");
const ticketId = useParams().ticketId;
const chatBoxRef = useRef<HTMLDivElement>(null);
const messageApiPage = useMessageStore(state => state.apiPage);
const messagesPerPage = useMessageStore(state => state.messagesPerPage);
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
const fetchState = useMessageStore(state => state.ticketMessagesFetchState);
const lastMessageId = useMessageStore(state => state.lastMessageId);
const fileInputRef = useRef<HTMLInputElement>(null);
const [disableFileButton, setDisableFileButton] = useState(false);
const token = useToken();
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const tickets = useTicketStore((state) => state.tickets);
const messages = useMessageStore((state) => state.messages);
const [messageField, setMessageField] = useState<string>("");
const ticketId = useParams().ticketId;
const chatBoxRef = useRef<HTMLDivElement>(null);
const messageApiPage = useMessageStore((state) => state.apiPage);
const messagesPerPage = useMessageStore((state) => state.messagesPerPage);
const isPreventAutoscroll = useMessageStore((state) => state.isPreventAutoscroll);
const fetchState = useMessageStore((state) => state.ticketMessagesFetchState);
const lastMessageId = useMessageStore((state) => state.lastMessageId);
const fileInputRef = useRef<HTMLInputElement>(null);
const [disableFileButton, setDisableFileButton] = useState(false);
const ticket = tickets.find(ticket => ticket.id === ticketId);
const ticket = tickets.find((ticket) => ticket.id === ticketId);
useTicketMessages({
url: process.env.REACT_APP_DOMAIN + "/heruvym/getMessages",
ticketId,
messagesPerPage,
messageApiPage,
onSuccess: messages => {
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
addOrUpdateMessages(messages);
},
onError: (error: Error) => {
const message = getMessageFromFetchError(error);
if (message) enqueueSnackbar(message);
},
onFetchStateChange: setTicketMessagesFetchState,
});
useTicketMessages({
url: process.env.REACT_APP_DOMAIN + "/heruvym/getMessages",
ticketId,
messagesPerPage,
messageApiPage,
onSuccess: (messages) => {
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
addOrUpdateMessages(messages);
},
onError: (error: Error) => {
const message = getMessageFromFetchError(error);
if (message) enqueueSnackbar(message);
},
onFetchStateChange: setTicketMessagesFetchState,
});
useSSESubscription<TicketMessage>({
enabled: Boolean(token) && Boolean(ticketId),
url: process.env.REACT_APP_DOMAIN + `/heruvym/ticket?ticket=${ticketId}&Authorization=${token}`,
onNewData: addOrUpdateMessages,
onDisconnect: () => {
clearMessageState();
setIsPreventAutoscroll(false);
},
marker: "ticket message"
});
useSSESubscription<TicketMessage>({
enabled: Boolean(token) && Boolean(ticketId),
url: process.env.REACT_APP_DOMAIN + `/heruvym/ticket?ticket=${ticketId}&Authorization=${token}`,
onNewData: addOrUpdateMessages,
onDisconnect: () => {
clearMessageState();
setIsPreventAutoscroll(false);
},
marker: "ticket message",
});
const throttledScrollHandler = useMemo(() => throttle(() => {
const chatBox = chatBoxRef.current;
if (!chatBox) return;
const throttledScrollHandler = useMemo(
() =>
throttle(() => {
const chatBox = chatBoxRef.current;
if (!chatBox) return;
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight * 20;
setIsPreventAutoscroll(isPreventAutoscroll);
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight * 20;
setIsPreventAutoscroll(isPreventAutoscroll);
if (fetchState !== "idle") return;
if (fetchState !== "idle") return;
if (chatBox.scrollTop < chatBox.clientHeight) {
incrementMessageApiPage();
}
}, 200), [fetchState]);
if (chatBox.scrollTop < chatBox.clientHeight) {
incrementMessageApiPage();
}
}, 200),
[fetchState]
);
useEventListener("scroll", throttledScrollHandler, chatBoxRef);
useEventListener("scroll", throttledScrollHandler, chatBoxRef);
useEffect(function scrollOnNewMessage() {
if (!chatBoxRef.current) return;
useEffect(
function scrollOnNewMessage() {
if (!chatBoxRef.current) return;
if (!isPreventAutoscroll) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lastMessageId]);
if (!isPreventAutoscroll) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
},
[lastMessageId]
);
function scrollToBottom(behavior?: ScrollBehavior) {
if (!chatBoxRef.current) return;
function scrollToBottom(behavior?: ScrollBehavior) {
if (!chatBoxRef.current) return;
const chatBox = chatBoxRef.current;
chatBox.scroll({
left: 0,
top: chatBox.scrollHeight,
behavior,
});
}
const chatBox = chatBoxRef.current;
chatBox.scroll({
left: 0,
top: chatBox.scrollHeight,
behavior,
});
}
function handleSendMessage() {
if (!ticket || !messageField) return;
function handleSendMessage() {
if (!ticket || !messageField) return;
sendTicketMessage({
files: [],
lang: "ru",
message: messageField,
ticket: ticket.id,
});
setMessageField("");
}
sendTicketMessage({
files: [],
lang: "ru",
message: messageField,
ticket: ticket.id,
});
setMessageField("");
}
const sendFile = async (file: File) => {
if (file === undefined) return true;
let data;
const ticketId = ticket?.id
if (ticketId !== undefined) {
try {
const body = new FormData();
body.append(file.name, file);
body.append("ticket", ticketId);
await makeRequest({
url: process.env.REACT_APP_DOMAIN + "/heruvym/sendFiles",
body: body,
method: "POST",
});
} catch (error: any) {
const errorMessage = getMessageFromFetchError(error);
if (errorMessage) enqueueSnackbar(errorMessage);
}
return true;
}
};
const sendFileHC = async (file: File) => {
const check = checkAcceptableMediaType(file)
if (check.length > 0) {
enqueueSnackbar(check)
return
}
setDisableFileButton(true)
await sendFile(file)
setDisableFileButton(false)
};
const sendFile = async (file: File) => {
if (file === undefined) return true;
function handleTextfieldKeyPress(e: KeyboardEvent) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
}
let data;
return (
<Box sx={{
border: "1px solid",
borderColor: theme.palette.grayDark.main,
height: "600px",
borderRadius: "3px",
p: "8px",
display: "flex",
flex: upMd ? "2 0 0" : undefined,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
gap: "8px",
}}>
<Typography>{ticket ? ticket.title : "Выберите тикет"}</Typography>
<Box
ref={chatBoxRef}
sx={{
width: "100%",
backgroundColor: "#46474a",
flexGrow: 1,
display: "flex",
flexDirection: "column",
gap: "12px",
p: "8px",
overflow: "auto",
colorScheme: "dark",
}}
>
{ticket &&
messages.map((message) => {
const isFileVideo = () => {
if (message.files) {
return (ACCEPT_SEND_MEDIA_TYPES_MAP.video.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType),
))
}
};
const isFileImage = () => {
if (message.files) {
return (ACCEPT_SEND_MEDIA_TYPES_MAP.picture.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType),
))
}
};
const isFileDocument = () => {
if (message.files) {
return (ACCEPT_SEND_MEDIA_TYPES_MAP.document.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType),
))
}
};
if (message.files !== null && message.files.length > 0 && isFileImage()) {
return <ChatImage
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
}
if (message.files !== null && message.files.length > 0 && isFileVideo()) {
return <ChatVideo
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
}
if (message.files !== null && message.files.length > 0 && isFileDocument()) {
return <ChatDocument
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
}
return <ChatMessage
unAuthenticated
key={message.id}
text={message.message}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
const ticketId = ticket?.id;
if (ticketId !== undefined) {
try {
const body = new FormData();
})
}
</Box>
{ticket &&
<TextField
value={messageField}
onChange={e => setMessageField(e.target.value)}
onKeyPress={handleTextfieldKeyPress}
id="message-input"
placeholder="Написать сообщение"
fullWidth
multiline
maxRows={8}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleSendMessage}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<SendIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
<IconButton
onClick={() => {
if (!disableFileButton) fileInputRef.current?.click()
}}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<input
ref={fileInputRef}
id="fileinput"
onChange={(e) => {
if (e.target.files?.[0]) sendFileHC(e.target.files?.[0]);
}}
style={{ display: "none" }}
type="file"
/>
<AttachFileIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
</InputAdornment>
)
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
}
}}
/>
}
</Box>
);
body.append(file.name, file);
body.append("ticket", ticketId);
await makeRequest({
url: process.env.REACT_APP_DOMAIN + "/heruvym/sendFiles",
body: body,
method: "POST",
});
} catch (error: any) {
const errorMessage = getMessageFromFetchError(error);
if (errorMessage) enqueueSnackbar(errorMessage);
}
return true;
}
};
const sendFileHC = async (file: File) => {
const check = checkAcceptableMediaType(file);
if (check.length > 0) {
enqueueSnackbar(check);
return;
}
setDisableFileButton(true);
await sendFile(file);
setDisableFileButton(false);
};
function handleTextfieldKeyPress(e: KeyboardEvent) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
}
return (
<Box
sx={{
border: "1px solid",
borderColor: theme.palette.grayDark.main,
height: "600px",
borderRadius: "3px",
p: "8px",
display: "flex",
flex: upMd ? "2 0 0" : undefined,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
gap: "8px",
}}
>
<Typography>{ticket ? ticket.title : "Выберите тикет"}</Typography>
<Box
ref={chatBoxRef}
sx={{
width: "100%",
backgroundColor: "#46474a",
flexGrow: 1,
display: "flex",
flexDirection: "column",
gap: "12px",
p: "8px",
overflow: "auto",
colorScheme: "dark",
}}
>
{ticket &&
messages.map((message) => {
const isFileVideo = () => {
if (message.files) {
return ACCEPT_SEND_MEDIA_TYPES_MAP.video.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType)
);
}
};
const isFileImage = () => {
if (message.files) {
return ACCEPT_SEND_MEDIA_TYPES_MAP.picture.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType)
);
}
};
const isFileDocument = () => {
if (message.files) {
return ACCEPT_SEND_MEDIA_TYPES_MAP.document.some((fileType) =>
message.files[0].toLowerCase().endsWith(fileType)
);
}
};
if (message.files !== null && message.files.length > 0 && isFileImage()) {
return (
<ChatImage
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
);
}
if (message.files !== null && message.files.length > 0 && isFileVideo()) {
return (
<ChatVideo
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
);
}
if (message.files !== null && message.files.length > 0 && isFileDocument()) {
return (
<ChatDocument
unAuthenticated
key={message.id}
file={message.files[0]}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
);
}
return (
<ChatMessage
unAuthenticated
key={message.id}
text={message.message}
createdAt={message.created_at}
isSelf={ticket.user !== message.user_id}
/>
);
})}
</Box>
{ticket && (
<TextField
value={messageField}
onChange={(e) => setMessageField(e.target.value)}
onKeyPress={handleTextfieldKeyPress}
id="message-input"
placeholder="Написать сообщение"
fullWidth
multiline
maxRows={8}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleSendMessage}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<SendIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
<IconButton
onClick={() => {
if (!disableFileButton) fileInputRef.current?.click();
}}
sx={{
height: "45px",
width: "45px",
p: 0,
}}
>
<input
ref={fileInputRef}
id="fileinput"
onChange={(e) => {
if (e.target.files?.[0]) sendFileHC(e.target.files?.[0]);
}}
style={{ display: "none" }}
type="file"
/>
<AttachFileIcon sx={{ color: theme.palette.golden.main }} />
</IconButton>
</InputAdornment>
),
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
)}
</Box>
);
}

@ -1,62 +1,58 @@
import { Box, Link, Typography, useMediaQuery, useTheme } from "@mui/material";
import DownloadIcon from '@mui/icons-material/Download';
import DownloadIcon from "@mui/icons-material/Download";
interface Props {
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
}
export default function ChatDocument({
unAuthenticated = false,
isSelf,
file,
createdAt,
}: Props) {
const theme = useTheme();
export default function ChatDocument({ unAuthenticated = false, isSelf, file, createdAt }: Props) {
const theme = useTheme();
const date = new Date(createdAt);
const date = new Date(createdAt);
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography sx={{
fontSize: "12px",
alignSelf: "end",
}}>
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Link
download
href={`https://admin.pena/pair/${file}`}
style={{
color: "#7E2AEA",
display: "flex",
gap: "10px",
}}
>
<DownloadIcon/>
</Link>
</Box>
</Box>
);
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Link
download
href={`https://admin.pena/pair/${file}`}
style={{
color: "#7E2AEA",
display: "flex",
gap: "10px",
}}
>
<DownloadIcon />
</Link>
</Box>
</Box>
);
}

@ -1,68 +1,57 @@
import {
Box,
ButtonBase,
Link,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import { Box, ButtonBase, Link, Typography, useMediaQuery, useTheme } from "@mui/material";
import { useNavigate } from "react-router-dom";
interface Props {
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
}
export default function ChatImage({
unAuthenticated = false,
isSelf,
file,
createdAt,
}: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const navigate = useNavigate();
export default function ChatImage({ unAuthenticated = false, isSelf, file, createdAt }: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const navigate = useNavigate();
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography sx={{
fontSize: "12px",
alignSelf: "end",
}}>
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<ButtonBase target="_blank" href={`/image/${file}`}>
<Box
component="img"
sx={{
height: "217px",
width: "217px",
}}
src={`https://admin.pena/pair/${file}`}
/>
</ButtonBase>
</Box>
</Box>
);
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<ButtonBase target="_blank" href={`/image/${file}`}>
<Box
component="img"
sx={{
height: "217px",
width: "217px",
}}
src={`https://admin.pena/pair/${file}`}
/>
</ButtonBase>
</Box>
</Box>
);
}

@ -1,53 +1,48 @@
import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
interface Props {
unAuthenticated?: boolean;
isSelf: boolean;
text: string;
createdAt: string;
unAuthenticated?: boolean;
isSelf: boolean;
text: string;
createdAt: string;
}
export default function ChatMessage({
unAuthenticated = false,
isSelf,
text,
createdAt,
}: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
export default function ChatMessage({ unAuthenticated = false, isSelf, text, createdAt }: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography sx={{
fontSize: "12px",
alignSelf: "end",
}}>
{new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Typography fontSize="14px" sx={{ wordBreak: "break-word" }}>
{text}
</Typography>
</Box>
</Box>
);
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Typography fontSize="14px" sx={{ wordBreak: "break-word" }}>
{text}
</Typography>
</Box>
</Box>
);
}

@ -2,66 +2,61 @@ import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
import { useNavigate } from "react-router-dom";
interface Props {
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
unAuthenticated?: boolean;
isSelf: boolean;
file: string;
createdAt: string;
}
export default function ChatImage({
unAuthenticated = false,
isSelf,
file,
createdAt,
}: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const navigate = useNavigate();
export default function ChatImage({ unAuthenticated = false, isSelf, file, createdAt }: Props) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const navigate = useNavigate();
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(createdAt).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Box
component="video"
sx={{
pointerEvents: "auto",
height: "217px",
width: "auto",
minWidth: "217px",
}}
controls
>
<source src={`https://admin.pena/pair/${file}`} />
</Box>
</Box>
</Box>
);
return (
<Box
sx={{
display: "flex",
gap: "9px",
padding: isSelf ? "0 8px 0 0" : "0 0 0 8px",
justifyContent: isSelf ? "end" : "start",
}}
>
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(createdAt).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</Typography>
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Box
component="video"
sx={{
pointerEvents: "auto",
height: "217px",
width: "auto",
minWidth: "217px",
}}
controls
>
<source src={`https://admin.pena/pair/${file}`} />
</Box>
</Box>
</Box>
);
}

@ -1,44 +1,49 @@
import { Box, Typography, useTheme } from "@mui/material";
import { TicketMessage } from "@root/model/ticket";
interface Props {
message: TicketMessage;
isSelf?: boolean;
message: TicketMessage;
isSelf?: boolean;
}
export default function Message({ message, isSelf }: Props) {
const theme = useTheme();
const theme = useTheme();
const time = (
<Typography sx={{
fontSize: "12px",
alignSelf: "end",
}}>
{new Date(message.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</Typography>
);
return (
<Box sx={{
display: "flex",
justifyContent: isSelf ? "end" : "start",
gap: "6px",
}}>
{isSelf && time}
<Box sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}>
<Typography fontSize="14px" sx={{ wordBreak: "break-word" }}>
{message.message}
</Typography>
</Box>
{!isSelf && time}
</Box>
);
}
const time = (
<Typography
sx={{
fontSize: "12px",
alignSelf: "end",
}}
>
{new Date(message.created_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</Typography>
);
return (
<Box
sx={{
display: "flex",
justifyContent: isSelf ? "end" : "start",
gap: "6px",
}}
>
{isSelf && time}
<Box
sx={{
backgroundColor: "#2a2b2c",
p: "12px",
border: `1px solid ${theme.palette.golden.main}`,
borderRadius: "20px",
borderTopLeftRadius: isSelf ? "20px" : 0,
borderTopRightRadius: isSelf ? 0 : "20px",
maxWidth: "90%",
}}
>
<Typography fontSize="14px" sx={{ wordBreak: "break-word" }}>
{message.message}
</Typography>
</Box>
{!isSelf && time}
</Box>
);
}

@ -3,7 +3,7 @@ export const MAX_PHOTO_SIZE = 5242880;
export const MAX_VIDEO_SIZE = 52428800;
export const ACCEPT_SEND_MEDIA_TYPES_MAP = {
picture: ["jpg", "png"],
video: ["mp4"],
document: ["doc", "docx", "pdf", "txt", "xlsx", "csv"],
} as const;
picture: ["jpg", "png"],
video: ["mp4"],
document: ["doc", "docx", "pdf", "txt", "xlsx", "csv"],
} as const;

@ -2,18 +2,18 @@ import { Box } from "@mui/material";
import { useLocation } from "react-router-dom";
export default function ChatImageNewWindow() {
const location = useLocation();
const srcImage = location.pathname.split("image/")[1];
return (
<>
<Box
component="img"
sx={{
maxHeight: "100vh",
maxWidth: "100vw",
}}
src={`https://admin.pena/pair/${srcImage}`}
/>
</>
);
const location = useLocation();
const srcImage = location.pathname.split("image/")[1];
return (
<>
<Box
component="img"
sx={{
maxHeight: "100vh",
maxWidth: "100vw",
}}
src={`https://admin.pena/pair/${srcImage}`}
/>
</>
);
}

@ -3,51 +3,51 @@ import { Box, Typography, useTheme } from "@mui/material";
import ExpandIcon from "./ExpandIcon";
interface Props {
headerText: string;
children: (callback: () => void) => ReactNode;
headerText: string;
children: (callback: () => void) => ReactNode;
}
export default function Collapse({ headerText, children }: Props) {
const theme = useTheme();
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const theme = useTheme();
const [isExpanded, setIsExpanded] = useState<boolean>(false);
return (
<Box
sx={{
position: "relative",
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "72px",
p: "16px",
backgroundColor: theme.palette.menu.main,
borderRadius: "12px",
return (
<Box
sx={{
position: "relative",
}}
>
<Box
onClick={() => setIsExpanded((prev) => !prev)}
sx={{
height: "72px",
p: "16px",
backgroundColor: theme.palette.menu.main,
borderRadius: "12px",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography variant="h4">{headerText}</Typography>
<ExpandIcon isExpanded={isExpanded} />
</Box>
{isExpanded && (
<Box
sx={{
mt: "8px",
position: "absolute",
zIndex: 100,
backgroundColor: theme.palette.content.main,
width: "100%",
}}
>
{children(() => setIsExpanded(false))}
</Box>
)}
</Box>
);
display: "flex",
justifyContent: "space-between",
alignItems: "center",
cursor: "pointer",
userSelect: "none",
}}
>
<Typography variant="h4">{headerText}</Typography>
<ExpandIcon isExpanded={isExpanded} />
</Box>
{isExpanded && (
<Box
sx={{
mt: "8px",
position: "absolute",
zIndex: 100,
backgroundColor: theme.palette.content.main,
width: "100%",
}}
>
{children(() => setIsExpanded(false))}
</Box>
)}
</Box>
);
}

@ -1,17 +1,34 @@
import { useTheme } from "@mui/material";
interface Props {
isExpanded: boolean;
isExpanded: boolean;
}
export default function ExpandIcon({ isExpanded }: Props) {
const theme = useTheme();
const theme = useTheme();
return (
<svg style={{ transform: isExpanded ? "rotate(180deg)" : undefined }} xmlns="http://www.w3.org/2000/svg" width="32" height="33" viewBox="0 0 32 33" fill="none">
<path stroke={isExpanded ? theme.palette.golden.main : theme.palette.goldenDark.main} d="M16 28.7949C22.6274 28.7949 28 23.4223 28 16.7949C28 10.1675 22.6274 4.79492 16 4.79492C9.37258 4.79492 4 10.1675 4 16.7949C4 23.4223 9.37258 28.7949 16 28.7949Z" strokeWidth="2" strokeMiterlimit="10" />
<path stroke={isExpanded ? theme.palette.golden.main : theme.palette.goldenDark.main} d="M20.5 15.2949L16 20.2949L11.5 15.2949" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
return (
<svg
style={{ transform: isExpanded ? "rotate(180deg)" : undefined }}
xmlns="http://www.w3.org/2000/svg"
width="32"
height="33"
viewBox="0 0 32 33"
fill="none"
>
<path
stroke={isExpanded ? theme.palette.golden.main : theme.palette.goldenDark.main}
d="M16 28.7949C22.6274 28.7949 28 23.4223 28 16.7949C28 10.1675 22.6274 4.79492 16 4.79492C9.37258 4.79492 4 10.1675 4 16.7949C4 23.4223 9.37258 28.7949 16 28.7949Z"
strokeWidth="2"
strokeMiterlimit="10"
/>
<path
stroke={isExpanded ? theme.palette.golden.main : theme.palette.goldenDark.main}
d="M20.5 15.2949L16 20.2949L11.5 15.2949"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}

@ -4,100 +4,79 @@ import Chat from "./Chat/Chat";
import Collapse from "./Collapse";
import TicketList from "./TicketList/TicketList";
import { Ticket } from "@root/model/ticket";
import {
clearTickets,
setTicketsFetchState,
updateTickets,
useTicketStore,
} from "@root/stores/tickets";
import { clearTickets, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
import { enqueueSnackbar } from "notistack";
import { clearMessageState } from "@root/stores/messages";
import {
getMessageFromFetchError,
useSSESubscription,
useTicketsFetcher,
useToken,
} from "@frontend/kitui";
import { getMessageFromFetchError, useSSESubscription, useTicketsFetcher, useToken } from "@frontend/kitui";
import ModalUser from "@root/pages/dashboard/ModalUser";
export default function Support() {
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
const [activeUserId, setActiveUserId] = useState<string>("");
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
const ticketApiPage = useTicketStore((state) => state.apiPage);
const token = useToken();
const [openUserModal, setOpenUserModal] = useState<boolean>(false);
const [activeUserId, setActiveUserId] = useState<string>("");
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
const ticketApiPage = useTicketStore((state) => state.apiPage);
const token = useToken();
useTicketsFetcher({
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
ticketsPerPage,
ticketApiPage,
onSuccess: (result) => {
if (result.data) updateTickets(result.data);
},
onError: (error: Error) => {
const message = getMessageFromFetchError(error);
if (message) enqueueSnackbar(message);
},
onFetchStateChange: setTicketsFetchState,
});
useTicketsFetcher({
url: process.env.REACT_APP_DOMAIN + "/heruvym/getTickets",
ticketsPerPage,
ticketApiPage,
onSuccess: (result) => {
if (result.data) updateTickets(result.data);
},
onError: (error: Error) => {
const message = getMessageFromFetchError(error);
if (message) enqueueSnackbar(message);
},
onFetchStateChange: setTicketsFetchState,
});
useSSESubscription<Ticket>({
enabled: Boolean(token),
url:
process.env.REACT_APP_DOMAIN +
`/heruvym/subscribe?Authorization=${token}`,
onNewData: updateTickets,
onDisconnect: () => {
clearMessageState();
clearTickets();
},
marker: "ticket",
});
useSSESubscription<Ticket>({
enabled: Boolean(token),
url: process.env.REACT_APP_DOMAIN + `/heruvym/subscribe?Authorization=${token}`,
onNewData: updateTickets,
onDisconnect: () => {
clearMessageState();
clearTickets();
},
marker: "ticket",
});
useEffect(() => {
if (!openUserModal) {
setActiveUserId("");
}
}, [openUserModal]);
useEffect(() => {
if (!openUserModal) {
setActiveUserId("");
}
}, [openUserModal]);
useEffect(() => {
if (activeUserId) {
setOpenUserModal(true);
useEffect(() => {
if (activeUserId) {
setOpenUserModal(true);
return;
}
return;
}
setOpenUserModal(false);
}, [activeUserId]);
setOpenUserModal(false);
}, [activeUserId]);
return (
<Box
sx={{
display: "flex",
width: "100%",
flexDirection: upMd ? "row" : "column",
gap: "12px",
}}
>
{!upMd && (
<Collapse headerText="Тикеты">
{(closeCollapse) => (
<TicketList
closeCollapse={closeCollapse}
setActiveUserId={setActiveUserId}
/>
)}
</Collapse>
)}
<Chat />
{upMd && <TicketList setActiveUserId={setActiveUserId} />}
<ModalUser
open={openUserModal}
onClose={() => setOpenUserModal(false)}
userId={activeUserId}
/>
</Box>
);
return (
<Box
sx={{
display: "flex",
width: "100%",
flexDirection: upMd ? "row" : "column",
gap: "12px",
}}
>
{!upMd && (
<Collapse headerText="Тикеты">
{(closeCollapse) => <TicketList closeCollapse={closeCollapse} setActiveUserId={setActiveUserId} />}
</Collapse>
)}
<Chat />
{upMd && <TicketList setActiveUserId={setActiveUserId} />}
<ModalUser open={openUserModal} onClose={() => setOpenUserModal(false)} userId={activeUserId} />
</Box>
);
}

@ -1,87 +1,83 @@
import Modal from "@mui/material/Modal";
import {closeDeleteTariffDialog} from "@stores/tariffs";
import { closeDeleteTariffDialog } from "@stores/tariffs";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import makeRequest from "@root/api/makeRequest";
import {parseAxiosError} from "@root/utils/parse-error";
interface Props{
ticketId: string | undefined,
openModal: boolean,
setOpenModal: (a: boolean) => void
import { parseAxiosError } from "@root/utils/parse-error";
interface Props {
ticketId: string | undefined;
openModal: boolean;
setOpenModal: (a: boolean) => void;
}
export default function CloseTicketModal({ticketId, openModal, setOpenModal}: Props) {
export default function CloseTicketModal({ ticketId, openModal, setOpenModal }: Props) {
const CloseTicket = async () => {
try {
const ticketCloseResponse = await makeRequest<unknown, unknown>({
url: process.env.REACT_APP_DOMAIN + "/heruvym/close",
method: "post",
useToken: true,
body: {
ticket: ticketId,
},
});
const CloseTicket = async () => {
try {
const ticketCloseResponse = await makeRequest<unknown, unknown>({
url: process.env.REACT_APP_DOMAIN + "/heruvym/close" ,
method: "post",
useToken: true,
body: {
"ticket": ticketId
},
});
return [ticketCloseResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [ticketCloseResponse];
} catch (nativeError) {
const [error] = parseAxiosError(nativeError);
return [null, `Не удалось закрыть тикет. ${error}`];
}
};
return [null, `Не удалось закрыть тикет. ${error}`];
}
}
return (
<Modal
open={openModal}
onClose={() => setOpenModal(false)}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Typography id="modal-modal-title" variant="h6" component="h2">
Вы уверены, что хотите закрыть тикет?
</Typography>
<Box
sx={{
mt: "20px",
display: "flex",
width: "332px",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Button
onClick={async ()=>{
CloseTicket()
setOpenModal(false)
}}
sx={{width: "40px", height: "25px"}}
>
Да
</Button>
<Button
onClick={() => setOpenModal(false)}
sx={{width: "40px", height: "25px"}}
>
Нет
</Button>
</Box>
</Box>
</Modal>
)
}
return (
<Modal
open={openModal}
onClose={() => setOpenModal(false)}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid gray",
borderRadius: "6px",
boxShadow: 24,
p: 4,
}}
>
<Typography id="modal-modal-title" variant="h6" component="h2">
Вы уверены, что хотите закрыть тикет?
</Typography>
<Box
sx={{
mt: "20px",
display: "flex",
width: "332px",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Button
onClick={async () => {
CloseTicket();
setOpenModal(false);
}}
sx={{ width: "40px", height: "25px" }}
>
Да
</Button>
<Button onClick={() => setOpenModal(false)} sx={{ width: "40px", height: "25px" }}>
Нет
</Button>
</Box>
</Box>
</Modal>
);
}

@ -1,108 +1,97 @@
import CircleIcon from "@mui/icons-material/Circle";
import {
Box,
Card,
CardActionArea,
CardContent,
CardHeader,
Divider,
Typography,
useTheme,
} from "@mui/material";
import { Box, Card, CardActionArea, CardContent, CardHeader, Divider, Typography, useTheme } from "@mui/material";
import { green } from "@mui/material/colors";
import { Ticket } from "@root/model/ticket";
import { useNavigate, useParams } from "react-router-dom";
const flexCenterSx = {
textAlign: "center",
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "10px",
textAlign: "center",
display: "flex",
justifyContent: "center",
alignItems: "center",
padding: "10px",
};
interface Props {
ticket: Ticket;
setActiveUserId: (userId: string) => void;
ticket: Ticket;
setActiveUserId: (userId: string) => void;
}
export default function TicketItem({ ticket, setActiveUserId }: Props) {
const theme = useTheme();
const navigate = useNavigate();
const ticketId = useParams().ticketId;
const theme = useTheme();
const navigate = useNavigate();
const ticketId = useParams().ticketId;
const isUnread = ticket.user === ticket.top_message.user_id;
const isSelected = ticket.id === ticketId;
const isUnread = ticket.user === ticket.top_message.user_id;
const isSelected = ticket.id === ticketId;
const unreadSx = {
border: "1px solid",
borderColor: theme.palette.golden.main,
backgroundColor: theme.palette.goldenMedium.main,
};
const unreadSx = {
border: "1px solid",
borderColor: theme.palette.golden.main,
backgroundColor: theme.palette.goldenMedium.main,
};
const selectedSx = {
border: `2px solid ${theme.palette.secondary.main}`,
};
const selectedSx = {
border: `2px solid ${theme.palette.secondary.main}`,
};
function handleCardClick() {
navigate(`/support/${ticket.id}`);
}
function handleCardClick() {
navigate(`/support/${ticket.id}`);
}
return (
<Card
sx={{
minHeight: "70px",
backgroundColor: "transparent",
color: "white",
...(isUnread && unreadSx),
...(isSelected && selectedSx),
}}
>
<CardActionArea onClick={handleCardClick}>
<CardHeader
title={<Typography>{ticket.title}</Typography>}
disableTypography
sx={{
textAlign: "center",
p: "4px",
}}
/>
<Divider />
<CardContent
sx={{
display: "flex",
justifyContent: "space-between",
backgroundColor: "transparent",
p: 0,
}}
>
<Box sx={flexCenterSx}>
{new Date(ticket.top_message.created_at).toLocaleDateString()}
</Box>
<Box
sx={{
...flexCenterSx,
overflow: "hidden",
whiteSpace: "nowrap",
display: "block",
flexGrow: 1,
}}
>
{ticket.top_message.message}
</Box>
<Box sx={flexCenterSx}>
<CircleIcon
sx={{
color: green[700],
transform: "scale(0.8)",
}}
/>
</Box>
<Box sx={flexCenterSx} onClick={() => setActiveUserId(ticket.user)}>
ИНФО
</Box>
</CardContent>
</CardActionArea>
</Card>
);
return (
<Card
sx={{
minHeight: "70px",
backgroundColor: "transparent",
color: "white",
...(isUnread && unreadSx),
...(isSelected && selectedSx),
}}
>
<CardActionArea onClick={handleCardClick}>
<CardHeader
title={<Typography>{ticket.title}</Typography>}
disableTypography
sx={{
textAlign: "center",
p: "4px",
}}
/>
<Divider />
<CardContent
sx={{
display: "flex",
justifyContent: "space-between",
backgroundColor: "transparent",
p: 0,
}}
>
<Box sx={flexCenterSx}>{new Date(ticket.top_message.created_at).toLocaleDateString()}</Box>
<Box
sx={{
...flexCenterSx,
overflow: "hidden",
whiteSpace: "nowrap",
display: "block",
flexGrow: 1,
}}
>
{ticket.top_message.message}
</Box>
<Box sx={flexCenterSx}>
<CircleIcon
sx={{
color: green[700],
transform: "scale(0.8)",
}}
/>
</Box>
<Box sx={flexCenterSx} onClick={() => setActiveUserId(ticket.user)}>
ИНФО
</Box>
</CardContent>
</CardActionArea>
</Card>
);
}

@ -3,152 +3,140 @@ import SearchOutlinedIcon from "@mui/icons-material/SearchOutlined";
import { Box, Button, useMediaQuery, useTheme } from "@mui/material";
import { Ticket } from "@root/model/ticket";
import { incrementTicketsApiPage, useTicketStore } from "@root/stores/tickets";
import {useEffect, useRef, useState} from "react";
import { useEffect, useRef, useState } from "react";
import TicketItem from "./TicketItem";
import { throttle } from "@frontend/kitui";
import makeRequest from "@root/api/makeRequest";
import {parseAxiosError} from "@root/utils/parse-error";
import {useParams} from "react-router-dom";
import { parseAxiosError } from "@root/utils/parse-error";
import { useParams } from "react-router-dom";
import CloseTicketModal from "@pages/dashboard/Content/Support/TicketList/CloseTicketModal";
type TicketListProps = {
closeCollapse?: () => void;
setActiveUserId: (id: string) => void;
closeCollapse?: () => void;
setActiveUserId: (id: string) => void;
};
export default function TicketList({
closeCollapse,
setActiveUserId,
}: TicketListProps) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const tickets = useTicketStore((state) => state.tickets);
const ticketsFetchState = useTicketStore((state) => state.ticketsFetchState);
const ticketsBoxRef = useRef<HTMLDivElement>(null);
const ticketId = useParams().ticketId;
const [openModal, setOpenModal] = useState(false)
export default function TicketList({ closeCollapse, setActiveUserId }: TicketListProps) {
const theme = useTheme();
const upMd = useMediaQuery(theme.breakpoints.up("md"));
const tickets = useTicketStore((state) => state.tickets);
const ticketsFetchState = useTicketStore((state) => state.ticketsFetchState);
const ticketsBoxRef = useRef<HTMLDivElement>(null);
const ticketId = useParams().ticketId;
const [openModal, setOpenModal] = useState(false);
useEffect(
function updateCurrentPageOnScroll() {
if (!ticketsBoxRef.current) return;
useEffect(
function updateCurrentPageOnScroll() {
if (!ticketsBoxRef.current) return;
const ticketsBox = ticketsBoxRef.current;
const scrollHandler = () => {
const scrollBottom =
ticketsBox.scrollHeight -
ticketsBox.scrollTop -
ticketsBox.clientHeight;
if (
scrollBottom < ticketsBox.clientHeight &&
ticketsFetchState === "idle"
)
incrementTicketsApiPage();
};
const ticketsBox = ticketsBoxRef.current;
const scrollHandler = () => {
const scrollBottom = ticketsBox.scrollHeight - ticketsBox.scrollTop - ticketsBox.clientHeight;
if (scrollBottom < ticketsBox.clientHeight && ticketsFetchState === "idle") incrementTicketsApiPage();
};
const throttledScrollHandler = throttle(scrollHandler, 200);
ticketsBox.addEventListener("scroll", throttledScrollHandler);
const throttledScrollHandler = throttle(scrollHandler, 200);
ticketsBox.addEventListener("scroll", throttledScrollHandler);
return () => {
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
};
},
[ticketsFetchState]
);
return () => {
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
};
},
[ticketsFetchState]
);
const sortedTickets = tickets
.sort(sortTicketsByUpdateTime)
.sort(sortTicketsByUnread);
const sortedTickets = tickets.sort(sortTicketsByUpdateTime).sort(sortTicketsByUnread);
return (
<Box
sx={{
display: "flex",
flex: upMd ? "3 0 0" : undefined,
maxWidth: upMd ? "400px" : undefined,
maxHeight: "600px",
flexDirection: "column",
alignItems: "center",
}}
>
<Box
sx={{
width: "100%",
border: "1px solid",
borderColor: theme.palette.grayDark.main,
borderRadius: "3px",
padding: "10px",
}}
>
<Button
variant="contained"
sx={{
backgroundColor: theme.palette.grayDark.main,
width: "100%",
height: "45px",
fontSize: "15px",
fontWeight: "normal",
textTransform: "capitalize",
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
Поиск
<SearchOutlinedIcon />
</Button>
<Button
onClick={()=> setOpenModal(true)}
variant="text"
sx={{
width: "100%",
height: "35px",
fontSize: "14px",
fontWeight: "normal",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.golden.main,
borderRadius: 0,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ЗАКРЫТЬ ТИКЕТ
<HighlightOffOutlinedIcon />
</Button>
<CloseTicketModal openModal={openModal} setOpenModal={setOpenModal} ticketId={ticketId}/>
</Box>
<Box
ref={ticketsBoxRef}
sx={{
width: "100%",
border: "1px solid",
borderColor: theme.palette.grayDark.main,
borderRadius: "3px",
overflow: "auto",
overflowY: "auto",
padding: "10px",
colorScheme: "dark",
}}
>
{sortedTickets.map((ticket) => (
<Box key={ticket.id} onClick={closeCollapse}>
<TicketItem ticket={ticket} setActiveUserId={setActiveUserId} />
</Box>
))}
</Box>
</Box>
);
return (
<Box
sx={{
display: "flex",
flex: upMd ? "3 0 0" : undefined,
maxWidth: upMd ? "400px" : undefined,
maxHeight: "600px",
flexDirection: "column",
alignItems: "center",
}}
>
<Box
sx={{
width: "100%",
border: "1px solid",
borderColor: theme.palette.grayDark.main,
borderRadius: "3px",
padding: "10px",
}}
>
<Button
variant="contained"
sx={{
backgroundColor: theme.palette.grayDark.main,
width: "100%",
height: "45px",
fontSize: "15px",
fontWeight: "normal",
textTransform: "capitalize",
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
Поиск
<SearchOutlinedIcon />
</Button>
<Button
onClick={() => setOpenModal(true)}
variant="text"
sx={{
width: "100%",
height: "35px",
fontSize: "14px",
fontWeight: "normal",
color: theme.palette.secondary.main,
border: "1px solid",
borderColor: theme.palette.golden.main,
borderRadius: 0,
"&:hover": {
backgroundColor: theme.palette.menu.main,
},
}}
>
ЗАКРЫТЬ ТИКЕТ
<HighlightOffOutlinedIcon />
</Button>
<CloseTicketModal openModal={openModal} setOpenModal={setOpenModal} ticketId={ticketId} />
</Box>
<Box
ref={ticketsBoxRef}
sx={{
width: "100%",
border: "1px solid",
borderColor: theme.palette.grayDark.main,
borderRadius: "3px",
overflow: "auto",
overflowY: "auto",
padding: "10px",
colorScheme: "dark",
}}
>
{sortedTickets.map((ticket) => (
<Box key={ticket.id} onClick={closeCollapse}>
<TicketItem ticket={ticket} setActiveUserId={setActiveUserId} />
</Box>
))}
</Box>
</Box>
);
}
function sortTicketsByUpdateTime(ticket1: Ticket, ticket2: Ticket) {
const date1 = new Date(ticket1.updated_at).getTime();
const date2 = new Date(ticket2.updated_at).getTime();
return date2 - date1;
const date1 = new Date(ticket1.updated_at).getTime();
const date2 = new Date(ticket2.updated_at).getTime();
return date2 - date1;
}
function sortTicketsByUnread(ticket1: Ticket, ticket2: Ticket) {
const isUnread1 = ticket1.user === ticket1.top_message.user_id;
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
return Number(isUnread2) - Number(isUnread1);
const isUnread1 = ticket1.user === ticket1.top_message.user_id;
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
return Number(isUnread2) - Number(isUnread1);
}

@ -2,80 +2,84 @@ import * as React from "react";
import { Box, Typography, Button } from "@mui/material";
import theme from "../../../../../theme";
export interface MWProps {
openModal: (type:number, num: number) => void
openModal: (type: number, num: number) => void;
}
const Contractor: React.FC<MWProps> = ({ openModal }) => {
return (
<React.Fragment>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main
}}>
Сокращатель ссылок
</Typography>
const Contractor: React.FC<MWProps> = ({ openModal }) => {
return (
<React.Fragment>
<Typography
variant="subtitle1"
sx={{
width: "90%",
height: "60px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
color: theme.palette.secondary.main,
}}
>
Сокращатель ссылок
</Typography>
<Box sx={{
marginTop: "35px",
display: "grid",
gridTemplateColumns: "repeat(2, 1fr)",
gridGap: "20px",
marginBottom: "120px",
}}>
<Button
variant = "contained"
onClick={ () => openModal(3, 1) }
sx={{
backgroundColor: theme.palette.menu.main,
padding: '11px 65px',
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main
}
}}>
Создать тариф <br /> на аналитику время
</Button>
<Button
variant = "contained"
onClick={ () => openModal(3, 1) }
sx={{
backgroundColor: theme.palette.menu.main,
padding: '11px 65px',
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main
}
}}>
Создать тариф <br /> на a/b тесты время
</Button>
<Button
variant = "contained"
sx={{
backgroundColor: theme.palette.menu.main,
padding: '11px 65px',
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main
}
}}>
Изменить тариф
</Button>
</Box>
</React.Fragment>
);
}
<Box
sx={{
marginTop: "35px",
display: "grid",
gridTemplateColumns: "repeat(2, 1fr)",
gridGap: "20px",
marginBottom: "120px",
}}
>
<Button
variant="contained"
onClick={() => openModal(3, 1)}
sx={{
backgroundColor: theme.palette.menu.main,
padding: "11px 65px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Создать тариф <br /> на аналитику время
</Button>
<Button
variant="contained"
onClick={() => openModal(3, 1)}
sx={{
backgroundColor: theme.palette.menu.main,
padding: "11px 65px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Создать тариф <br /> на a/b тесты время
</Button>
<Button
variant="contained"
sx={{
backgroundColor: theme.palette.menu.main,
padding: "11px 65px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
}}
>
Изменить тариф
</Button>
</Box>
</React.Fragment>
);
};
export default Contractor;
export default Contractor;

@ -1,354 +1,331 @@
import {
Typography,
Container,
Button,
Select,
MenuItem,
FormControl,
InputLabel,
useTheme,
Box, TextField,
Typography,
Container,
Button,
Select,
MenuItem,
FormControl,
InputLabel,
useTheme,
Box,
TextField,
} from "@mui/material";
import { enqueueSnackbar } from "notistack";
import { requestTariffs } from "@root/services/tariffs.service";
import { createTariff } from "@root/api/tariffs";
import {
findPrivilegeById,
usePrivilegeStore,
} from "@root/stores/privilegesStore";
import { findPrivilegeById, usePrivilegeStore } from "@root/stores/privilegesStore";
import { Privilege } from "@frontend/kitui";
import { currencyFormatter } from "@root/utils/currencyFormatter";
import { Formik, Field, Form, FormikHelpers } from "formik";
interface Values {
nameField: string,
descriptionField: string,
amountField: string,
customPriceField: string,
privilegeIdField: string,
orderField: number,
privilege: Privilege | null
nameField: string;
descriptionField: string;
amountField: string;
customPriceField: string;
privilegeIdField: string;
orderField: number;
privilege: Privilege | null;
}
export default function CreateTariff() {
const theme = useTheme();
const theme = useTheme();
const privileges = usePrivilegeStore((store) => store.privileges);
const privileges = usePrivilegeStore((store) => store.privileges);
const checkFulledFields = (values: Values) => {
const errors = {} as any;
const checkFulledFields = (values: Values) => {
const errors = {} as any;
if (values.nameField.length === 0) {
errors.nameField = "Пустое название тарифа"
}
if (values.amountField.length === 0) {
errors.amountField = "Пустое кол-во едениц привилегии"
}
if (values.privilegeIdField.length === 0) {
errors.privilegeIdField = "Не выбрана привилегия"
}
return errors;
if (values.nameField.length === 0) {
errors.nameField = "Пустое название тарифа";
}
if (values.amountField.length === 0) {
errors.amountField = "Пустое кол-во едениц привилегии";
}
if (values.privilegeIdField.length === 0) {
errors.privilegeIdField = "Не выбрана привилегия";
}
return errors;
};
};
const initialValues: Values = {
nameField: "",
descriptionField: "",
amountField: "",
customPriceField: "",
privilegeIdField: "",
orderField: 0,
privilege: null,
};
const initialValues: Values = {
nameField: "",
descriptionField: "",
amountField: "",
customPriceField: "",
privilegeIdField: "",
orderField: 0,
privilege: null
};
const createTariffBackend = async (values: Values, formikHelpers: FormikHelpers<Values>) => {
if (values.privilege !== null) {
const [, createdTariffError] = await createTariff({
name: values.nameField,
price: Number(values.customPriceField) * 100,
order: values.orderField,
isCustom: false,
description: values.descriptionField,
privileges: [
{
name: values.privilege.name,
privilegeId: values.privilege.privilegeId ?? "",
serviceKey: values.privilege.serviceKey,
description: values.privilege.description,
type: values.privilege.type,
value: values.privilege.value ?? "",
price: values.privilege.price,
amount: Number(values.amountField),
},
],
});
const createTariffBackend = async (
values: Values,
formikHelpers: FormikHelpers<Values>
) => {
if (values.privilege !== null) {
const [, createdTariffError] = await createTariff({
name: values.nameField,
price: Number(values.customPriceField) * 100,
order: values.orderField,
isCustom: false,
description: values.descriptionField,
privileges: [
{
name: values.privilege.name,
privilegeId: values.privilege.privilegeId ?? "",
serviceKey: values.privilege.serviceKey,
description: values.privilege.description,
type: values.privilege.type,
value: values.privilege.value ?? "",
price: values.privilege.price,
amount: Number(values.amountField),
},
],
});
if (createdTariffError) {
return enqueueSnackbar(createdTariffError);
}
if (createdTariffError) {
return enqueueSnackbar(createdTariffError);
}
enqueueSnackbar("Тариф создан");
enqueueSnackbar("Тариф создан");
await requestTariffs();
}
};
await requestTariffs();
}
};
// const createTariffFrontend = () => {
// if (checkFulledFields() && privilege !== null) {
// updateTariffStore({
// id: nanoid(5),
// name: nameField,
// amount: Number(amountField),
// isFront: true,
// privilegeId: privilege.privilegeId,
// customPricePerUnit: customPriceField.length !== 0 ? Number(customPriceField)*100: undefined,
// })
// }
// }
// const createTariffFrontend = () => {
// if (checkFulledFields() && privilege !== null) {
// updateTariffStore({
// id: nanoid(5),
// name: nameField,
// amount: Number(amountField),
// isFront: true,
// privilegeId: privilege.privilegeId,
// customPricePerUnit: customPriceField.length !== 0 ? Number(customPriceField)*100: undefined,
// })
// }
// }
return (
<Formik
initialValues={initialValues}
validate={checkFulledFields}
onSubmit={createTariffBackend}
>
{(props) => (
<Form style={{ width: "100%" }} >
<Container
sx={{
p: "20px",
border: "1px solid rgba(224, 224, 224, 1)",
borderRadius: "4px",
display: "flex",
flexDirection: "column",
gap: "12px",
}}
>
<Typography variant="h6" sx={{ textAlign: "center", mb: "16px" }}>
Создание тарифа
</Typography>
<FormControl
fullWidth
sx={{
height: "52px",
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
value={props.values.privilegeIdField}
label="Привилегия"
error={props.touched.privilegeIdField && !!props.errors.privilegeIdField}
onChange={(e) => {
console.log(e.target.value)
console.log(findPrivilegeById(e.target.value))
if (findPrivilegeById(e.target.value) === null) {
return enqueueSnackbar("Привилегия не найдена");
}
props.setFieldValue("privilegeIdField", e.target.value)
props.setFieldValue("privilege", findPrivilegeById(e.target.value))
}}
onBlur={props.handleBlur}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
border: "1px solid",
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{ sx: { pt: "12px" } }}
>
{privileges.map((privilege) => (
<MenuItem
data-cy={`select-option-${privilege.description}`}
key={privilege._id}
value={privilege._id}
sx={{ whiteSpace: "normal", wordBreak: "break-world" }}
>
{privilege.serviceKey}:{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
{props.values.privilege && (
<Box
sx={{
display: "flex",
flexDirection: "column",
}}
>
<Typography>
Имя: <span>{props.values.privilege.name}</span>
</Typography>
<Typography>
Сервис: <span>{props.values.privilege.serviceKey}</span>
</Typography>
<Typography>
Единица: <span>{props.values.privilege.type}</span>
</Typography>
<Typography>
Стандартная цена за единицу: <span>{currencyFormatter.format(props.values.privilege.price / 100)}</span>
</Typography>
</Box>
)}
<Field
as={TextField}
id="tariff-name"
name="nameField"
variant="filled"
label="Название тарифа"
type="text"
error={props.touched.nameField && !!props.errors.nameField}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.nameField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<TextField
id="amountField"
name="amountField"
variant="filled"
onChange={(e) => {
props.setFieldValue("amountField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.amountField}
onBlur={props.handleBlur}
label="Кол-во единиц привилегии"
error={props.touched.amountField && !!props.errors.amountField}
helperText={
<Typography sx={{ fontSize: "12px", width: "200px" }}>
{props.errors.amountField}
</Typography>
}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<TextField
id="tariff-custom-price"
name="customPriceField"
variant="filled"
onChange={(e) => {
props.setFieldValue("customPriceField", e.target.value.replace(/[^\d]/g, ''))
}}
value={props.values.customPriceField}
onBlur={props.handleBlur}
label="Кастомная цена (не обязательно)"
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<TextField
id="tariff-dezcription"
name="descriptionField"
variant="filled"
onChange={(e) => {
props.setFieldValue("descriptionField", e.target.value)
}}
value={props.values.descriptionField}
onBlur={props.handleBlur}
label="Описание"
multiline={true}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<TextField
id="tariff-order"
name="orderField"
variant="filled"
onChange={(e) => {
props.setFieldValue("orderField", e.target.value)
}}
value={props.values.orderField}
onBlur={props.handleBlur}
label="порядковый номер"
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
}
}}
type={'number'}
InputLabelProps={{
style: {
color: theme.palette.secondary.main
}
}}
/>
<Button
className="btn_createTariffBackend"
type="submit"
disabled={props.isSubmitting}
>
Создать
</Button>
</Container>
</Form>
)}
</Formik>
);
return (
<Formik initialValues={initialValues} validate={checkFulledFields} onSubmit={createTariffBackend}>
{(props) => (
<Form style={{ width: "100%" }}>
<Container
sx={{
p: "20px",
border: "1px solid rgba(224, 224, 224, 1)",
borderRadius: "4px",
display: "flex",
flexDirection: "column",
gap: "12px",
}}
>
<Typography variant="h6" sx={{ textAlign: "center", mb: "16px" }}>
Создание тарифа
</Typography>
<FormControl
fullWidth
sx={{
height: "52px",
color: theme.palette.secondary.main,
"& .MuiInputLabel-outlined": {
color: theme.palette.secondary.main,
},
"& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
color: theme.palette.secondary.main,
},
}}
>
<InputLabel
id="privilege-select-label"
sx={{
color: theme.palette.secondary.main,
fontSize: "16px",
lineHeight: "19px",
}}
>
Привилегия
</InputLabel>
<Select
labelId="privilege-select-label"
id="privilege-select"
value={props.values.privilegeIdField}
label="Привилегия"
error={props.touched.privilegeIdField && !!props.errors.privilegeIdField}
onChange={(e) => {
console.log(e.target.value);
console.log(findPrivilegeById(e.target.value));
if (findPrivilegeById(e.target.value) === null) {
return enqueueSnackbar("Привилегия не найдена");
}
props.setFieldValue("privilegeIdField", e.target.value);
props.setFieldValue("privilege", findPrivilegeById(e.target.value));
}}
onBlur={props.handleBlur}
sx={{
color: theme.palette.secondary.main,
borderColor: theme.palette.secondary.main,
"&.Mui-focused .MuiOutlinedInput-notchedOutline": {
borderColor: theme.palette.secondary.main,
border: "1px solid",
},
".MuiSvgIcon-root ": {
fill: theme.palette.secondary.main,
},
}}
inputProps={{ sx: { pt: "12px" } }}
>
{privileges.map((privilege) => (
<MenuItem
data-cy={`select-option-${privilege.description}`}
key={privilege._id}
value={privilege._id}
sx={{ whiteSpace: "normal", wordBreak: "break-world" }}
>
{privilege.serviceKey}:{privilege.description}
</MenuItem>
))}
</Select>
</FormControl>
{props.values.privilege && (
<Box
sx={{
display: "flex",
flexDirection: "column",
}}
>
<Typography>
Имя: <span>{props.values.privilege.name}</span>
</Typography>
<Typography>
Сервис: <span>{props.values.privilege.serviceKey}</span>
</Typography>
<Typography>
Единица: <span>{props.values.privilege.type}</span>
</Typography>
<Typography>
Стандартная цена за единицу:{" "}
<span>{currencyFormatter.format(props.values.privilege.price / 100)}</span>
</Typography>
</Box>
)}
<Field
as={TextField}
id="tariff-name"
name="nameField"
variant="filled"
label="Название тарифа"
type="text"
error={props.touched.nameField && !!props.errors.nameField}
helperText={<Typography sx={{ fontSize: "12px", width: "200px" }}>{props.errors.nameField}</Typography>}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<TextField
id="amountField"
name="amountField"
variant="filled"
onChange={(e) => {
props.setFieldValue("amountField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.amountField}
onBlur={props.handleBlur}
label="Кол-во единиц привилегии"
error={props.touched.amountField && !!props.errors.amountField}
helperText={<Typography sx={{ fontSize: "12px", width: "200px" }}>{props.errors.amountField}</Typography>}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<TextField
id="tariff-custom-price"
name="customPriceField"
variant="filled"
onChange={(e) => {
props.setFieldValue("customPriceField", e.target.value.replace(/[^\d]/g, ""));
}}
value={props.values.customPriceField}
onBlur={props.handleBlur}
label="Кастомная цена (не обязательно)"
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<TextField
id="tariff-dezcription"
name="descriptionField"
variant="filled"
onChange={(e) => {
props.setFieldValue("descriptionField", e.target.value);
}}
value={props.values.descriptionField}
onBlur={props.handleBlur}
label="Описание"
multiline={true}
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<TextField
id="tariff-order"
name="orderField"
variant="filled"
onChange={(e) => {
props.setFieldValue("orderField", e.target.value);
}}
value={props.values.orderField}
onBlur={props.handleBlur}
label="порядковый номер"
InputProps={{
style: {
backgroundColor: theme.palette.content.main,
color: theme.palette.secondary.main,
},
}}
type={"number"}
InputLabelProps={{
style: {
color: theme.palette.secondary.main,
},
}}
/>
<Button className="btn_createTariffBackend" type="submit" disabled={props.isSubmitting}>
Создать
</Button>
</Container>
</Form>
)}
</Formik>
);
}

@ -1,32 +1,31 @@
import { Button, SxProps, Theme, useTheme } from "@mui/material";
import { MouseEventHandler, ReactNode } from "react";
interface Props {
onClick?: MouseEventHandler<HTMLButtonElement>;
children: ReactNode;
sx?: SxProps<Theme>;
onClick?: MouseEventHandler<HTMLButtonElement>;
children: ReactNode;
sx?: SxProps<Theme>;
}
export default function CustomButton({ onClick, children, sx }: Props) {
const theme = useTheme();
const theme = useTheme();
return (
<Button
variant="contained"
onClick={onClick}
sx={{
backgroundColor: theme.palette.menu.main,
padding: '11px 25px',
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main
},
...sx,
}}
>
{children}
</Button>
);
}
return (
<Button
variant="contained"
onClick={onClick}
sx={{
backgroundColor: theme.palette.menu.main,
padding: "11px 25px",
fontWeight: "normal",
fontSize: "17px",
"&:hover": {
backgroundColor: theme.palette.grayMedium.main,
},
...sx,
}}
>
{children}
</Button>
);
}

Some files were not shown because too many files have changed in this diff Show More