feat: price by category

This commit is contained in:
2024-09-27 04:41:18 +03:00
parent f30c55456c
commit c5f839d9ef
44 changed files with 1316 additions and 681 deletions

View File

@@ -52,6 +52,8 @@ export type { CreatePayRateRequest } from './models/CreatePayRateRequest';
export type { CreatePayRateResponse } from './models/CreatePayRateResponse';
export type { CreatePositionRequest } from './models/CreatePositionRequest';
export type { CreatePositionResponse } from './models/CreatePositionResponse';
export type { CreatePriceCategoryRequest } from './models/CreatePriceCategoryRequest';
export type { CreatePriceCategoryResponse } from './models/CreatePriceCategoryResponse';
export type { CreateServiceKitSchema } from './models/CreateServiceKitSchema';
export type { CreateServicesKitRequest } from './models/CreateServicesKitRequest';
export type { CreateServicesKitResponse } from './models/CreateServicesKitResponse';
@@ -120,6 +122,8 @@ export type { DeletePayRateRequest } from './models/DeletePayRateRequest';
export type { DeletePayRateResponse } from './models/DeletePayRateResponse';
export type { DeletePositionRequest } from './models/DeletePositionRequest';
export type { DeletePositionResponse } from './models/DeletePositionResponse';
export type { DeletePriceCategoryRequest } from './models/DeletePriceCategoryRequest';
export type { DeletePriceCategoryResponse } from './models/DeletePriceCategoryResponse';
export type { DeleteShippingWarehouseRequest } from './models/DeleteShippingWarehouseRequest';
export type { DeleteShippingWarehouseResponse } from './models/DeleteShippingWarehouseResponse';
export type { GetAllBarcodeTemplateAttributesResponse } from './models/GetAllBarcodeTemplateAttributesResponse';
@@ -129,6 +133,7 @@ export type { GetAllBaseMarketplacesResponse } from './models/GetAllBaseMarketpl
export type { GetAllPayRatesResponse } from './models/GetAllPayRatesResponse';
export type { GetAllPayrollSchemeResponse } from './models/GetAllPayrollSchemeResponse';
export type { GetAllPositionsResponse } from './models/GetAllPositionsResponse';
export type { GetAllPriceCategoriesResponse } from './models/GetAllPriceCategoriesResponse';
export type { GetAllRolesResponse } from './models/GetAllRolesResponse';
export type { GetAllServicesKitsResponse } from './models/GetAllServicesKitsResponse';
export type { GetAllShippingWarehousesResponse } from './models/GetAllShippingWarehousesResponse';
@@ -174,6 +179,7 @@ export type { ProductUpdateRequest } from './models/ProductUpdateRequest';
export type { ProductUpdateResponse } from './models/ProductUpdateResponse';
export type { ProductUploadImageResponse } from './models/ProductUploadImageResponse';
export type { RoleSchema } from './models/RoleSchema';
export type { ServiceCategoryPriceSchema } from './models/ServiceCategoryPriceSchema';
export type { ServiceCategorySchema } from './models/ServiceCategorySchema';
export type { ServiceCreateCategoryRequest } from './models/ServiceCreateCategoryRequest';
export type { ServiceCreateCategoryResponse } from './models/ServiceCreateCategoryResponse';
@@ -183,6 +189,7 @@ export type { ServiceDeleteRequest } from './models/ServiceDeleteRequest';
export type { ServiceDeleteResponse } from './models/ServiceDeleteResponse';
export type { ServiceGetAllCategoriesResponse } from './models/ServiceGetAllCategoriesResponse';
export type { ServiceGetAllResponse } from './models/ServiceGetAllResponse';
export type { ServicePriceCategorySchema } from './models/ServicePriceCategorySchema';
export type { ServicePriceRangeSchema } from './models/ServicePriceRangeSchema';
export type { ServiceSchema } from './models/ServiceSchema';
export type { ServiceUpdateRequest } from './models/ServiceUpdateRequest';
@@ -196,6 +203,8 @@ export type { UpdateMarketplaceRequest } from './models/UpdateMarketplaceRequest
export type { UpdateMarketplaceResponse } from './models/UpdateMarketplaceResponse';
export type { UpdatePayRateRequest } from './models/UpdatePayRateRequest';
export type { UpdatePayRateResponse } from './models/UpdatePayRateResponse';
export type { UpdatePriceCategoryRequest } from './models/UpdatePriceCategoryRequest';
export type { UpdatePriceCategoryResponse } from './models/UpdatePriceCategoryResponse';
export type { UpdateServiceKitSchema } from './models/UpdateServiceKitSchema';
export type { UpdateServicesKitRequest } from './models/UpdateServicesKitRequest';
export type { UpdateServicesKitResponse } from './models/UpdateServicesKitResponse';

View File

@@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type CreatePriceCategoryRequest = {
name: string;
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type CreatePriceCategoryResponse = {
ok: boolean;
message: string;
};

View File

@@ -3,6 +3,7 @@
/* tslint:disable */
/* eslint-disable */
import type { BaseMarketplaceSchema } from './BaseMarketplaceSchema';
import type { ServicePriceCategorySchema } from './ServicePriceCategorySchema';
export type DealQuickCreateRequest = {
name: string;
clientName: string;
@@ -10,5 +11,6 @@ export type DealQuickCreateRequest = {
acceptanceDate: string;
shippingWarehouse: string;
baseMarketplace: BaseMarketplaceSchema;
category?: (ServicePriceCategorySchema | null);
};

View File

@@ -7,6 +7,7 @@ import type { DealBillRequestSchema } from './DealBillRequestSchema';
import type { DealProductSchema } from './DealProductSchema';
import type { DealServiceSchema } from './DealServiceSchema';
import type { DealStatusHistorySchema } from './DealStatusHistorySchema';
import type { ServicePriceCategorySchema } from './ServicePriceCategorySchema';
import type { ShippingWarehouseSchema } from './ShippingWarehouseSchema';
export type DealSchema = {
id: number;
@@ -24,5 +25,6 @@ export type DealSchema = {
comment: string;
shippingWarehouse?: (ShippingWarehouseSchema | string | null);
billRequest?: (DealBillRequestSchema | null);
category?: (ServicePriceCategorySchema | null);
};

View File

@@ -0,0 +1,8 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type DeletePriceCategoryRequest = {
id: number;
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type DeletePriceCategoryResponse = {
ok: boolean;
message: string;
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ServicePriceCategorySchema } from './ServicePriceCategorySchema';
export type GetAllPriceCategoriesResponse = {
priceCategories: Array<ServicePriceCategorySchema>;
};

View File

@@ -0,0 +1,10 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ServicePriceCategorySchema } from './ServicePriceCategorySchema';
export type ServiceCategoryPriceSchema = {
category: ServicePriceCategorySchema;
price: number;
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ServicePriceCategorySchema = {
id: number;
name: string;
};

View File

@@ -2,6 +2,7 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ServiceCategoryPriceSchema } from './ServiceCategoryPriceSchema';
import type { ServiceCategorySchema } from './ServiceCategorySchema';
import type { ServicePriceRangeSchema } from './ServicePriceRangeSchema';
export type ServiceSchema = {
@@ -11,6 +12,7 @@ export type ServiceSchema = {
price: number;
serviceType: number;
priceRanges: Array<ServicePriceRangeSchema>;
categoryPrices: Array<ServiceCategoryPriceSchema>;
cost: (number | null);
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UpdatePriceCategoryRequest = {
id: number;
name: string;
};

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UpdatePriceCategoryResponse = {
ok: boolean;
message: string;
};

View File

@@ -305,6 +305,27 @@ export class DealService {
},
});
}
/**
* Get Detailed Deal Document
* @returns any Successful Response
* @throws ApiError
*/
public static getDealDocumentDetailed({
dealId,
}: {
dealId: number,
}): CancelablePromise<any> {
return __request(OpenAPI, {
method: 'GET',
url: '/deal/detailedDocument/{deal_id}',
path: {
'deal_id': dealId,
},
errors: {
422: `Validation Error`,
},
});
}
/**
* Services Add
* @returns DealAddServicesResponse Successful Response

View File

@@ -3,8 +3,13 @@
/* tslint:disable */
/* eslint-disable */
import type { BaseEnumListSchema } from '../models/BaseEnumListSchema';
import type { CreatePriceCategoryRequest } from '../models/CreatePriceCategoryRequest';
import type { CreatePriceCategoryResponse } from '../models/CreatePriceCategoryResponse';
import type { CreateServicesKitRequest } from '../models/CreateServicesKitRequest';
import type { CreateServicesKitResponse } from '../models/CreateServicesKitResponse';
import type { DeletePriceCategoryRequest } from '../models/DeletePriceCategoryRequest';
import type { DeletePriceCategoryResponse } from '../models/DeletePriceCategoryResponse';
import type { GetAllPriceCategoriesResponse } from '../models/GetAllPriceCategoriesResponse';
import type { GetAllServicesKitsResponse } from '../models/GetAllServicesKitsResponse';
import type { ServiceCreateCategoryRequest } from '../models/ServiceCreateCategoryRequest';
import type { ServiceCreateCategoryResponse } from '../models/ServiceCreateCategoryResponse';
@@ -16,6 +21,8 @@ import type { ServiceGetAllCategoriesResponse } from '../models/ServiceGetAllCat
import type { ServiceGetAllResponse } from '../models/ServiceGetAllResponse';
import type { ServiceUpdateRequest } from '../models/ServiceUpdateRequest';
import type { ServiceUpdateResponse } from '../models/ServiceUpdateResponse';
import type { UpdatePriceCategoryRequest } from '../models/UpdatePriceCategoryRequest';
import type { UpdatePriceCategoryResponse } from '../models/UpdatePriceCategoryResponse';
import type { UpdateServicesKitRequest } from '../models/UpdateServicesKitRequest';
import type { UpdateServicesKitResponse } from '../models/UpdateServicesKitResponse';
import type { CancelablePromise } from '../core/CancelablePromise';
@@ -186,4 +193,75 @@ export class ServiceService {
},
});
}
/**
* Get All Price Categories
* @returns GetAllPriceCategoriesResponse Successful Response
* @throws ApiError
*/
public static getAllPriceCategories(): CancelablePromise<GetAllPriceCategoriesResponse> {
return __request(OpenAPI, {
method: 'GET',
url: '/service/price-categories/get-all',
});
}
/**
* Create Price Category
* @returns CreatePriceCategoryResponse Successful Response
* @throws ApiError
*/
public static createPriceCategory({
requestBody,
}: {
requestBody: CreatePriceCategoryRequest,
}): CancelablePromise<CreatePriceCategoryResponse> {
return __request(OpenAPI, {
method: 'POST',
url: '/service/price-categories/create',
body: requestBody,
mediaType: 'application/json',
errors: {
422: `Validation Error`,
},
});
}
/**
* Update Price Category
* @returns UpdatePriceCategoryResponse Successful Response
* @throws ApiError
*/
public static updatePriceCategory({
requestBody,
}: {
requestBody: UpdatePriceCategoryRequest,
}): CancelablePromise<UpdatePriceCategoryResponse> {
return __request(OpenAPI, {
method: 'POST',
url: '/service/price-categories/update',
body: requestBody,
mediaType: 'application/json',
errors: {
422: `Validation Error`,
},
});
}
/**
* Delete Price Category
* @returns DeletePriceCategoryResponse Successful Response
* @throws ApiError
*/
public static deletePriceCategory({
requestBody,
}: {
requestBody: DeletePriceCategoryRequest,
}): CancelablePromise<DeletePriceCategoryResponse> {
return __request(OpenAPI, {
method: 'POST',
url: '/service/price-categories/delete',
body: requestBody,
mediaType: 'application/json',
errors: {
422: `Validation Error`,
},
});
}
}

View File

@@ -2,12 +2,13 @@ import {Button, rem, Textarea, TextInput} from "@mantine/core";
import { QuickDeal } from "../../../types/QuickDeal.ts";
import { FC } from "react";
import { useForm } from "@mantine/form";
import styles from './CreateDealForm.module.css';
import styles from "./CreateDealForm.module.css";
import ClientAutocomplete from "../../Selects/ClientAutocomplete/ClientAutocomplete.tsx";
import { DateTimePicker } from "@mantine/dates";
import ShippingWarehouseAutocomplete
from "../../Selects/ShippingWarehouseAutocomplete/ShippingWarehouseAutocomplete.tsx";
import BaseMarketplaceSelect from "../../Selects/BaseMarketplaceSelect/BaseMarketplaceSelect.tsx";
import ServicePriceCategorySelect from "../../Selects/ServicePriceCategorySelect/ServicePriceCategorySelect.tsx";
type Props = {
onSubmit: (quickDeal: QuickDeal) => void
@@ -16,84 +17,92 @@ type Props = {
const CreateDealFrom: FC<Props> = ({ onSubmit, onCancel }) => {
const form = useForm<QuickDeal>({
initialValues: {
name: '',
clientName: '',
clientAddress: '',
comment: '',
name: "",
clientName: "",
clientAddress: "",
comment: "",
acceptanceDate: new Date(),
shippingWarehouse: '',
shippingWarehouse: "",
baseMarketplace: {
key: "",
iconUrl: "",
name: ""
}
}
name: "",
},
},
});
return (
<form
style={{width: '100%'}}
style={{ width: "100%" }}
onSubmit={form.onSubmit((values) => onSubmit(values))}
>
<div style={{
display: 'flex',
flexDirection: 'column',
width: '100%',
display: "flex",
flexDirection: "column",
width: "100%",
gap: rem(10),
padding: rem(10)
padding: rem(10),
}}>
<div className={styles['inputs']}>
<div className={styles["inputs"]}>
<TextInput
placeholder={'Название сделки'}
{...form.getInputProps('name')}
placeholder={"Название сделки"}
{...form.getInputProps("name")}
/>
</div>
<div className={styles['inputs']}>
<div className={styles["inputs"]}>
<ClientAutocomplete
nameRestProps={form.getInputProps('clientName')}
nameRestProps={form.getInputProps("clientName")}
/>
</div>
<div className={styles['inputs']}>
<div className={styles["inputs"]}>
<BaseMarketplaceSelect
rightSection={<></>}
placeholder={"Базовый маркетплейс"}
{...form.getInputProps("baseMarketplace")}
/>
<ShippingWarehouseAutocomplete
{...form.getInputProps('shippingWarehouse')}
placeholder={'Склад отгрузки'}
{...form.getInputProps("shippingWarehouse")}
placeholder={"Склад отгрузки"}
/>
</div>
<div className={styles["inputs"]}>
<ServicePriceCategorySelect
rightSection={<></>}
placeholder={"Выберите категорию"}
{...form.getInputProps("category")}
/>
</div>
<div className={styles['inputs']}>
<div className={styles["inputs"]}>
<Textarea
autosize
placeholder={'Комментарий'}
placeholder={"Комментарий"}
minRows={2}
maxRows={4}
{...form.getInputProps('comment')}
{...form.getInputProps("comment")}
/>
</div>
<div className={styles['inputs']}>
<div className={styles["inputs"]}>
<DateTimePicker
placeholder={'Дата приемки'}
{...form.getInputProps('acceptanceDate')}
placeholder={"Дата приемки"}
{...form.getInputProps("acceptanceDate")}
/>
</div>
<div className={styles['buttons']}>
<div className={styles["buttons"]}>
<Button
type={'submit'}
type={"submit"}
>Добавить</Button>
<Button
variant={'outline'}
variant={"outline"}
onClick={() => onCancel()}
>Отменить</Button>
</div>
</div>
</form>
)
}
);
};
export default CreateDealFrom;

View File

@@ -0,0 +1,17 @@
import ObjectSelect, { ObjectSelectProps } from "../../ObjectSelect/ObjectSelect.tsx";
import { ServicePriceCategorySchema } from "../../../client";
import useServicePriceCategoriesList from "../../../pages/ServicesPage/hooks/useServicePriceCategoriesList.tsx";
type Props = Omit<ObjectSelectProps<ServicePriceCategorySchema>, "data">
const ServicePriceCategorySelect = (props: Props) => {
const { objects } = useServicePriceCategoriesList();
return (
<ObjectSelect
{...props}
data={objects}
/>
);
};
export default ServicePriceCategorySelect;

View File

@@ -1,11 +1,11 @@
import { ObjectSelectProps } from "../ObjectSelect/ObjectSelect.tsx";
import {ServiceSchema} from "../../client";
import { ServicePriceCategorySchema, ServiceSchema } from "../../client";
import { Flex, FlexProps, NumberInput, NumberInputProps, rem } from "@mantine/core";
import { FC, useEffect, useRef, useState } from "react";
import ServiceSelectNew from "../Selects/ServiceSelectNew/ServiceSelectNew.tsx";
import { ServiceType } from "../../shared/enums/ServiceType.ts";
type ServiceProps = Omit<ObjectSelectProps<ServiceSchema>, 'data'>;
type ServiceProps = Omit<ObjectSelectProps<ServiceSchema>, "data">;
type PriceProps = NumberInputProps;
type Props = {
@@ -15,6 +15,7 @@ type Props = {
containerProps: FlexProps,
filterType?: ServiceType,
lockOnEdit?: boolean
category?: ServicePriceCategorySchema
}
const ServiceWithPriceInput: FC<Props> = ({
serviceProps,
@@ -22,10 +23,11 @@ const ServiceWithPriceInput: FC<Props> = ({
quantity,
containerProps,
filterType = ServiceType.PRODUCT_SERVICE,
lockOnEdit = true
lockOnEdit = true,
category,
}) => {
const [price, setPrice] = useState<number | undefined>(
typeof priceProps.value === 'number' ? priceProps.value : undefined);
typeof priceProps.value === "number" ? priceProps.value : undefined);
const [service, setService] = useState<ServiceSchema | undefined>(serviceProps.value);
const isFirstRender = useRef(true);
const setPriceBasedOnQuantity = (): boolean => {
@@ -35,29 +37,40 @@ const ServiceWithPriceInput: FC<Props> = ({
setPrice(range.price);
return true;
}
};
const setPriceBasedOnCategory = () => {
if (!category || !service) return false;
const categoryPrice = service.categoryPrices.find(categoryPrice => categoryPrice.category.id === category.id);
if (!categoryPrice) return false;
setPrice(categoryPrice.price);
return true;
};
const setPriceBasedOnService = () => {
if (!service) return;
// if category is set, we should not set price based on service
if (setPriceBasedOnCategory()) return;
if (setPriceBasedOnQuantity()) return;
setPrice(service.price);
}
};
const onServiceManualChange = (service: ServiceSchema) => {
setService(service);
}
};
const onPriceManualChange = (value: number | string) => {
if (typeof value !== 'number') return;
if (typeof value !== "number") return;
setPrice(value);
}
};
useEffect(() => {
if (isFirstRender.current && lockOnEdit) return;
// we need to set price based on quantity only if category is not set, because category has higher priority
if (category) return;
setPriceBasedOnQuantity();
}, [quantity]);
useEffect(() => {
if (isFirstRender.current && lockOnEdit) return;
if (!priceProps.onChange || typeof price === 'undefined') return;
if (!priceProps.onChange || typeof price === "undefined") return;
priceProps.onChange(price);
}, [price]);
@@ -97,7 +110,7 @@ const ServiceWithPriceInput: FC<Props> = ({
/>
</Flex>
)
}
);
};
export default ServiceWithPriceInput;

View File

@@ -1,19 +1,19 @@
import ReactDOM from 'react-dom/client'
import {RouterProvider, createRouter} from '@tanstack/react-router'
import {routeTree} from './routeTree.gen'
import ReactDOM from "react-dom/client";
import { RouterProvider, createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Provider } from "react-redux";
import { store } from "./redux/store.ts";
import '@mantine/core/styles.css';
import '@mantine/notifications/styles.css';
import '@mantine/dates/styles.css';
import 'mantine-react-table/styles.css';
import "@mantine/core/styles.css";
import "@mantine/notifications/styles.css";
import "@mantine/dates/styles.css";
import "mantine-react-table/styles.css";
import 'dayjs/locale/ru';
import "dayjs/locale/ru";
import './main.css';
import "./main.css";
import { Notifications } from "@mantine/notifications";
import { ModalsProvider } from "@mantine/modals";
import { OpenAPI } from "./client";
@@ -22,14 +22,14 @@ import {modals} from "./modals/modals.ts";
import TasksProvider from "./providers/TasksProvider/TasksProvider.tsx";
// Configuring router
const router = createRouter({routeTree})
declare module '@tanstack/react-router' {
const router = createRouter({ routeTree });
declare module "@tanstack/react-router" {
interface Register {
router: typeof router
router: typeof router;
}
}
declare module '@mantine/modals' {
declare module "@mantine/modals" {
export interface MantineModalsOverride {
modals: typeof modals;
}
@@ -39,14 +39,14 @@ declare module '@mantine/modals' {
const queryClient = new QueryClient();
// Configuring OpenAPI
OpenAPI.BASE = import.meta.env.VITE_API_URL
OpenAPI.TOKEN = JSON.parse(localStorage.getItem('authState') || "{}")['accessToken'];
ReactDOM.createRoot(document.getElementById('root')!).render(
OpenAPI.BASE = import.meta.env.VITE_API_URL;
OpenAPI.TOKEN = JSON.parse(localStorage.getItem("authState") || "{}")["accessToken"];
ReactDOM.createRoot(document.getElementById("root")!).render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<MantineProvider defaultColorScheme={"dark"}>
<ModalsProvider modals={modals}>
<DatesProvider settings={{locale: 'ru'}}>
<ModalsProvider labels={{ confirm: "Да", cancel: "Нет" }} modals={modals}>
<DatesProvider settings={{ locale: "ru" }}>
<TasksProvider>
<RouterProvider router={router} />
@@ -57,5 +57,5 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
</ModalsProvider>
</MantineProvider>
</QueryClientProvider>
</Provider>
)
</Provider>,
);

View File

@@ -21,6 +21,7 @@ import ServicesKitSelectModal from "./ServicesKitSelectModal/ServicesKitSelectMo
import SelectDealProductsModal from "../pages/LeadsPage/modals/SelectDealProductsModal.tsx";
import ShippingWarehouseForm from "../pages/ShippingWarehousesPage/modals/ShippingWarehouseForm.tsx";
import MarketplaceFormModal from "../pages/MarketplacesPage/modals/MarketplaceFormModal/MarketplaceFormModal.tsx";
import ServicePriceCategoryForm from "../pages/ServicesPage/modals/ServicePriceCategoryForm.tsx";
export const modals = {
enterDeadline: EnterDeadlineModal,
@@ -44,5 +45,6 @@ export const modals = {
servicesKitSelectModal: ServicesKitSelectModal,
selectDealProductsModal: SelectDealProductsModal,
shippingWarehouseForm: ShippingWarehouseForm,
marketplaceFormModal: MarketplaceFormModal
}
marketplaceFormModal: MarketplaceFormModal,
servicePriceCategoryForm: ServicePriceCategoryForm,
};

View File

@@ -24,8 +24,8 @@ const useDealServicesTableState = () => {
DealService.updateDealService({
requestBody: {
dealId: selectedDeal.id,
service
}
service,
},
}).then(async ({ ok, message }) => {
if (!ok) {
@@ -33,9 +33,9 @@ const useDealServicesTableState = () => {
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
}
.then(setSelectedDeal);
});
};
const onServiceDelete = (service: DealServiceSchema) => {
if (!selectedDeal) return;
modals.openConfirmModal({
@@ -56,23 +56,23 @@ const useDealServicesTableState = () => {
DealService.deleteDealService({
requestBody: {
dealId: selectedDeal.id,
serviceId: service.service.id
}
serviceId: service.service.id,
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
.then(setSelectedDeal);
});
},
labels: {
cancel: "Отмена",
confirm: "Удалить"
}
})
}
confirm: "Удалить",
},
});
};
const onServiceCreate = (service: DealServiceSchema) => {
if (!selectedDeal) return;
DealService.addDealService({
@@ -80,17 +80,17 @@ const useDealServicesTableState = () => {
dealId: selectedDeal.id,
serviceId: service.service.id,
quantity: service.quantity,
price: service.price
}
price: service.price,
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
}
.then(setSelectedDeal);
});
};
const onsServiceMultipleDelete = (items: DealServiceSchema[]) => {
if (!selectedDeal) return;
modals.openConfirmModal({
@@ -106,23 +106,23 @@ const useDealServicesTableState = () => {
DealService.deleteMultipleDealServices({
requestBody: {
dealId: selectedDeal.id,
serviceIds: items.map(item => item.service.id)
}
serviceIds: items.map(item => item.service.id),
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
.then(setSelectedDeal);
});
},
labels: {
cancel: "Отмена",
confirm: "Удалить"
}
})
}
confirm: "Удалить",
},
});
};
return {
onServiceUpdate,
@@ -130,9 +130,9 @@ const useDealServicesTableState = () => {
onServiceCreate,
onsServiceMultipleDelete,
tableRef,
services: selectedDeal?.services || []
}
}
services: selectedDeal?.services || [],
};
};
const DealEditDrawerServicesTable = () => {
const {
services,
@@ -140,7 +140,7 @@ const DealEditDrawerServicesTable = () => {
onServiceCreate,
onServiceUpdate,
onServiceDelete,
onsServiceMultipleDelete
onsServiceMultipleDelete,
} = useDealServicesTableState();
return (<DealServicesTable
@@ -150,8 +150,8 @@ const DealEditDrawerServicesTable = () => {
onDelete={onServiceDelete}
onCreate={onServiceCreate}
onMultipleDelete={onsServiceMultipleDelete}
/>)
}
/>);
};
const useDealProductTableState = () => {
const { selectedDeal, setSelectedDeal } = useDealPageContext();
@@ -161,15 +161,15 @@ const useDealProductTableState = () => {
DealService.updateDealProduct({
requestBody: {
dealId: selectedDeal.id,
product: product
}
product: product,
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message });
if (!ok) return;
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
}
.then(setSelectedDeal);
});
};
const onProductDelete = (product: DealProductSchema) => {
if (!selectedDeal) return;
modals.openConfirmModal({
@@ -190,39 +190,39 @@ const useDealProductTableState = () => {
DealService.deleteDealProduct({
requestBody: {
dealId: selectedDeal.id,
productId: product.product.id
}
productId: product.product.id,
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
.then(setSelectedDeal);
});
},
labels: {
cancel: "Отмена",
confirm: "Удалить"
}
})
}
confirm: "Удалить",
},
});
};
const onProductCreate = (product: DealProductSchema) => {
if (!selectedDeal) return;
DealService.addDealProduct({
requestBody: {
dealId: selectedDeal.id,
product: product
}
product: product,
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
}
.then(setSelectedDeal);
});
};
const onProductMultipleDelete = (items: DealProductSchema[]) => {
if (!selectedDeal) return;
modals.openConfirmModal({
@@ -238,32 +238,32 @@ const useDealProductTableState = () => {
DealService.deleteMultipleDealProducts({
requestBody: {
dealId: selectedDeal.id,
productIds: items.map(item => item.product.id)
}
productIds: items.map(item => item.product.id),
},
}).then(async ({ ok, message }) => {
if (!ok) {
notifications.guess(ok, { message });
return;
}
await DealService.getDealById({ dealId: selectedDeal.id })
.then(setSelectedDeal)
})
.then(setSelectedDeal);
});
},
labels: {
cancel: "Отмена",
confirm: "Удалить"
}
})
}
confirm: "Удалить",
},
});
};
return {
clientId: selectedDeal?.clientId || -1,
products: selectedDeal?.products || [],
onProductUpdate,
onProductDelete,
onProductCreate,
onProductMultipleDelete
}
}
onProductMultipleDelete,
};
};
const DealEditDrawerProductsTable = () => {
const {
products,
@@ -283,38 +283,38 @@ const DealEditDrawerProductsTable = () => {
onCreate={onProductCreate}
/>
)
}
);
};
const useDealStatusChangeState = () => {
const { selectedDeal } = useDealPageContext();
return {
statusHistory: selectedDeal?.statusHistory || []
}
}
statusHistory: selectedDeal?.statusHistory || [],
};
};
const DealEditDrawerStatusChangeTable = () => {
const { statusHistory } = useDealStatusChangeState();
return (
<DealStatusChangeTable
items={statusHistory}
/>)
}
/>);
};
const useDealEditDrawerState = () => {
const { selectedDeal, setSelectedDeal } = useDealPageContext();
return {
isVisible: selectedDeal !== undefined,
onClose: () => setSelectedDeal(undefined)
}
}
onClose: () => setSelectedDeal(undefined),
};
};
const DealEditDrawer: FC = () => {
const { isVisible, onClose } = useDealEditDrawerState();
const queryClient = useQueryClient();
useEffect(() => {
if (isVisible) return;
queryClient.invalidateQueries({queryKey: ["getDealSummaries"]})
queryClient.invalidateQueries({ queryKey: ["getDealSummaries"] });
}, [isVisible]);
return (
<Drawer
@@ -324,16 +324,23 @@ const DealEditDrawer: FC = () => {
removeScrollProps={{ allowPinchZoom: true }}
withCloseButton={false}
opened={isVisible}
styles={{body: {height: '100%'}}}
styles={{
body: {
height: "100%",
display: "flex",
flexDirection: "column", gap: rem(10),
},
}}
>
<Tabs
defaultValue={"general"}
h={'100%'}
flex={1}
variant={"outline"}
orientation={"vertical"}
keepMounted={false}
>
<Tabs.List
>
<Tabs.Tab value={"general"} leftSection={<IconSettings />}>
@@ -398,6 +405,6 @@ const DealEditDrawer: FC = () => {
</Tabs>
</Drawer>
);
}
};
export default DealEditDrawer;

View File

@@ -103,7 +103,7 @@ const Content: FC<Props> = ({ deal }) => {
};
return (
<form onSubmit={form.onSubmit((values) => handleSubmit(values))}>
<Flex direction={"column"}>
<Flex direction={"column"} justify={"space-between"} h={"100%"}>
<Fieldset legend={`Общие параметры [ID: ${deal.id}]`}>
<Flex direction={"column"} gap={rem(10)}>
<TextInput
@@ -122,6 +122,15 @@ const Content: FC<Props> = ({ deal }) => {
placeholder={"Текущий статус"}
label={"Текущий статус"}
value={DealStatusDictionary[deal.currentStatus as DealStatus]} />
{deal.category && (
<TextInput
disabled
placeholder={"Категория"}
label={"Категория"}
value={deal.category.name}
/>
)}
<Textarea
label={"Коментарий к сделке"}
placeholder={"Введите коментарий к сделке"}
@@ -141,34 +150,6 @@ const Content: FC<Props> = ({ deal }) => {
/>
</Flex>
</Fieldset>
<Fieldset legend={"Клиент"}>
<TextInput
disabled
placeholder={"Название"}
label={"Название"}
value={deal.client.name}
/>
<TextInput
placeholder={"Введите телефон"}
label={"Телефон клиента"}
{...form.getInputProps("client.details.phoneNumber")}
/>
<TextInput
placeholder={"Введите email"}
label={"Email"}
{...form.getInputProps("client.details.email")}
/>
<TextInput
placeholder={"Введите телеграм"}
label={"Телеграм"}
{...form.getInputProps("client.details.telegram")}
/>
<TextInput
placeholder={"Введите ИНН"}
label={"ИНН"}
{...form.getInputProps("client.details.inn")}
/>
</Fieldset>
<Flex mt={"md"} gap={rem(10)} align={"center"} justify={"flex-end"}>
<Flex align={"center"} gap={rem(10)} justify={"center"}>
@@ -199,10 +180,7 @@ const Content: FC<Props> = ({ deal }) => {
:
<ButtonCopyControlled
onCopyClick={() => {
// get current datetime for filename, replaced dots with _
const date = getCurrentDateTimeForFilename();
FileSaver.saveAs(`${import.meta.env.VITE_API_URL}/deal/document/${deal.id}`,
`bill_${deal.id}_${date}.pdf`);
}}

View File

@@ -2,11 +2,9 @@ import {ContextModalProps} from "@mantine/modals";
import BaseFormModal, { CreateEditFormProps } from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import { DealProductSchema, DealProductServiceSchema } from "../../../client";
import { useForm } from "@mantine/form";
import {Fieldset, NumberInput} from "@mantine/core";
import { NumberInput } from "@mantine/core";
import ProductSelect from "../../../components/ProductSelect/ProductSelect.tsx";
import DealProductServiceTable from "../components/DealProductsTable/DealProductServiceTable.tsx";
import { omit } from "lodash";
import {BaseFormInputProps} from "../../../types/utils.ts";
type RestProps = {
clientId: number;
@@ -65,13 +63,13 @@ const AddDealProductModal = ({
min={1}
{...form.getInputProps('quantity')}
/>
<Fieldset legend={'Услуги'}>
<DealProductServiceTable
quantity={form.values.quantity || 1}
{...form.getInputProps('services') as
BaseFormInputProps<DealProductServiceSchema[]>}
/>
</Fieldset>
{/*<Fieldset legend={'Услуги'}>*/}
{/* <DealProductServiceTable*/}
{/* quantity={form.values.quantity || 1}*/}
{/* {...form.getInputProps('services') as*/}
{/* BaseFormInputProps<DealProductServiceSchema[]>}*/}
{/* />*/}
{/*</Fieldset>*/}
</>

View File

@@ -1,6 +1,6 @@
import {ContextModalProps} from "@mantine/modals";
import BaseFormModal, {CreateEditFormProps} from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {DealServiceSchema} from "../../../client";
import { DealServiceSchema, ServicePriceCategorySchema } from "../../../client";
import {useForm} from "@mantine/form";
import {ComboboxItem, ComboboxItemGroup, NumberInput, OptionsFilter} from "@mantine/core";
import ServiceWithPriceInput from "../../../components/ServiceWithPriceInput/ServiceWithPriceInput.tsx";
@@ -10,6 +10,7 @@ import {RootState} from "../../../redux/store.ts";
type RestProps = {
serviceIds?: number[];
category?: ServicePriceCategorySchema;
}
type Props = CreateEditFormProps<Partial<DealServiceSchema>> & RestProps;
const AddDealServiceModal = ({
@@ -18,7 +19,7 @@ const AddDealServiceModal = ({
innerProps
}: ContextModalProps<Props>) => {
const authState = useSelector((state: RootState) => state.auth);
console.log(innerProps.category)
const isEditing = 'element' in innerProps;
const form = useForm<Partial<DealServiceSchema>>({
initialValues: isEditing ? innerProps.element : {
@@ -54,6 +55,7 @@ const AddDealServiceModal = ({
<BaseFormModal.Body>
<>
<ServiceWithPriceInput
category={innerProps.category}
serviceProps={{
...form.getInputProps('service'),
label: "Услуга",

View File

@@ -1,5 +1,5 @@
import BaseFormModal, { CreateEditFormProps } from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {DealProductServiceSchema, ServiceSchema} from "../../../client";
import { DealProductServiceSchema, ServicePriceCategorySchema, ServiceSchema } from "../../../client";
import { ContextModalProps } from "@mantine/modals";
import { useForm, UseFormReturnType } from "@mantine/form";
import { isNil, isNumber } from "lodash";
@@ -12,31 +12,32 @@ import {RootState} from "../../../redux/store.ts";
type RestProps = {
quantity: number;
serviceIds: number[];
category?: ServicePriceCategorySchema;
}
type Props = CreateEditFormProps<DealProductServiceSchema> & RestProps;
const ProductServiceFormModal = ({
context,
id, innerProps
id, innerProps,
}: ContextModalProps<Props>) => {
const authState = useSelector((state: RootState) => state.auth);
const isEditing = 'onChange' in innerProps;
const isEditing = "onChange" in innerProps;
const initialValues: Partial<DealProductServiceSchema> = isEditing ? innerProps.element : {
service: undefined,
price: undefined,
employees: []
}
employees: [],
};
const form = useForm<Partial<DealProductServiceSchema>>({
initialValues,
validate: {
service: (service?: ServiceSchema) => isNil(service) || service.id < 0 ? 'Укажите услугу' : null,
price: (price?: number) => !isNumber(price) || price < 0 ? 'Укажите цену' : null
}
})
service: (service?: ServiceSchema) => isNil(service) || service.id < 0 ? "Укажите услугу" : null,
price: (price?: number) => !isNumber(price) || price < 0 ? "Укажите цену" : null,
},
});
const onClose = () => {
context.closeContextModal(id);
}
};
return (
<BaseFormModal
{...innerProps}
@@ -49,25 +50,26 @@ const ProductServiceFormModal = ({
<Flex w={"100%"}>
<ServiceWithPriceInput
category={innerProps.category}
serviceProps={{
...form.getInputProps('service'),
...form.getInputProps("service"),
label: "Услуга",
placeholder: "Выберите услугу",
disabled: isEditing,
filterBy: (item) => !innerProps.serviceIds.includes(item.id) || isEditing,
style: {width: "100%"}
style: { width: "100%" },
}}
priceProps={{
...form.getInputProps('price'),
...form.getInputProps("price"),
label: "Цена",
placeholder: "Введите цену",
style: { width: "100%" },
disabled: authState.isGuest
disabled: authState.isGuest,
}}
filterType={ServiceType.PRODUCT_SERVICE}
containerProps={{
direction: "column",
style: {width: "100%"}
style: { width: "100%" },
}}
lockOnEdit={isEditing}
@@ -79,6 +81,6 @@ const ProductServiceFormModal = ({
</BaseFormModal.Body>
</BaseFormModal>
)
}
);
};
export default ProductServiceFormModal;

View File

@@ -27,68 +27,70 @@ const DealServicesTable: FC<Props> = ({items, onDelete, onCreate, onChange, onKi
const onDeleteClick = (item: DealServiceSchema) => {
if (!onDelete) return;
onDelete(item);
}
};
const onCreateClick = () => {
if (!onCreate) return;
console.log("228")
const serviceIds = items.map(service => service.service.id);
modals.openContextModal({
modal: "addDealService",
innerProps: {
onCreate: onCreate,
serviceIds
serviceIds,
category: dealState.deal?.category || undefined,
},
withCloseButton: false
})
}
withCloseButton: false,
});
};
const onQuantityChange = (item: DealServiceSchema, quantity: number) => {
if (!onChange) return;
onChange({
...item,
quantity
})
}
quantity,
});
};
const onPriceChange = (item: DealServiceSchema, price: number) => {
if (!onChange) return;
onChange({
...item,
price
})
}
price,
});
};
const onEmployeeClick = (item: DealServiceSchema) => {
if (!onChange) return;
setCurrentService(item);
setEmployeesModalVisible(true);
}
};
const onEmployeeModalClose = () => {
setEmployeesModalVisible(false);
setCurrentService(undefined);
}
};
const getCurrentEmployees = (): UserSchema[] => {
if (!currentService) return [];
const item = items.find(i => i.service.id === currentService.service.id)
const item = items.find(i => i.service.id === currentService.service.id);
if (!item) return [];
return item.employees;
}
};
const onEmployeesChange = (items: UserSchema[]) => {
if (!currentService || !onChange) return;
onChange({
...currentService,
employees: items
employees: items,
});
}
};
const onAddKitClick = () => {
if (!onKitAdd) return;
modals.openContextModal({
modal: "servicesKitSelectModal",
innerProps: {
onSelect: onKitAdd,
serviceType: ServiceType.DEAL_SERVICE
serviceType: ServiceType.DEAL_SERVICE,
},
withCloseButton: false
withCloseButton: false,
})
}
});
};
return (
<>
<Flex
@@ -196,6 +198,6 @@ const DealServicesTable: FC<Props> = ({items, onDelete, onCreate, onChange, onKi
</Modal>
</>
)
}
);
};
export default DealServicesTable;

View File

@@ -26,7 +26,7 @@ const ProductServicesTable: FC<Props> = ({
onDelete,
onChange,
onCopyServices,
onKitAdd
onKitAdd,
}) => {
const { dealState } = useDealProductAndServiceTabState();
const isLocked = Boolean(dealState.deal?.billRequest);
@@ -45,11 +45,12 @@ const ProductServicesTable: FC<Props> = ({
innerProps: {
onCreate: onCreate,
serviceIds,
quantity
quantity,
category: dealState.deal?.category || undefined,
},
withCloseButton: false
})
}
withCloseButton: false,
});
};
const onChangeClick = (item: DealProductServiceSchema) => {
if (!onChange) return;
@@ -59,33 +60,35 @@ const ProductServicesTable: FC<Props> = ({
element: item,
onChange,
serviceIds,
quantity
quantity,
category: dealState.deal?.category || undefined,
},
withCloseButton: false
})
}
withCloseButton: false,
});
};
const onEmployeeClick = (item: DealProductServiceSchema) => {
if (!onChange) return;
setCurrentService(item);
setEmployeesModalVisible(true);
}
};
const onEmployeeModalClose = () => {
setEmployeesModalVisible(false);
setCurrentService(undefined);
}
};
const getCurrentEmployees = (): UserSchema[] => {
if (!currentService) return [];
const item = items.find(i => i.service.id === currentService.service.id)
const item = items.find(i => i.service.id === currentService.service.id);
if (!item) return [];
return item.employees;
}
};
const onEmployeesChange = (items: UserSchema[]) => {
if (!currentService || !onChange) return;
onChange({
...currentService,
employees: items
employees: items,
});
}
};
return (
<>
<Flex
@@ -177,6 +180,6 @@ const ProductServicesTable: FC<Props> = ({
</Modal>
</>
)
}
);
};
export default ProductServicesTable;

View File

@@ -1,5 +1,5 @@
import { FC, useEffect, useState } from "react";
import styles from './LeadsPage.module.css';
import styles from "./LeadsPage.module.css";
import Board from "../../../components/Dnd/Board/Board.tsx";
import { DragDropContext, Droppable, DropResult } from "@hello-pangea/dnd";
import { useDealSummaries } from "../hooks/useDealSummaries.tsx";
@@ -51,14 +51,14 @@ export const LeadsPage: FC = () => {
notifications.guess(ok, { message });
if (!ok) return;
await refetch();
})
});
},
labels: {
confirm: "Удалить",
cancel: "Отмена"
}
cancel: "Отмена",
},
});
}
};
const onSuccess = (dealId: number) => {
const summary = summaries.find(summary => summary.id == dealId);
if (!summary) return;
@@ -74,14 +74,14 @@ export const LeadsPage: FC = () => {
notifications.guess(ok, { message });
if (!ok) return;
await refetch();
})
});
},
labels: {
confirm: "Завершить",
cancel: "Отмена"
}
cancel: "Отмена",
},
});
}
};
const onDragEnd = async (result: DropResult) => {
setIsDragEnded(true);
// If there is no changes
@@ -97,11 +97,11 @@ export const LeadsPage: FC = () => {
// Checking if it is custom actions
const droppableId = result.destination.droppableId;
if (droppableId === 'DELETE') {
if (droppableId === "DELETE") {
onDelete(dealId);
return;
}
if (droppableId === 'SUCCESS') {
if (droppableId === "SUCCESS") {
onSuccess(dealId);
return;
}
@@ -109,8 +109,8 @@ export const LeadsPage: FC = () => {
const request: Partial<DealSummaryReorderRequest> = {
dealId: dealId,
index: result.destination.index,
status: status
}
status: status,
};
if (status == summary.status) {
DealService.reorderDealSummaries({ requestBody: request as DealSummaryReorderRequest })
.then(async response => {
@@ -120,7 +120,7 @@ export const LeadsPage: FC = () => {
return;
}
modals.openContextModal({
modal: 'enterDeadline',
modal: "enterDeadline",
title: "Необходимо указать дедлайн",
innerProps: {
onSubmit: (event) => DealService.reorderDealSummaries({ requestBody: event })
@@ -128,11 +128,11 @@ export const LeadsPage: FC = () => {
setSummaries(response.summaries);
await refetch();
}),
request: request
}
request: request,
},
});
}
};
const getTableBody = () => {
return (
<motion.div
@@ -145,8 +145,8 @@ export const LeadsPage: FC = () => {
<DealsTable items={data} />
</motion.div>
)
}
);
};
const getBoardBody = () => {
return (
@@ -154,7 +154,7 @@ export const LeadsPage: FC = () => {
style={{
display: "flex",
height: "100%",
flex: 1
flex: 1,
}}
key={displayMode}
initial={{ opacity: 0 }}
@@ -173,21 +173,21 @@ export const LeadsPage: FC = () => {
style={{ flex: 1 }}
>
<div className={styles['boards']}>
<div className={styles["boards"]}>
<Board
withCreateButton
summaries={summaries
.filter(summary => summary.status == DealStatus.AWAITING_ACCEPTANCE)}
title={"Ожидает приемки"}
droppableId={"AWAITING_ACCEPTANCE"}
color={'#4A90E2'}
color={"#4A90E2"}
/>
<Board
summaries={summaries
.filter(summary => summary.status == DealStatus.PACKAGING)}
title={"Упаковка"}
droppableId={"PACKAGING"}
color={'#F5A623'}
color={"#F5A623"}
/>
<Board
@@ -195,7 +195,7 @@ export const LeadsPage: FC = () => {
.filter(summary => summary.status == DealStatus.AWAITING_SHIPMENT)}
title={"Ожидает отгрузки"}
droppableId={"AWAITING_SHIPMENT"}
color={'#7ED321'}
color={"#7ED321"}
/>
<Board
@@ -203,7 +203,7 @@ export const LeadsPage: FC = () => {
.filter(summary => summary.status == DealStatus.AWAITING_PAYMENT)}
title={"Ожидает оплаты"}
droppableId={"AWAITING_PAYMENT"}
color={'#D0021B'}
color={"#D0021B"}
/>
<Board
@@ -211,15 +211,15 @@ export const LeadsPage: FC = () => {
.filter(summary => summary.status == DealStatus.COMPLETED)}
title={"Завершена"}
droppableId={"COMPLETED"}
color={'#417505'}
color={"#417505"}
/>
</div>
<Flex justify={"space-between"} gap={rem(10)}>
<div
className={
classNames(
styles['delete'],
isDragEnded && styles['delete-hidden']
styles["delete"],
isDragEnded && styles["delete-hidden"],
)
}
>
@@ -250,8 +250,8 @@ export const LeadsPage: FC = () => {
<div
className={
classNames(
styles['delete'],
isDragEnded && styles['delete-hidden']
styles["delete"],
isDragEnded && styles["delete-hidden"],
)
}
>
@@ -284,11 +284,11 @@ export const LeadsPage: FC = () => {
</DragDropContext>
</motion.div>
)
}
);
};
const getBody = () => {
return displayMode === DisplayMode.TABLE ? getTableBody() : getBoardBody();
}
};
return (
<PageBlock
fullHeight
@@ -352,7 +352,7 @@ export const LeadsPage: FC = () => {
>
<div
className={styles['top-panel']}
className={styles["top-panel"]}
style={{ display: displayMode === DisplayMode.TABLE ? "flex" : "none" }}
>
<DealStatusSelect
@@ -384,7 +384,7 @@ export const LeadsPage: FC = () => {
display: "flex",
flexDirection: "column",
flex: 1,
height: "100%"
height: "100%",
}}>
{getBody()}
</PageBlock>
@@ -394,5 +394,5 @@ export const LeadsPage: FC = () => {
</PageBlock>
)
}
);
};

View File

@@ -0,0 +1,41 @@
import { CRUDTableProps } from "../../../../types/CRUDTable.tsx";
import { ServicePriceCategorySchema } from "../../../../client";
import { FC } from "react";
import { BaseTable } from "../../../../components/BaseTable/BaseTable.tsx";
import useServicePriceCategoryTableColumns from "./columns.tsx";
import { MRT_TableOptions } from "mantine-react-table";
import { ActionIcon, Flex, Tooltip } from "@mantine/core";
import { IconEdit, IconTrash } from "@tabler/icons-react";
type Props = CRUDTableProps<ServicePriceCategorySchema>
const ServicePriceCategoryTable: FC<Props> = ({ items, onChange, onDelete }) => {
const columns = useServicePriceCategoryTableColumns();
return (
<BaseTable
data={items}
columns={columns}
restProps={{
enableRowActions: true,
renderRowActions: ({ row }) => (
<Flex gap="md">
<Tooltip label="Редактировать">
<ActionIcon
onClick={() => onChange && onChange(row.original)}
variant={"default"}>
<IconEdit />
</ActionIcon>
</Tooltip>
<Tooltip label="Удалить">
<ActionIcon onClick={() => onDelete && onDelete(row.original)} variant={"default"}>
<IconTrash />
</ActionIcon>
</Tooltip>
</Flex>
),
} as MRT_TableOptions<ServicePriceCategorySchema>}
/>
);
};
export default ServicePriceCategoryTable;

View File

@@ -0,0 +1,17 @@
import { useMemo } from "react";
import { MRT_ColumnDef } from "mantine-react-table";
import { ServicePriceCategorySchema } from "../../../../client";
const useServicePriceCategoryTableColumns = () => {
return useMemo<MRT_ColumnDef<ServicePriceCategorySchema>[]>(() => [
{
accessorKey: "name",
header: "Название",
enableColumnActions: false,
enableSorting: false,
},
], []);
};
export default useServicePriceCategoryTableColumns;

View File

@@ -0,0 +1,54 @@
import { BaseFormInputProps } from "../../../../types/utils.ts";
import type { ServiceCategoryPriceSchema, ServicePriceCategorySchema } from "../../../../client";
import { FC, useEffect, useState } from "react";
import { Flex, NumberInput, rem } from "@mantine/core";
import ServicePriceCategorySelect
from "../../../../components/Selects/ServicePriceCategorySelect/ServicePriceCategorySelect.tsx";
export type PriceCategoryInputProps = BaseFormInputProps<ServiceCategoryPriceSchema[]>
const PriceCategoryInput: FC<PriceCategoryInputProps> = (props: PriceCategoryInputProps) => {
const [innerState, setInnerState] = useState<ServiceCategoryPriceSchema[]>(props.value || []);
const [category, setCategory] = useState<ServicePriceCategorySchema | undefined>(undefined);
const getValue = (): number | undefined | string => {
if (category === undefined) return undefined;
const value = innerState.find(item => item.category.id === category.id);
return value?.price || "";
};
const handleChange = (value: number | string) => {
// remove value if is string
if (typeof value === "string") {
setInnerState(innerState.filter(item => item.category.id !== category?.id));
return;
}
const newValue = {
category: category as ServicePriceCategorySchema,
price: value,
};
const newInnerState = innerState.filter(item => item.category.id !== category?.id);
setInnerState([...newInnerState, newValue]);
};
useEffect(() => {
if (props.value === innerState) return;
props.onChange(innerState);
}, [innerState]);
return (
<Flex direction={"column"} gap={rem(10)}>
<ServicePriceCategorySelect
label={"Категория цены"}
placeholder={"Выберите категорию цены"}
onChange={setCategory}
/>
<NumberInput
label={"Цена"}
placeholder={"Введите цену"}
value={getValue()}
onChange={handleChange}
/>
</Flex>
);
};
export default PriceCategoryInput;

View File

@@ -0,0 +1,49 @@
import { SegmentedControl, SegmentedControlProps } from "@mantine/core";
import { FC } from "react";
import { omit } from "lodash";
export enum ServicePriceType {
DEFAULT,
BY_RANGE,
BY_CATEGORY,
}
type RestProps = {
onChange: (value: ServicePriceType) => void;
value?: ServicePriceType;
}
type Props = Omit<SegmentedControlProps, "data" | "value" | "onChange"> & RestProps;
const ServicePriceTypeSegmentedControl: FC<Props> = (props) => {
const { onChange, value } = props;
const data = [
{
label: "По умолчанию",
value: ServicePriceType.DEFAULT.toString(),
},
{
label: "По диапазону",
value: ServicePriceType.BY_RANGE.toString(),
},
{
label: "По категории",
value: ServicePriceType.BY_CATEGORY.toString(),
},
];
const handleChange = (value: string) => {
onChange(Number(value));
};
const restProps = omit(props, ["onChange", "value"]);
return (
<SegmentedControl
data={data}
value={value?.toString()}
onChange={handleChange}
{...restProps}
/>
);
};
export default ServicePriceTypeSegmentedControl;

View File

@@ -1,27 +1,33 @@
import { FC } from "react";
import { SegmentedControl, SegmentedControlProps } from "@mantine/core";
export enum ServicesTab {
DEAL_SERVICE,
PRODUCT_SERVICE,
SERVICES_KITS
SERVICES_KITS,
SERVICES_PRICE_CATEGORIES
}
type Props = Omit<SegmentedControlProps, 'data'>;
type Props = Omit<SegmentedControlProps, "data">;
const data = [
{
label: 'Для товара',
value: ServicesTab.PRODUCT_SERVICE.toString()
label: "Для товара",
value: ServicesTab.PRODUCT_SERVICE.toString(),
},
{
label: 'Для сделки',
value: ServicesTab.DEAL_SERVICE.toString()
label: "Для сделки",
value: ServicesTab.DEAL_SERVICE.toString(),
},
{
label: 'Наборы услуг',
value: ServicesTab.SERVICES_KITS.toString()
}
]
label: "Наборы услуг",
value: ServicesTab.SERVICES_KITS.toString(),
},
{
label: "Категории цен",
value: ServicesTab.SERVICES_PRICE_CATEGORIES.toString(),
},
];
const ServiceTypeSegmentedControl: FC<Props> = (props) => {
return (
@@ -29,6 +35,6 @@ const ServiceTypeSegmentedControl: FC<Props> = (props) => {
data={data}
{...props}
/>
)
}
export default ServiceTypeSegmentedControl
);
};
export default ServiceTypeSegmentedControl;

View File

@@ -0,0 +1,10 @@
import ObjectList from "../../../hooks/objectList.tsx";
import { ServiceService } from "../../../client";
const useServicePriceCategoriesList = () => ObjectList({
queryFn: ServiceService.getAllPriceCategories,
getObjectsFn: (response) => response.priceCategories,
queryKey: "getAllPriceCategories",
});
export default useServicePriceCategoriesList;

View File

@@ -0,0 +1,80 @@
import UseObjectState from "../../../types/UseObjectState.ts";
import { type ServicePriceCategorySchema, ServiceService } from "../../../client";
import useServicePriceCategoriesList from "./useServicePriceCategoriesList.tsx";
import { modals } from "@mantine/modals";
import { notifications } from "../../../shared/lib/notifications.ts";
const useServicePriceCategoryState = (): UseObjectState<ServicePriceCategorySchema> => {
const { objects, refetch } = useServicePriceCategoriesList();
const onCreateClick = () => {
modals.openContextModal({
modal: "servicePriceCategoryForm",
title: "Создание категории цен",
withCloseButton: false,
innerProps: {
onCreate,
},
});
};
const onCreate = (values: ServicePriceCategorySchema) => {
console.log(ServiceService);
ServiceService.createPriceCategory({
requestBody: {
name: values.name,
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
};
const onDelete = (item: ServicePriceCategorySchema) => {
modals.openConfirmModal({
title: "Удаление категории",
children: "Вы уверены, что хотите удалить категорию?",
onConfirm: () => {
ServiceService.deletePriceCategory({
requestBody: {
id: item.id,
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
},
});
};
const onChange = (item: ServicePriceCategorySchema) => {
modals.openContextModal({
modal: "servicePriceCategoryForm",
title: "Изменение категории цен",
withCloseButton: false,
innerProps: {
onChange: (values: ServicePriceCategorySchema) => {
ServiceService.updatePriceCategory({
requestBody: {
id: item.id,
name: values.name,
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
},
element: item,
},
});
};
return {
onCreateClick,
onCreate,
onDelete,
onChange,
objects,
};
};
export default useServicePriceCategoryState;

View File

@@ -0,0 +1,57 @@
import { GetServiceKitSchema, ServiceService } from "../../../client";
import { omit } from "lodash";
import { notifications } from "../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import useServicesKitsList from "./useServicesKitsList.tsx";
const useServicesKitsState = () => {
const { objects: servicesKits, refetch: refetchKits } = useServicesKitsList();
const onKitCreate = (kit: GetServiceKitSchema) => {
ServiceService.createServicesKit({
requestBody: {
data: {
...omit(kit, ["services", "id"]),
servicesIds: kit.services.map(service => service.id),
},
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetchKits();
});
};
const onKitCreateClick = () => {
modals.openContextModal({
modal: "serviceKitModalForm",
title: "Создание набора услуг",
withCloseButton: false,
innerProps: {
onCreate: onKitCreate,
},
});
};
const onKitUpdate = (kit: GetServiceKitSchema) => {
ServiceService.updateServicesKit({
requestBody: {
data: {
...omit(kit, ["services"]),
servicesIds: kit.services.map(service => service.id),
},
},
}).then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetchKits();
});
};
return {
onKitCreateClick,
onKitUpdate,
servicesKits,
};
};
export default useServicesKitsState;

View File

@@ -0,0 +1,89 @@
import { modals } from "@mantine/modals";
import { ServiceCategorySchema, ServiceSchema, ServiceService } from "../../../client";
import { notifications } from "../../../shared/lib/notifications.ts";
import useServicesList from "./useServicesList.tsx";
import { Text } from "@mantine/core";
const useServicesState = () => {
const { services, refetch } = useServicesList();
const onCreateClick = () => {
modals.openContextModal({
modal: "createService",
title: "Создание услуги",
withCloseButton: false,
innerProps: {
onCreate,
},
});
};
const onCreate = (values: ServiceSchema) => {
ServiceService.createService({ requestBody: { service: values } })
.then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
};
const onCreateCategoryClick = () => {
modals.openContextModal({
modal: "createServiceCategory",
title: "Создание категории",
withCloseButton: false,
innerProps: {
onCreate: onCategoryCreate,
},
});
};
const onCategoryCreate = (category: ServiceCategorySchema) => {
ServiceService.createServiceCategory({ requestBody: { category: category } })
.then(({ ok, message }) =>
notifications.guess(ok, { message: message }));
};
const onServiceDelete = (service: ServiceSchema) => {
modals.openConfirmModal({
title: "Удаление услуги",
children: (<Text>
Вы уверены, что хотите удалить услугу "{service.name}"?
</Text>),
onConfirm: () => {
ServiceService.deleteService({ requestBody: { serviceId: service.id } })
.then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
},
labels: {
confirm: "Удалить",
cancel: "Отмена",
},
});
};
const onServiceUpdate = (service: ServiceSchema) => {
ServiceService
.updateService({
requestBody: {
data: service,
},
})
.then(async ({ ok, message }) => {
notifications.guess(ok, { message: message });
if (!ok) return;
await refetch();
});
};
return {
services,
onCreateClick,
onServiceDelete,
onServiceUpdate,
onCreateCategoryClick,
};
};
export default useServicesState;

View File

@@ -2,11 +2,16 @@ import {ServicePriceRangeSchema, ServiceSchema} from "../../../client";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import BaseFormModal, { CreateEditFormProps } from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {NumberInput, TextInput} from "@mantine/core";
import { Fieldset, Flex, rem, TextInput } from "@mantine/core";
import ServiceCategorySelect from "../components/ServiceCategorySelect/ServiceCategorySelect.tsx";
import ServiceTypeSelect from "../components/ServiceTypeSelect/ServiceTypeSelect.tsx";
import ServicePriceInput from "../components/ServicePriceInput/ServicePriceInput.tsx";
import {PriceRangeInputType} from "../components/ServicePriceInput/RangePriceInput.tsx";
import ServicePriceTypeSegmentedControl, {
ServicePriceType,
} from "../components/ServicePriceTypeSegmentedControl/ServicePriceTypeSegmentedControl.tsx";
import { useEffect, useState } from "react";
import RangePriceInput, { PriceRangeInputType } from "../components/ServicePriceInput/RangePriceInput.tsx";
import SinglePriceInput from "../components/ServicePriceInput/SinglePriceInput.tsx";
import PriceCategoryInput, { PriceCategoryInputProps } from "../components/ServicePriceInput/PriceCategoryInput.tsx";
type Props = CreateEditFormProps<ServiceSchema>
const CreateServiceModal = ({
@@ -14,40 +19,61 @@ const CreateServiceModal = ({
id,
innerProps,
}: ContextModalProps<Props>) => {
const isEditing = 'onChange' in innerProps;
const [priceType, setPriceType] = useState<ServicePriceType>(ServicePriceType.DEFAULT);
const isEditing = "onChange" in innerProps;
const initialValues: ServiceSchema = isEditing ? innerProps.element : {
id: -1,
name: '',
name: "",
price: 0,
category: {
id: -1,
name: ''
name: "",
},
serviceType: -1,
priceRanges: [] as ServicePriceRangeSchema[],
cost: null
}
cost: null,
categoryPrices: [],
};
const form = useForm<ServiceSchema>({
initialValues: initialValues,
validate: {
name: (name: string) => name.trim() !== '' ? null : "Необходимо ввести название услуги",
name: (name: string) => name.trim() !== "" ? null : "Необходимо ввести название услуги",
category: (category: {
id: number,
name: string
}) => category.id !== -1 ? null : "Необходимо выбрать категорию",
serviceType: (serviceType: number) => serviceType !== -1 ? null : "Необходимо выбрать тип услуги",
priceRanges: (value, values) => value.length > 0 || values.price > 0 ? null : "Необходимо добавить хотя бы один диапазон цен или указать цену за единицу услуги",
price: (value, values) => value > 0 || values.priceRanges.length > 0 ? null : "Необходимо добавить хотя бы один диапазон цен или указать цену за единицу услуги"
price: (value, values) => value > 0 || values.priceRanges.length > 0 ? null : "Необходимо добавить хотя бы один диапазон цен или указать цену за единицу услуги",
},
});
useEffect(() => {
console.log(form.values.categoryPrices);
}, [form.values]);
const getPriceBody = () => {
switch (priceType) {
case ServicePriceType.DEFAULT:
return <SinglePriceInput
placeholder={"Введите стоимость услуги"}
label={"Cтоимость услуги"}
hideControls
{...form.getInputProps("cost")}
/>;
case ServicePriceType.BY_RANGE:
return <RangePriceInput
{...form.getInputProps("priceRanges") as PriceRangeInputType}
/>;
case ServicePriceType.BY_CATEGORY:
return <PriceCategoryInput
{...form.getInputProps("categoryPrices") as PriceCategoryInputProps}
/>;
}
})
};
const onCancelClick = () => {
context.closeContextModal(id);
}
};
return (
<BaseFormModal
{...innerProps}
@@ -57,43 +83,39 @@ const CreateServiceModal = ({
>
<BaseFormModal.Body>
<>
<Fieldset legend={"Общие параметры"}>
<ServiceCategorySelect
placeholder={"Выберите категорию"}
label={"Категория услуги"}
{...form.getInputProps('category')}
{...form.getInputProps("category")}
/>
<TextInput
placeholder={"Введите название услуги"}
label={"Название услуги"}
{...form.getInputProps('name')}
{...form.getInputProps("name")}
/>
<ServiceTypeSelect
placeholder={"Выберите тип услуги"}
label={"Тип услуги"}
{...form.getInputProps('serviceType')}
{...form.getInputProps("serviceType")}
/>
<NumberInput
placeholder={"Введите себестоимость услуги"}
label={"Себестоимость услуги"}
hideControls
{...form.getInputProps('cost')}
/>
<ServicePriceInput
singlePriceInputProps={{
hideControls: true,
label: "Цена за единицу услуги",
placeholder: "Введите цену за одну услугу",
...form.getInputProps('price'),
}}
priceRangeInputProps={{
...form.getInputProps('priceRanges')
} as PriceRangeInputType}
</Fieldset>
<Fieldset legend={"Стоимость"}>
<Flex direction={"column"} gap={rem(10)} justify={"center"}>
<ServicePriceTypeSegmentedControl
value={priceType}
onChange={setPriceType}
/>
{getPriceBody()}
</Flex>
</Fieldset>
</>
</BaseFormModal.Body>
</BaseFormModal>
)
}
);
};
export default CreateServiceModal;

View File

@@ -0,0 +1,38 @@
import { ServicePriceCategorySchema } from "../../../client";
import BaseFormModal, { CreateEditFormProps } from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import { ContextModalProps } from "@mantine/modals";
import { TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
type Props = CreateEditFormProps<ServicePriceCategorySchema>;
const ServicePriceCategoryForm = ({ context, id, innerProps }: ContextModalProps<Props>) => {
const isEditing = "element" in innerProps;
const initialValues: Partial<ServicePriceCategorySchema> = isEditing ? innerProps.element : {
name: "",
};
const form = useForm<Partial<ServicePriceCategorySchema>>({
initialValues,
});
return (
<BaseFormModal
{...innerProps}
form={form}
closeOnSubmit
onClose={() => context.closeContextModal(id)}
>
<BaseFormModal.Body>
<>
<TextInput
label={"Название"}
placeholder={"Введите название категории"}
{...form.getInputProps("name")}
/>
</>
</BaseFormModal.Body>
</BaseFormModal>
);
};
export default ServicePriceCategoryForm;

View File

@@ -13,17 +13,17 @@ const ServiceKitModalForm = ({
id,
innerProps,
}: ContextModalProps<Props>) => {
const isEditing = 'element' in innerProps;
const isEditing = "element" in innerProps;
const initialValues: Partial<GetServiceKitSchema> = isEditing ? innerProps.element : {
name: "",
serviceType: ServiceType.DEAL_SERVICE,
services: []
}
services: [],
};
const form = useForm<Partial<GetServiceKitSchema>>(
{
initialValues
}
initialValues,
},
);
return (
<BaseFormModal
@@ -54,7 +54,7 @@ const ServiceKitModalForm = ({
</>
</BaseFormModal.Body>
</BaseFormModal>
)
}
);
};
export default ServiceKitModalForm;

View File

@@ -1,173 +1,90 @@
import { FC, useState } from "react";
import ServicesTable from "../components/ServicesTable/ServicesTable.tsx";
import useServicesList from "../hooks/useServicesList.tsx";
import PageBlock from "../../../components/PageBlock/PageBlock.tsx";
import styles from './ServicesPage.module.css';
import {Button, Text} from "@mantine/core";
import {GetServiceKitSchema, ServiceCategorySchema, ServiceSchema, ServiceService} from "../../../client";
import {notifications} from "../../../shared/lib/notifications.ts";
import {modals} from "@mantine/modals";
import styles from "./ServicesPage.module.css";
import { Button } from "@mantine/core";
import ServiceTypeSegmentedControl, {
ServicesTab
ServicesTab,
} from "../components/ServiceTypeSegmentedControl/ServiceTypeSegmentedControl.tsx";
import useServicesKitsList from "../hooks/useServicesKitsList.tsx";
import ServicesKitsTable from "../components/ServicesKitsTable/ServicesKitsTable.tsx";
import {omit} from "lodash";
import ServicePriceCategoryTable from "../components/ServicePriceCategoryTable/ServicePriceCategoryTable.tsx";
import useServicesState from "../hooks/useServicesState.tsx";
import useServicesKitsState from "../hooks/useServicesKitsState.tsx";
import useServicePriceCategoryState from "../hooks/useServicePriceCategoryState.tsx";
import { ObjectStateToTableProps } from "../../../types/utils.ts";
export const ServicesPage: FC = () => {
const {services, refetch} = useServicesList();
const {objects: servicesKits, refetch: refetchKits} = useServicesKitsList();
const [serviceType, setServiceType] = useState(ServicesTab.DEAL_SERVICE)
// region Service create
const onCreateClick = () => {
modals.openContextModal({
modal: 'createService',
title: 'Создание услуги',
withCloseButton: false,
innerProps: {
onCreate
}
})
}
const onCreate = (values: ServiceSchema) => {
ServiceService.createService({requestBody: {service: values}})
.then(async ({ok, message}) => {
notifications.guess(ok, {message: message});
if (!ok) return;
await refetch();
})
}
// endregion
// region Category create
const onCreateCategoryClick = () => {
modals.openContextModal({
modal: "createServiceCategory",
title: 'Создание категории',
withCloseButton: false,
innerProps: {
onCreate: onCategoryCreate
}
})
}
const onCategoryCreate = (category: ServiceCategorySchema) => {
ServiceService.createServiceCategory({requestBody: {category: category}})
.then(({ok, message}) =>
notifications.guess(ok, {message: message}))
}
// endregion
const onServiceDelete = (service: ServiceSchema) => {
modals.openConfirmModal({
title: 'Удаление услуги',
children: (<Text>
Вы уверены, что хотите удалить услугу "{service.name}"?
</Text>),
onConfirm: () => {
ServiceService.deleteService({requestBody: {serviceId: service.id}})
.then(async ({ok, message}) => {
notifications.guess(ok, {message: message});
if (!ok) return;
await refetch();
})
},
labels: {
confirm: 'Удалить',
cancel: 'Отмена'
}
});
}
const onServiceUpdate = (service: ServiceSchema) => {
ServiceService
.updateService({
requestBody: {
data: service
}
})
.then(async ({ok, message}) => {
notifications.guess(ok, {message: message});
if (!ok) return;
await refetch();
})
}
const onKitCreate = (kit: GetServiceKitSchema) => {
ServiceService.createServicesKit({
requestBody: {
data: {
...omit(kit, ["services", "id"]),
servicesIds: kit.services.map(service => service.id)
}
}
}).then(async ({ok, message}) => {
notifications.guess(ok, {message: message});
if (!ok) return;
await refetchKits();
})
}
const onKitCreateClick = () => {
modals.openContextModal({
modal: 'serviceKitModalForm',
title: 'Создание набора услуг',
withCloseButton: false,
innerProps: {
onCreate: onKitCreate
}
})
}
const onKitUpdate = (kit: GetServiceKitSchema) => {
ServiceService.updateServicesKit({
requestBody: {
data: {
...omit(kit, ["services"]),
servicesIds: kit.services.map(service => service.id)
}
}
}).then(async ({ok, message}) => {
notifications.guess(ok, {message: message});
if (!ok) return;
await refetchKits();
})
}
const [serviceType, setServiceType] = useState(ServicesTab.DEAL_SERVICE);
const { services, onServiceDelete, onServiceUpdate, onCreateClick, onCreateCategoryClick } = useServicesState();
const { servicesKits, onKitUpdate, onKitCreateClick } = useServicesKitsState();
const { onCreateClick: onCreatePriceCategoryClick, ...priceCategoryRestProps } = useServicePriceCategoryState();
const getBody = () => {
switch (serviceType) {
case ServicesTab.SERVICES_KITS:
return (
<ServicesKitsTable
items={servicesKits}
onChange={onKitUpdate}
/>
);
case ServicesTab.DEAL_SERVICE:
case ServicesTab.PRODUCT_SERVICE:
return (
<ServicesTable
onDelete={onServiceDelete}
onChange={onServiceUpdate}
items={services.filter(service => service.serviceType == serviceType)}
/>
);
case ServicesTab.SERVICES_PRICE_CATEGORIES:
return (
<ServicePriceCategoryTable
{...ObjectStateToTableProps(priceCategoryRestProps)}
/>
);
}
};
const getControls = () => {
switch (serviceType) {
case ServicesTab.SERVICES_KITS:
return (
<Button onClick={onKitCreateClick} variant={"default"}>Создать набор</Button>
);
case ServicesTab.DEAL_SERVICE:
case ServicesTab.PRODUCT_SERVICE:
return (
<div className={styles['container']}>
<PageBlock>
<div className={styles['top-panel']}>
{
serviceType === ServicesTab.SERVICES_KITS ?
<Button onClick={onKitCreateClick} variant={"default"}>Создать набор</Button> :
<>
<Button onClick={onCreateClick} variant={"default"}>Создать услугу</Button>
<Button onClick={onCreateCategoryClick} variant={"default"}>Создать
категорию</Button>
<Button onClick={onCreateCategoryClick} variant={"default"}>Создать категорию</Button>
</>
);
case ServicesTab.SERVICES_PRICE_CATEGORIES:
return (
<Button variant={"default"} onClick={() => {
if (onCreatePriceCategoryClick) {
onCreatePriceCategoryClick();
}
}}>Создать категорию</Button>
);
}
};
return (
<div className={styles["container"]}>
<PageBlock>
<div className={styles["top-panel"]}>
{getControls()}
<ServiceTypeSegmentedControl
className={styles['top-panel-last-item']}
className={styles["top-panel-last-item"]}
value={serviceType.toString()}
onChange={(event) => setServiceType(parseInt(event))}
/>
</div>
</PageBlock>
<PageBlock>
{
serviceType === ServicesTab.SERVICES_KITS ?
<ServicesKitsTable
items={servicesKits}
onChange={onKitUpdate}
/>
:
<ServicesTable
onDelete={onServiceDelete}
onChange={onServiceUpdate}
items={services.filter(service => service.serviceType == serviceType)}
/>
}
{getBody()}
</PageBlock>
</div>
)
}
);
};

View File

@@ -1,4 +1,4 @@
import {BaseMarketplaceSchema} from "../client";
import { BaseMarketplaceSchema, ServicePriceCategorySchema } from "../client";
export type QuickDeal = {
name: string;
@@ -7,5 +7,6 @@ export type QuickDeal = {
comment: string;
acceptanceDate: Date;
shippingWarehouse: string;
baseMarketplace: BaseMarketplaceSchema
baseMarketplace: BaseMarketplaceSchema;
category?: ServicePriceCategorySchema;
}

View File

@@ -0,0 +1,14 @@
type UseObjectState<T> = {
onCreateClick?: () => void;
onCreate: (values: T) => void;
onDeleteClick?: (item: T) => void;
onDelete: (item: T) => void;
onChangeClick?: (item: T) => void;
onChange: (item: T) => void;
objects: T[];
}
export default UseObjectState;

View File

@@ -1,6 +1,9 @@
import { ProductSchema } from "../client";
import { isNil } from "lodash";
import { ProductFieldNames } from "../pages/LeadsPage/tabs/ProductAndServiceTab/components/ProductView/ProductView.tsx";
import UseObjectState from "./UseObjectState.ts";
import { CRUDTableProps } from "./CRUDTable.tsx";
import { MRT_RowData } from "mantine-react-table";
export type ObjectWithNameAndId = {
id: number;
@@ -14,12 +17,22 @@ export type BaseFormInputProps<T> = {
}
export const formatDate = (date: string) => {
return new Date(date).toLocaleDateString("ru-RU");
}
};
export const getProductFields = (product: ProductSchema) => {
return Object.entries(product).map(([key, value]) => {
const fieldName = ProductFieldNames[key as keyof ProductSchema];
if (!fieldName || isNil(value) || value === '' || !value) return;
if (!fieldName || isNil(value) || value === "" || !value) return;
return [fieldName.toString(), value.toString()];
}).filter(obj => obj !== undefined) || [];
};
export function ObjectStateToTableProps<T extends MRT_RowData>(state: UseObjectState<T>): CRUDTableProps<T> {
return {
items: state.objects,
onDelete: state.onDelete,
onChange: state.onChange,
onCreate: state.onCreate,
};
}