finished add, edit, delete functionality

parent 0a4a3a0d
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
interface Organization {
id: number;
id: number | string;
bin: string;
organization_code: string;
organization_name: string;
......@@ -34,13 +34,15 @@ export const apiSlice = createApi({
url: `/organizations/${id}`,
method: 'PUT',
body: rest,
})
}),
invalidatesTags: ["organizations"]
}),
deleteOrganization: builder.mutation<{ success: boolean; id: number }, number>({
query: (orgId) => ({
url: `/organizations/${orgId}`,
method: 'DELETE',
}),
invalidatesTags: ["organizations"],
}),
}),
});
......
......@@ -7,23 +7,20 @@ import './style.css';
const { Item } = Form;
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 navigate = useNavigate();
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 {
await addNewOrganization(values).unwrap();
await addNewOrganization(newValues).unwrap();
message.success('Организация успешно добавлена!');
console.log(values);
navigate('/');
......
import React from 'react';
import { Form, Input, Button, Select } from 'antd';
import { useNavigate } from 'react-router';
import React, { useEffect } from 'react';
import { Form, Input, Button, Select, message } from 'antd';
import { useNavigate, useParams } from 'react-router';
import { useGetOrganizationQuery, useEditOrganizationMutation } from '../../features/api/apiSlice';
import './style.css';
const { Item } = Form;
......@@ -8,69 +9,113 @@ const { Option } = Select;
const EditPage: React.FC = () => {
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 (
<div className="container">
<Form
form={form}
layout="vertical"
name="organization_form"
initialValues={{ remember: true }}
onFinish={onFinish}
className='form'
>
<Item
label="ID"
name="id"
rules={[{ required: true, message: 'Пожалуйста, введите ID!' }]}
>
<Input maxLength={12} placeholder="Максимальная длина: 12 символов" />
<Input disabled />
</Item>
<Item
label="БИН организации"
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
label="Код организации"
name="code"
rules={[{ required: true, message: 'Пожалуйста, введите код организации!' }]}
name="organization_code"
rules={[
{ required: true, message: 'Пожалуйста, введите код организации!' },
{ pattern: /^[a-zA-Z0-9-_]+$/, message: 'Код организации должен содержать только английские буквы, цифры, символы "-" и "_"' }
]}
>
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" />
<Input maxLength={128} />
</Item>
<Item
label="Наименование организации"
name="name"
name="organization_name"
rules={[{ required: true, message: 'Пожалуйста, введите наименование организации!' }]}
>
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" />
<Input maxLength={128} />
</Item>
<Item
label="Адрес системы/хост"
name="address"
name="host"
rules={[{ required: true, message: 'Пожалуйста, введите адрес системы/хост!' }]}
>
<Input maxLength={128} placeholder="Максимальная длина: 128 символов" />
<Input maxLength={128} />
</Item>
<Item
label="Логин"
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
label="Пароль"
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
......@@ -86,12 +131,10 @@ const EditPage: React.FC = () => {
</Item>
<div className='form-footer'>
<Item style={{}} className='form-footer-item'>
<Button type="default" style={{ marginRight: '8px' }}
onClick={() => navigate("/")}>
<Item className='form-footer-item'>
<Button type="default" style={{ marginRight: '8px' }} onClick={() => navigate("/")}>
Отмена
</Button>
<Button type="primary" htmlType="submit">
Сохранить
</Button>
......
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';
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 './Homepage.css';
import { useGetOrganizationsQuery } from '../../features/api/apiSlice';
import { useGetOrganizationsQuery, useDeleteOrganizationMutation } from '../../features/api/apiSlice';
interface DataType {
id: number;
id: number | string;
bin: string;
organization_code: string;
organization_name: string;
......@@ -46,7 +46,7 @@ const columns: TableProps<DataType>['columns'] = [
dataIndex: "status",
key: "status",
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 (
<p>
<Tag color={color} style={{ fontSize: '14px' }}>
......@@ -68,15 +68,22 @@ const columns: TableProps<DataType>['columns'] = [
]
const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
const [open, setOpen] = useState(false);
const [open, setOpen] = useState<boolean>(false);
const navigate = useNavigate();
const [deleteOrganization] = useDeleteOrganizationMutation();
const showDeleteModal = () => {
setOpen(true);
};
const handleDeleteModalOk = () => {
setOpen(false);
const handleDeleteModalOk = async () => {
try {
await deleteOrganization(data.id).unwrap();
message.success('Организация успешно удалена!');
setOpen(false);
} catch (err) {
message.error('Произошла ошибка при удалении организации!');
}
};
const handleDeleteModalCancel = () => {
......@@ -84,7 +91,7 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
};
const handleEditClick = () => {
navigate(`/edit/${data.id}`);
navigate(`/edit/${(data.id).toString()}`);
}
return (
......@@ -110,9 +117,9 @@ const ActionColumn: React.FC<{ data: any }> = ({ data }) => {
}
const HomePage: React.FC = () => {
const [totalOrgNumber, setTotalOrgNumber] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const ORG_NUMBER_PER_PAGE = 15;
const [totalOrgNumber, setTotalOrgNumber] = useState<number>(0);
const [currentPage, setCurrentPage] = useState<number>(1);
const ORG_NUMBER_PER_PAGE: number = 15;
const navigate = useNavigate();
const handleAddClick = () => {
......
......@@ -9,4 +9,4 @@ const store: Store = configureStore({
getDefaultMiddleware().concat(apiSlice.middleware),
})
export default store;
\ No newline at end of file
export default store;
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