finished add, edit, delete functionality

parent 0a4a3a0d
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
interface Organization { interface Organization {
id: number; id: number | string;
bin: string; bin: string;
organization_code: string; organization_code: string;
organization_name: string; organization_name: string;
...@@ -34,13 +34,15 @@ export const apiSlice = createApi({ ...@@ -34,13 +34,15 @@ export const apiSlice = createApi({
url: `/organizations/${id}`, url: `/organizations/${id}`,
method: 'PUT', method: 'PUT',
body: rest, body: rest,
}) }),
invalidatesTags: ["organizations"]
}), }),
deleteOrganization: builder.mutation<{ success: boolean; id: number }, number>({ deleteOrganization: builder.mutation<{ success: boolean; id: number }, number>({
query: (orgId) => ({ query: (orgId) => ({
url: `/organizations/${orgId}`, url: `/organizations/${orgId}`,
method: 'DELETE', method: 'DELETE',
}), }),
invalidatesTags: ["organizations"],
}), }),
}), }),
}); });
......
...@@ -7,23 +7,20 @@ import './style.css'; ...@@ -7,23 +7,20 @@ 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 [addNewOrganization] = useAddNewOrganizationMutation();
const onFinish = async (values: Values) => { const onFinish = async (values: any) => {
const newValues = {
...values,
status: values.status === 'active' ? '2' : values.status === 'blocked' ? '1' : '0',
deleted: null,
created: new Date().toISOString(),
};
try { try {
await addNewOrganization(values).unwrap(); await addNewOrganization(newValues).unwrap();
message.success('Организация успешно добавлена!'); message.success('Организация успешно добавлена!');
console.log(values); console.log(values);
navigate('/'); navigate('/');
......
import React from 'react'; import React, { useEffect } from 'react';
import { Form, Input, Button, Select } from 'antd'; import { Form, Input, Button, Select, message } from 'antd';
import { useNavigate } from 'react-router'; import { useNavigate, useParams } from 'react-router';
import { useGetOrganizationQuery, useEditOrganizationMutation } from '../../features/api/apiSlice';
import './style.css'; import './style.css';
const { Item } = Form; const { Item } = Form;
...@@ -8,69 +9,113 @@ const { Option } = Select; ...@@ -8,69 +9,113 @@ const { Option } = Select;
const EditPage: React.FC = () => { const EditPage: React.FC = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { id } = useParams<{ id: string }>();
const { data, isLoading, isError } = useGetOrganizationQuery(id!);
const [editOrganization] = useEditOrganizationMutation();
const [form] = Form.useForm();
useEffect(() => {
if (data) {
form.setFieldsValue({
...data,
status: data.status === '2' ? 'active' : data.status === '1' ? 'blocked' : 'deleted'
});
}
}, [data, form]);
const onFinish = async (values: any) => {
const updatedValues = {
...values,
status: values.status === 'active' ? '2' : values.status === 'blocked' ? '1' : '0',
deleted: null,
};
try {
await editOrganization({ id: data?.id, ...updatedValues }).unwrap();
message.success('Организация успешно обновлена!');
navigate('/');
} catch (err) {
message.error('Произошла ошибка при обновлении организации!');
}
};
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error loading organization data</div>;
return ( return (
<div className="container"> <div className="container">
<Form <Form
form={form}
layout="vertical" layout="vertical"
name="organization_form" name="organization_form"
initialValues={{ remember: true }} onFinish={onFinish}
className='form' className='form'
> >
<Item <Item
label="ID" label="ID"
name="id" name="id"
rules={[{ required: true, message: 'Пожалуйста, введите ID!' }]}
> >
<Input maxLength={12} placeholder="Максимальная длина: 12 символов" /> <Input disabled />
</Item> </Item>
<Item <Item
label="БИН организации" label="БИН организации"
name="bin" name="bin"
rules={[{ required: true, message: 'Пожалуйста, введите БИН организации!' }]} rules={[
{ required: true, message: 'Пожалуйста, введите БИН организации!' },
{ pattern: /^\d{12}$/, message: 'БИН должен состоять из 12 цифр!' }
]}
> >
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" /> <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
...@@ -86,12 +131,10 @@ const EditPage: React.FC = () => { ...@@ -86,12 +131,10 @@ const EditPage: 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, { useState, useEffect } from 'react'; import React, { useState, useEffect } 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, Modal } from 'antd'; import { Button, Pagination, Space, Spin, Table, Tag, Modal, message } from 'antd';
import type { TableProps } from 'antd'; import type { TableProps } from 'antd';
import './Homepage.css'; import './Homepage.css';
import { useGetOrganizationsQuery } from '../../features/api/apiSlice'; import { useGetOrganizationsQuery, useDeleteOrganizationMutation } from '../../features/api/apiSlice';
interface DataType { interface DataType {
id: number; id: number | string;
bin: string; bin: string;
organization_code: string; organization_code: string;
organization_name: string; organization_name: string;
...@@ -46,7 +46,7 @@ const columns: TableProps<DataType>['columns'] = [ ...@@ -46,7 +46,7 @@ const columns: TableProps<DataType>['columns'] = [
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 == '0' ? 'red' : record.status == '1' ? 'processing' : 'green';
return ( return (
<p> <p>
<Tag color={color} style={{ fontSize: '14px' }}> <Tag color={color} style={{ fontSize: '14px' }}>
...@@ -68,15 +68,22 @@ const columns: TableProps<DataType>['columns'] = [ ...@@ -68,15 +68,22 @@ const columns: TableProps<DataType>['columns'] = [
] ]
const ActionColumn: React.FC<{ data: any }> = ({ data }) => { const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState<boolean>(false);
const navigate = useNavigate(); const navigate = useNavigate();
const [deleteOrganization] = useDeleteOrganizationMutation();
const showDeleteModal = () => { const showDeleteModal = () => {
setOpen(true); setOpen(true);
}; };
const handleDeleteModalOk = () => { const handleDeleteModalOk = async () => {
try {
await deleteOrganization(data.id).unwrap();
message.success('Организация успешно удалена!');
setOpen(false); setOpen(false);
} catch (err) {
message.error('Произошла ошибка при удалении организации!');
}
}; };
const handleDeleteModalCancel = () => { const handleDeleteModalCancel = () => {
...@@ -84,7 +91,7 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => { ...@@ -84,7 +91,7 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
}; };
const handleEditClick = () => { const handleEditClick = () => {
navigate(`/edit/${data.id}`); navigate(`/edit/${(data.id).toString()}`);
} }
return ( return (
...@@ -110,9 +117,9 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => { ...@@ -110,9 +117,9 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
} }
const HomePage: React.FC = () => { const HomePage: React.FC = () => {
const [totalOrgNumber, setTotalOrgNumber] = useState(0); const [totalOrgNumber, setTotalOrgNumber] = useState<number>(0);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState<number>(1);
const ORG_NUMBER_PER_PAGE = 15; const ORG_NUMBER_PER_PAGE: number = 15;
const navigate = useNavigate(); const navigate = useNavigate();
const handleAddClick = () => { const handleAddClick = () => {
......
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