doing add functional

parent 135dd26d
...@@ -35,4 +35,4 @@ const App: React.FC = () => { ...@@ -35,4 +35,4 @@ const App: React.FC = () => {
); );
}; };
export default App; export default App;
\ No newline at end of file
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
interface Organizations { interface Organization {
id: number; id: number;
bin: string; bin: string;
organization_code: string; organization_code: string;
...@@ -12,39 +12,43 @@ interface Organizations { ...@@ -12,39 +12,43 @@ interface Organizations {
export const apiSlice = createApi({ export const apiSlice = createApi({
reducerPath: 'api', reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: "https://669f8d88b132e2c136fe5106.mockapi.io/api/v1" }), baseQuery: fetchBaseQuery({ baseUrl: "https://669f8d88b132e2c136fe5106.mockapi.io/api/v1" }),
tagTypes: ["organizations"],
endpoints: (builder) => ({ endpoints: (builder) => ({
getOrganizations: builder.query<Organizations[], void>({ getOrganizations: builder.query<Organization[], void>({
query: () => '/organizations' query: () => '/organizations',
providesTags: ["organizations"],
}), }),
getOrganization: builder.query({ getOrganization: builder.query<Organization, string>({
query: orgId => `/organizations/${orgId}` query: (orgId) => `/organizations/${orgId}`,
}), }),
addNewOrganization: builder.query({ addNewOrganization: builder.mutation<Organization, Partial<Organization>>({
query: initialOrg => ({ query: (initialOrg) => ({
url: '/organizations', url: '/organizations',
method: 'POST', method: 'POST',
body: initialOrg body: initialOrg,
}) }),
invalidatesTags: ["organizations"],
}), }),
editOrganization: builder.query({ editOrganization: builder.mutation<Organization, Partial<Organization>>({
query: org => ({ query: ({ id, ...rest }) => ({
url: `/organizations/${org.id}`, url: `/organizations/${id}`,
method: 'PUT', method: 'PUT',
body: org body: rest,
}) }),
}), }),
deleteOrganization: builder.query({ deleteOrganization: builder.mutation<{ success: boolean; id: number }, number>({
query: orgId => ({ query: (orgId) => ({
url: `organizations/${orgId}`, url: `/organizations/${orgId}`,
method: "DELETE", method: 'DELETE',
}) }),
}) }),
}) }),
}) });
export const { export const {
useGetOrganizationsQuery, useGetOrganizationsQuery,
useGetOrganizationQuery, useGetOrganizationQuery,
useAddNewOrganizationQuery, useAddNewOrganizationMutation,
useEditOrganizationQuery, useEditOrganizationMutation,
useDeleteOrganizationQuery } = apiSlice; useDeleteOrganizationMutation,
\ No newline at end of file } = apiSlice;
import React from 'react'; import React from 'react';
import { Form, Input, Button, Select } from 'antd'; import { Form, Input, Button, Select, message } from 'antd';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { useAddNewOrganizationMutation } from '../../features/api/apiSlice';
import './style.css'; import './style.css';
const { Item } = Form; const { Item } = Form;
const { Option } = Select; const { Option } = Select;
interface Values{
bin: string;
host: string;
login: string;
organization_code: string;
organization_name: string;
status: string;
password: string;
}
const AddPage: React.FC = () => { const AddPage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const [addNewOrganization] = useAddNewOrganizationMutation();
const onFinish = async (values: Values) => {
try {
await addNewOrganization(values).unwrap();
message.success('Организация успешно добавлена!');
console.log(values);
navigate('/');
} catch (err) {
message.error('Произошла ошибка при добавлении организации!');
}
};
return ( return (
<div className='container'> <div className='container'>
<Form <Form
layout="vertical" layout="vertical"
name="organization_form" name="organization_form"
initialValues={{ remember: true }} initialValues={{ status: 'active' }}
onFinish={onFinish}
className='form' className='form'
> >
<Item <Item
label="БИН организации" label="БИН организации"
name="bin" name="bin"
rules={[{ required: true, message: 'Пожалуйста, введите БИН организации!' }]} rules={[
{ required: true, message: 'Пожалуйста, введите БИН организации!' },
{ pattern: /^\d{12}$/, message: 'БИН должен состоять из 12 цифр!' }
]}
> >
<Input maxLength={12} placeholder="Максимальная длина: 12 символов" /> <Input maxLength={12} placeholder="12 цифр" />
</Item> </Item>
<Item <Item
label="Код организации" label="Код организации"
name="code" name="organization_code"
rules={[{ required: true, message: 'Пожалуйста, введите код организации!' }]} rules={[
{ required: true, message: 'Пожалуйста, введите код организации!' },
{ pattern: /^[a-zA-Z0-9-_]+$/, message: 'Код организации должен содержать только английские буквы, цифры, символы "-" и "_"' }
]}
> >
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" /> <Input maxLength={128} />
</Item> </Item>
<Item <Item
label="Наименование организации" label="Наименование организации"
name="name" name="organization_name"
rules={[{ required: true, message: 'Пожалуйста, введите наименование организации!' }]} rules={[{ required: true, message: 'Пожалуйста, введите наименование организации!' }]}
> >
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" /> <Input maxLength={128} />
</Item> </Item>
<Item <Item
label="Адрес системы/хост" label="Адрес системы/хост"
name="address" name="host"
rules={[{ required: true, message: 'Пожалуйста, введите адрес системы/хост!' }]} rules={[{ required: true, message: 'Пожалуйста, введите адрес системы/хост!' }]}
> >
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" /> <Input maxLength={128} />
</Item> </Item>
<Item <Item
label="Логин" label="Логин"
name="login" name="login"
rules={[{ required: true, message: 'Пожалуйста, введите логин!' }]} rules={[
{ required: true, message: 'Пожалуйста, введите логин!' },
{ pattern: /^[a-zA-Z0-9-_]+$/, message: 'Логин должен содержать только английские буквы, цифры, символы "-" и "_"' }
]}
> >
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" /> <Input maxLength={128} />
</Item> </Item>
<Item <Item
label="Пароль" label="Пароль"
name="password" name="password"
rules={[{ required: true, message: 'Пожалуйста, введите пароль!' }]} rules={[
{ required: true, message: 'Пожалуйста, введите пароль!' },
{ pattern: /^[a-zA-Z0-9-_]+$/, message: 'Пароль должен содержать только английские буквы, цифры, символы "-" и "_"' }
]}
> >
<Input.Password maxLength={128} placeholder="Максимальная длина: 128 символов" /> <Input.Password maxLength={128} />
</Item> </Item>
<Item <Item
...@@ -78,12 +114,10 @@ const AddPage: React.FC = () => { ...@@ -78,12 +114,10 @@ const AddPage: React.FC = () => {
</Item> </Item>
<div className='form-footer'> <div className='form-footer'>
<Item style={{}} className='form-footer-item'> <Item className='form-footer-item'>
<Button type="default" style={{ marginRight: '8px' }} <Button type="default" style={{ marginRight: '8px' }} onClick={() => navigate("/")}>
onClick={() => navigate("/")}>
Отмена Отмена
</Button> </Button>
<Button type="primary" htmlType="submit"> <Button type="primary" htmlType="submit">
Сохранить Сохранить
</Button> </Button>
......
import React from 'react'; import React from 'react';
import { useNavigate } from 'react-router'; import { useNavigate } from 'react-router';
import { MaterialSymbol } from 'react-material-symbols'; import { MaterialSymbol } from 'react-material-symbols';
import { Button, Pagination, Space, Spin, Table, Tag } from 'antd'; import { Button, Space, Spin, Table, Tag } from 'antd'; //Pagination
import type { TableProps } from 'antd'; import type { TableProps } from 'antd';
import './Homepage.css'; import './Homepage.css';
import { useGetOrganizationsQuery } from '../../features/api/apiSlice'; import { useGetOrganizationsQuery } from '../../features/api/apiSlice';
...@@ -29,46 +29,40 @@ const columns: TableProps<DataType>['columns'] = [ ...@@ -29,46 +29,40 @@ const columns: TableProps<DataType>['columns'] = [
{ {
title: "Код организации", title: "Код организации",
dataIndex: "organization_code", dataIndex: "organization_code",
key: "code" key: "organization_code"
}, },
{ {
title: "Наименование организации", title: "Наименование организации",
dataIndex: "organization_name", dataIndex: "organization_name",
key: "name" key: "organization_name"
},
{
title: "Адрес системы/хост",
dataIndex: "host",
key: "host"
}, },
{ {
title: "Статус", title: "Статус",
dataIndex: "status", dataIndex: "status",
key: "status", key: "status",
render: (_, record) => { render: (_, record) => {
let color = record.status == '0' ? 'red' : record.status == '1' ? 'processing' : 'green'; const color = record.status === 'deleted' ? 'red' : record.status === 'blocked' ? 'orange' : 'green';
return ( return (
<p> <Tag color={color} style={{ fontSize: '14px' }}>
<Tag color={color} style={{fontSize: '14px'}}> {record.status === 'deleted' ? 'Удален' : record.status === 'blocked' ? 'Заблокирован' : 'Активен'}
{record.status == '0' ? 'удален' : record.status == '1' ? 'заблокирован' : 'активен'} </Tag>
</Tag> );
</p>
)
} }
}, },
{ {
title: "Действия", title: "Действия",
width: 60, width: 60,
render: (value ) => { render: (value) => {
return ( return (
<Space> <Space>
<Button onClick={() => console.log(value)} icon={<MaterialSymbol icon='visibility' size={22} />} /> <Button onClick={() => console.log(value)} icon={<MaterialSymbol icon='visibility' size={22} />} />
<Button onClick={() => console.log(value)} icon={<MaterialSymbol icon='delete' size={22} />} /> <Button onClick={() => console.log(value)} icon={<MaterialSymbol icon='delete' size={22} />} />
</Space> </Space>
) )
} }
} }
]
];
const HomePage: React.FC = () => { const HomePage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
...@@ -77,10 +71,6 @@ const HomePage: React.FC = () => { ...@@ -77,10 +71,6 @@ const HomePage: React.FC = () => {
navigate("/add"); navigate("/add");
}; };
const handlePaginationChange = (page: number | string | null) => {
console.log("Current page:", page);
};
const { const {
data: orgs = [], data: orgs = [],
isLoading, isLoading,
...@@ -92,12 +82,12 @@ const HomePage: React.FC = () => { ...@@ -92,12 +82,12 @@ const HomePage: React.FC = () => {
let table; let table;
if (isLoading) { if (isLoading) {
table = <Spin /> table = <Spin />;
} else if (isSuccess) { } else if (isSuccess) {
const dataSource = orgs.map((org) => ({ ...org, key: org.id })); const dataSource = orgs.map((org) => ({ ...org, key: org.id }));
table = <Table dataSource={dataSource} columns={columns} pagination={false} /> table = <Table dataSource={dataSource} columns={columns} pagination={false} />;
} else if (isError) { } else if (isError) {
table = <div>{error.toString()}</div> table = <div>{error.toString()}</div>;
} }
return ( return (
...@@ -111,13 +101,12 @@ const HomePage: React.FC = () => { ...@@ -111,13 +101,12 @@ const HomePage: React.FC = () => {
<div className="data"> <div className="data">
{table} {table}
</div> </div>
<div className='pagination-container'> {/* <div className='pagination-container'>
<Pagination current={1} defaultCurrent={1} pageSize={1} total={10} onChange={handlePaginationChange} /> <Pagination current={1} defaultCurrent={1} pageSize={10} total={orgs.length} />
</div> </div> */}
</section> </section>
</div> </div>
); );
} };
export default HomePage; export default HomePage;
import React from "react";
import { Form, Input, Button } from "antd";
import { useNavigate } from "react-router";
import "../../src/styles/Home/addPage.css";
const { Item } = Form;
const AddPage: React.FC = () => {
const navigate = useNavigate();
return (
<div className="container">
<Form
layout="vertical"
name="organization_form"
initialValues={{ remember: true }}
className="form-add"
>
<Item
label="БИН организации"
name="bin"
rules={[
{ required: true, message: "Пожалуйста, введите БИН организации!" },
]}
>
<Input
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<Item
label="Код организации"
name="code"
rules={[
{ required: true, message: "Пожалуйста, введите код организации!" },
]}
>
<Input
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<Item
label="Наименование организации"
name="name"
rules={[
{
required: true,
message: "Пожалуйста, введите наименование организации!",
},
]}
>
<Input
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<Item
label="Адрес системы/хост"
name="address"
rules={[
{
required: true,
message: "Пожалуйста, введите адрес системы/хост!",
},
]}
>
<Input
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<Item
label="Логин"
name="login"
rules={[{ required: true, message: "Пожалуйста, введите логин!" }]}
>
<Input
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<Item
label="Пароль"
name="password"
rules={[{ required: true, message: "Пожалуйста, введите пароль!" }]}
>
<Input.Password
maxLength={128}
placeholder="Максимальная длина: 128 символов"
/>
</Item>
<div className="form-footer">
<Item style={{ textAlign: "right" }} className="form-footer-item">
<Button
type="default"
style={{ marginRight: "8px" }}
onClick={() => navigate("/")}
>
Отмена
</Button>
<Button type="primary" htmlType="submit">
Сохранить
</Button>
</Item>
</div>
</Form>
</div>
);
};
export default AddPage;
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment