Конечно! Вот финальные версии запрошенных файлов и пояснения.
1. backend/settings.py
Этот файл нужен для централизованного хранения настроек, которые подгружаются из .env.
# backend/settings.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
DATABASE_URL: str = "postgresql+asyncpg://user:password@localhost:5432/dbname"
INITIAL_EXCEL_PATH: str = "data/initial_structure.xlsx"
class Config:
env_file = ".env"
env_file_encoding = 'utf-8'
settings = Settings()
Примечания:
2. frontend/src/components/FileUploadForm.tsx
Форма для загрузки и скачивания Excel-файла с использованием MUI.
// frontend/src/components/FileUploadForm.tsx
import React, { useRef } from 'react';
import { Box, Button, Typography, Stack } from '@mui/material';
import UploadFileIcon from '@mui/icons-material/UploadFile';
import DownloadIcon from '@mui/icons-material/Download';
interface FileUploadFormProps {
onFileChange: (file: File | null) => void;
onUpload: () => void;
onDownloadTemplate: () => void;
selectedFile: File | null;
uploadStatus: string | null;
loading: boolean;
}
const FileUploadForm: React.FC<FileUploadFormProps> = ({
onFileChange,
onUpload,
onDownloadTemplate,
selectedFile,
uploadStatus,
loading,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFileInput = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
onFileChange(event.target.files[0]);
} else {
onFileChange(null);
}
};
return (
<Box sx={{ mb: 3 }}>
<Typography variant="h6" gutterBottom>
Загрузка структуры из Excel
</Typography>
<Stack direction="row" spacing={2} alignItems="center">
<Button
variant="contained"
component="label"
startIcon={<UploadFileIcon />}
disabled={loading}
>
Выбрать файл
<input
type="file"
accept=".xlsx"
hidden
ref={fileInputRef}
onChange={handleFileInput}
/>
</Button>
<Typography variant="body2">
{selectedFile ? selectedFile.name : 'Файл не выбран'}
</Typography>
<Button
variant="contained"
color="primary"
onClick={onUpload}
disabled={!selectedFile || loading}
>
Загрузить
</Button>
<Button
variant="outlined"
color="secondary"
startIcon={<DownloadIcon />}
onClick={onDownloadTemplate}
disabled={loading}
>
Скачать шаблон
</Button>
</Stack>
{uploadStatus && (
<Typography variant="body2" sx={{ mt: 1 }}>
{uploadStatus}
</Typography>
)}
</Box>
);
};
export default FileUploadForm;
3. frontend/src/OrgChartViewer.css
Стили для контейнера диаграммы.
/* frontend/src/OrgChartViewer.css */
.org-chart-container {
width: 100%;
height: 70vh;
border: 1px solid #ccc;
margin-top: 16px;
margin-bottom: 16px;
overflow: hidden;
background: #fafbfc;
border-radius: 8px;
position: relative;
}
.org-chart-container svg {
overflow: visible;
}
.org-chart-container text {
font-family: 'Roboto', 'Arial', sans-serif;
}
4. frontend/src/main.tsx
Точка входа приложения.
// frontend/src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import CssBaseline from '@mui/material/CssBaseline';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import './index.css';
const theme = createTheme({
palette: {
primary: {
main: '#1976d2',
},
secondary: {
main: '#9c27b0',
},
},
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
</React.StrictMode>
);
5. frontend/src/index.css
Глобальные стили.
/* frontend/src/index.css */
html, body, #root {
height: 100%;
margin: 0;
padding: 0;
font-family: 'Roboto', 'Arial', sans-serif;
background: #f5f6fa;
}
6. frontend/src/App.css
Общие стили приложения.
/* frontend/src/App.css */
.App {
max-width: 1200px;
margin: 0 auto;
padding: 24px;
background: #fff;
border-radius: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
min-height: 90vh;
}
h1 {
font-size: 2rem;
font-weight: 500;
margin-bottom: 24px;
color: #1976d2;
}
7. frontend/src/App.tsx
Главный компонент приложения, использующий MUI и все остальные компоненты.
// frontend/src/App.tsx
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Container, Typography, Alert } from '@mui/material';
import FileUploadForm from './components/FileUploadForm';
import OrgChartViewer from './components/OrgChartViewer';
import { OrganizationData, TreeNode } from './types';
import './App.css';
const API_BASE = 'http://localhost:8000';
function App() {
const [orgTreeData, setOrgTreeData] = useState<TreeNode | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [uploadStatus, setUploadStatus] = useState<string | null>(null);
// Преобразование данных с бэкенда в формат react-d3-tree
const mapBackendTreeToFrontendTree = (nodes: OrganizationData[]): TreeNode[] => {
return nodes.map(node => ({
name: node.name,
attributes: {
id: node.id,
ownershipShare: node.ownership_share,
},
children: node.children ? mapBackendTreeToFrontendTree(node.children) : [],
}));
};
const fetchData = async () => {
setLoading(true);
setError(null);
setOrgTreeData(null);
try {
const response = await axios.get<OrganizationData[]>(`${API_BASE}/organization/structure`);
if (response.data && response.data.length > 0) {
const formattedData = mapBackendTreeToFrontendTree(response.data);
setOrgTreeData(formattedData[0] || null);
} else {
setOrgTreeData(null);
}
} catch (err) {
setError('Не удалось загрузить структуру организации.');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
// --- Обработчики для загрузки файла ---
const handleFileChange = (file: File | null) => {
setSelectedFile(file);
setUploadStatus(null);
};
const handleUpload = async () => {
if (!selectedFile) {
setUploadStatus("Выберите файл для загрузки.");
return;
}
setLoading(true);
setUploadStatus("Загрузка...");
setError(null);
const formData = new FormData();
formData.append("file", selectedFile);
try {
const response = await axios.post(`${API_BASE}/organization/upload-structure`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
setUploadStatus(response.data.message || "Файл успешно загружен!");
setSelectedFile(null);
fetchData();
} catch (err: any) {
setUploadStatus(null);
if (err.response && err.response.data && err.response.data.detail) {
setError(`Ошибка загрузки: ${err.response.data.detail}`);
} else {
setError('Ошибка при загрузке файла.');
}
setLoading(false);
}
};
const handleDownloadTemplate = async () => {
try {
const response = await axios.get(`${API_BASE}/organization/download-template`, {
responseType: 'blob',
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'organization_structure_template.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (err) {
setError('Не удалось скачать шаблон файла.');
}
};
return (
<Container className="App">
<Typography variant="h4" component="h1" gutterBottom>
Структура Организации
</Typography>
<FileUploadForm
onFileChange={handleFileChange}
onUpload={handleUpload}
onDownloadTemplate={handleDownloadTemplate}
selectedFile={selectedFile}
uploadStatus={uploadStatus}
loading={loading}
/>
{error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
<OrgChartViewer treeData={orgTreeData} loading={loading} error={error} />
</Container>
);
}
export default App;
Теперь у вас полностью структурированный frontend на MUI с отдельными компонентами и всеми нужными стилями и файлами!
from fastapi import FastAPI, Depends, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
import os
from . import schemas, crud, database
from .settings import settings
def build_tree(organizations_list: List[schemas.OrganizationBase]) -> List[schemas.OrganizationNode]:
org_dict = {org.id: schemas.OrganizationNode(**org.model_dump(), children=[]) for org in organizations_list}
root_nodes = []
for org_id, org_node in org_dict.items():
parent_id = org_node.parent_id
if parent_id is None:
root_nodes.append(org_node)
else:
if parent_id in org_dict:
org_dict[parent_id].children.append(org_node)
else:
root_nodes.append(org_node)
return root_nodes
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
initial_data_inserted = await database.setup_database(crud.INITIAL_DATA)
if not os.path.exists(settings.INITIAL_EXCEL_PATH) or initial_data_inserted:
async with database.AsyncSessionLocal() as db:
current_organizations = await crud.get_all_organizations(db)
data_for_excel = [org.to_dict() for org in current_organizations]
if data_for_excel:
crud.generate_excel_from_data(data_for_excel, settings.INITIAL_EXCEL_PATH)
@app.get("/organization/structure", response_model=List[schemas.OrganizationNode])
async def get_organization_structure(db: AsyncSession = Depends(database.get_db)):
organizations = await crud.get_all_organizations(db)
organizations_base = [schemas.OrganizationBase.model_validate(org.to_dict()) for org in organizations]
if not organizations_base:
return []
tree_structure = build_tree(organizations_base)
return tree_structure
@app.post("/organization/upload-structure")
async def upload_organization_structure(file: UploadFile = File(...), db: AsyncSession = Depends(database.get_db)):
if not file.filename.endswith('.xlsx'):
raise HTTPException(status_code=400, detail="Неверный формат файла. Пожалуйста, загрузите .xlsx файл.")
organizations_data = crud.read_excel_file(file)
await crud.clear_and_insert_organizations(db, organizations_data)
return {"message": f"Данные успешно загружены из файла {file.filename}. Загружено {len(organizations_data)} записей."}
@app.get("/organization/download-template")
async def download_template(db: AsyncSession = Depends(database.get_db)):
current_organizations = await crud.get_all_organizations(db)
if not current_organizations:
crud.generate_excel_from_data([], settings.INITIAL_EXCEL_PATH + ".empty_template")
if os.path.exists(settings.INITIAL_EXCEL_PATH + ".empty_template"):
return FileResponse(
path=settings.INITIAL_EXCEL_PATH + ".empty_template",
filename="organization_structure_template_empty.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
else:
raise HTTPException(status_code=500, detail="Не удалось сгенерировать пустой шаблон файла.")
data_for_excel = [org.to_dict() for org in current_organizations]
import tempfile
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_file:
tmp_path = tmp_file.name
try:
crud.generate_excel_from_data(data_for_excel, tmp_path)
return FileResponse(
path=tmp_path,
filename="organization_structure_current.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
except Exception as e:
raise HTTPException(status_code=500, detail="Ошибка при генерации файла для скачивания.")
import pandas as pd
import shutil
import os
import tempfile
from typing import List, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, text
from fastapi import HTTPException, UploadFile
from . import models
from .settings import settings
# --- INITIAL DATA ---
INITIAL_DATA = [
{'id': 1, 'name': 'ООО "Главный Холдинг"', 'parent_id': None, 'ownership_share': 100.00},
{'id': 2, 'name': 'Дочка 1 (ИТ)', 'parent_id': 1, 'ownership_share': 85.00},
{'id': 3, 'name': 'Дочка 2 (Финансы)', 'parent_id': 1, 'ownership_share': 100.00},
{'id': 4, 'name': 'Дочка 3 (Производство)', 'parent_id': 1, 'ownership_share': 60.00},
{'id': 5, 'name': 'Внучка 1.1 (Разработка)', 'parent_id': 2, 'ownership_share': 70.00},
{'id': 6, 'name': 'Внучка 1.2 (Поддержка)', 'parent_id': 2, 'ownership_share': 95.00},
{'id': 7, 'name': 'Внучка 2.1 (Инвестиции)', 'parent_id': 3, 'ownership_share': 100.00},
{'id': 8, 'name': 'Внучка 3.1 (Сырье)', 'parent_id': 4, 'ownership_share': 55.00},
{'id': 9, 'name': 'Внучка 3.2 (Сборка)', 'parent_id': 4, 'ownership_share': 80.00},
{'id': 10, 'name': 'Правнучка 1.1.1 (Фронтенд)', 'parent_id': 5, 'ownership_share': 90.00},
{'id': 11, 'name': 'Правнучка 1.1.2 (Бэкенд)', 'parent_id': 5, 'ownership_share': 85.00},
{'id': 12, 'name': 'Правнучка 1.2.1 (Техподдержка)', 'parent_id': 6, 'ownership_share': 100.00},
{'id': 13, 'name': 'Правнучка 2.1.1 (Фонды)', 'parent_id': 7, 'ownership_share': 75.00},
{'id': 14, 'name': 'Правнучка 3.1.1 (Добыча)', 'parent_id': 8, 'ownership_share': 65.00},
{'id': 15, 'name': 'Правнучка 3.2.1 (Цех А)', 'parent_id': 9, 'ownership_share': 90.00},
{'id': 16, 'name': 'Праправнучка 1.1.1.1 (React)', 'parent_id': 10, 'ownership_share': 100.00},
{'id': 17, 'name': 'Праправнучка 1.1.2.1 (Django)', 'parent_id': 11, 'ownership_share': 95.00},
{'id': 18, 'name': 'Праправнучка 3.1.1.1 (Разведка)', 'parent_id': 14, 'ownership_share': 70.00},
{'id': 19, 'name': 'Праправнучка 3.2.1.1 (Линия 1)', 'parent_id': 15, 'ownership_share': 88.00},
{'id': 20, 'name': 'Праправнучка 3.2.1.2 (Линия 2)', 'parent_id': 15, 'ownership_share': 92.00},
{'id': 21, 'name': 'Дочка 4 (Логистика)', 'parent_id': 1, 'ownership_share': 75.00},
{'id': 22, 'name': 'Внучка 4.1 (Склад)', 'parent_id': 21, 'ownership_share': 80.00},
{'id': 23, 'name': 'Внучка 1.3 (Тестирование)', 'parent_id': 2, 'ownership_share': 80.00},
]
async def get_all_organizations(db: AsyncSession) -> List[models.Organization]:
result = await db.execute(select(models.Organization))
organizations = result.scalars().all()
return list(organizations)
async def clear_and_insert_organizations(db: AsyncSession, organizations_data: List[Dict[str, Any]]):
try:
await db.execute(text("TRUNCATE TABLE organizations RESTART IDENTITY CASCADE;"))
org_objects = [models.Organization(
id=data['id'],
name=data['name'],
parent_id=data.get('parent_id'),
ownership_share=data['ownership_share']
) for data in organizations_data]
db.add_all(org_objects)
await db.commit()
except Exception as e:
await db.rollback()
raise HTTPException(status_code=500, detail=f"Ошибка при вставке данных: {e}")
def validate_excel_dataframe(df: pd.DataFrame):
required_cols_en = ['Company ID', 'Company Name', 'Parent Company ID', 'Ownership Share by Parent (%)']
required_cols_ru = ['Уникальный ID компании', 'Название компании', 'ID родительской компании', 'Доля владения родительской компанией (%)']
actual_cols = df.columns.tolist()
col_mapping = {}
if all(col in actual_cols for col in required_cols_en):
col_mapping = {col_en: col_std for col_en, col_std in zip(required_cols_en, ['id', 'name', 'parent_id', 'ownership_share'])}
elif all(col in actual_cols for col in required_cols_ru):
col_mapping = {col_ru: col_std for col_ru, col_std in zip(required_cols_ru, ['id', 'name', 'parent_id', 'ownership_share'])}
else:
raise HTTPException(status_code=400, detail=f"Файл Excel должен содержать столбцы: {', '.join(required_cols_en)} или {', '.join(required_cols_ru)}")
df.rename(columns=col_mapping, inplace=True)
expected_cols = ['id', 'name', 'parent_id', 'ownership_share']
if not all(col in df.columns for col in expected_cols):
raise HTTPException(status_code=400, detail=f"Внутренняя ошибка валидации: не все столбцы найдены после переименования. Ожидаются: {', '.join(expected_cols)}")
# Проверка id
if not pd.api.types.is_numeric_dtype(df['id']):
raise HTTPException(status_code=400, detail="Столбец 'Company ID' должен быть числовым.")
if not df['id'].is_unique:
raise HTTPException(status_code=400, detail="Столбец 'Company ID' должен содержать уникальные значения.")
if (df['id'] <= 0).any():
raise HTTPException(status_code=400, detail="Столбец 'Company ID' должен содержать положительные значения.")
# Проверка name
if not pd.api.types.is_string_dtype(df['name']):
try:
df['name'] = df['name'].astype(str)
except Exception:
raise HTTPException(status_code=400, detail="Столбец 'Company Name' должен быть строковым.")
if df['name'].isnull().any() or (df['name'].str.strip() == '').any():
raise HTTPException(status_code=400, detail="Столбец 'Company Name' не должен содержать пустые значения.")
# Приведение parent_id с учетом id=1
def clean_parent_id(row):
x = row['parent_id']
id_ = int(row['id'])
# Для головной компании (id == 1)
if id_ == 1:
if pd.isna(x) or x == '' or str(x).strip() == '' or x == 0 or x == '0':
return None
if str(x).strip() == str(id_):
raise HTTPException(
status_code=400,
detail="Головная компания не может быть своим же родителем."
)
try:
int_x = int(float(x))
if int_x == 0:
return None
if int_x == id_:
raise HTTPException(
status_code=400,
detail="Головная компания не может быть своим же родителем."
)
return int_x
except Exception:
return None
# Для остальных компаний
else:
if pd.isna(x) or x == '' or str(x).strip() == '':
raise HTTPException(
status_code=400,
detail=f"Компания с id={id_} должна иметь заполненное поле 'Parent Company ID'."
)
try:
int_x = int(float(x))
if int_x == 0:
raise HTTPException(
status_code=400,
detail=f"Компания с id={id_} не может иметь 'Parent Company ID' равным 0."
)
if int_x == id_:
raise HTTPException(
status_code=400,
detail=f"Компания с id={id_} не может быть своим же родителем."
)
return int_x
except Exception:
raise HTTPException(
status_code=400,
detail=f"Некорректное значение в 'Parent Company ID' для компании с id={id_}."
)
df['parent_id'] = df.apply(clean_parent_id, axis=1)
# Проверка ownership_share
if not pd.api.types.is_numeric_dtype(df['ownership_share']):
raise HTTPException(status_code=400, detail="Столбец 'Ownership Share by Parent (%)' должен быть числовым.")
if not ((df['ownership_share'] >= 0) & (df['ownership_share'] <= 100)).all():
raise HTTPException(status_code=400, detail="Значения в столбце 'Ownership Share by Parent (%)' должны быть от 0 до 100.")
if df['ownership_share'].isnull().any():
raise HTTPException(status_code=400, detail="Столбец 'Ownership Share by Parent (%)' не должен содержать пустые значения.")
# Проверка parent_id на существование среди id (кроме None)
valid_ids = df['id'].tolist()
for idx, row in df.iterrows():
pid = row['parent_id']
if pid is not None and pid not in valid_ids:
raise HTTPException(
status_code=400,
detail=f"В 'Parent Company ID' указан несуществующий id ({pid}) для компании с id={row['id']}."
)
# Проверка наличия хотя бы одной головной компании
if not (df['parent_id'].isnull().any()):
raise HTTPException(status_code=400, detail="В структуре организации должен быть хотя бы один корневой узел (компания без родителя).")
return df[['id', 'name', 'parent_id', 'ownership_share']].to_dict('records')
def read_excel_file(file: UploadFile):
try:
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_file:
shutil.copyfileobj(file.file, tmp_file)
tmp_path = tmp_file.name
try:
df = pd.read_excel(tmp_path)
validated_data = validate_excel_dataframe(df)
return validated_data
except Exception as e:
if isinstance(e, HTTPException):
raise e
else:
raise HTTPException(status_code=400, detail=f"Ошибка чтения или валидации файла Excel: {e}")
finally:
os.unlink(tmp_path)
except Exception as e:
raise HTTPException(status_code=500, detail="Внутренняя ошибка сервера при обработке файла.")
def generate_excel_from_data(data: List[Dict[str, Any]], file_path: str):
try:
df = pd.DataFrame(data)
df = df[['id', 'name', 'parent_id', 'ownership_share']]
df.rename(columns={
'id': 'Company ID',
'name': 'Company Name',
'parent_id': 'Parent Company ID',
'ownership_share': 'Ownership Share by Parent (%)'
}, inplace=True)
df = df.fillna('')
os.makedirs(os.path.dirname(file_path), exist_ok=True)
df.to_excel(file_path, index=False)
except Exception as e:
pass # Можно логировать ошибку
async def reset_and_load_initial_data(db: AsyncSession):
await clear_and_insert_organizations(db, INITIAL_DATA)
from fastapi import FastAPI, Depends, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
import os
from . import schemas, crud, database
from .settings import settings
def build_tree(organizations_list: List[schemas.OrganizationBase]) -> List[schemas.OrganizationNode]:
org_dict = {org.id: schemas.OrganizationNode(**org.model_dump(), children=[]) for org in organizations_list}
root_nodes = []
for org_id, org_node in org_dict.items():
parent_id = org_node.parent_id
if parent_id is None:
root_nodes.append(org_node)
else:
if parent_id in org_dict:
org_dict[parent_id].children.append(org_node)
else:
root_nodes.append(org_node)
return root_nodes
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
await database.init_db()
async with database.AsyncSessionLocal() as db:
try:
organizations = await crud.get_all_organizations(db)
organizations_base = [schemas.OrganizationBase.model_validate(org.to_dict()) for org in organizations]
# Пробуем построить дерево
build_tree(organizations_base)
except Exception as e:
# Если не удалось построить дерево — сбрасываем БД и загружаем INITIAL_DATA
await crud.reset_and_load_initial_data(db)
# Генерируем Excel, если его нет
if not os.path.exists(settings.INITIAL_EXCEL_PATH):
current_organizations = await crud.get_all_organizations(db)
data_for_excel = [org.to_dict() for org in current_organizations]
if data_for_excel:
crud.generate_excel_from_data(data_for_excel, settings.INITIAL_EXCEL_PATH)
@app.get("/organization/structure", response_model=List[schemas.OrganizationNode])
async def get_organization_structure(db: AsyncSession = Depends(database.get_db)):
organizations = await crud.get_all_organizations(db)
organizations_base = [schemas.OrganizationBase.model_validate(org.to_dict()) for org in organizations]
if not organizations_base:
return []
tree_structure = build_tree(organizations_base)
return tree_structure
@app.post("/organization/upload-structure")
async def upload_organization_structure(file: UploadFile = File(...), db: AsyncSession = Depends(database.get_db)):
if not file.filename.endswith('.xlsx'):
raise HTTPException(status_code=400, detail="Неверный формат файла. Пожалуйста, загрузите .xlsx файл.")
organizations_data = crud.read_excel_file(file)
await crud.clear_and_insert_organizations(db, organizations_data)
return {"message": f"Данные успешно загружены из файла {file.filename}. Загружено {len(organizations_data)} записей."}
@app.get("/organization/download-template")
async def download_template(db: AsyncSession = Depends(database.get_db)):
current_organizations = await crud.get_all_organizations(db)
if not current_organizations:
crud.generate_excel_from_data([], settings.INITIAL_EXCEL_PATH + ".empty_template")
if os.path.exists(settings.INITIAL_EXCEL_PATH + ".empty_template"):
return FileResponse(
path=settings.INITIAL_EXCEL_PATH + ".empty_template",
filename="organization_structure_template_empty.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
else:
raise HTTPException(status_code=500, detail="Не удалось сгенерировать пустой шаблон файла.")
data_for_excel = [org.to_dict() for org in current_organizations]
import tempfile
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_file:
tmp_path = tmp_file.name
try:
crud.generate_excel_from_data(data_for_excel, tmp_path)
return FileResponse(
path=tmp_path,
filename="organization_structure_current.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
except Exception as e:
raise HTTPException(status_code=500, detail="Ошибка при генерации файла для скачивания.")
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Container, Typography, Alert, Button, Stack } from '@mui/material';
import FileUploadForm from './components/FileUploadForm';
import OrgChartViewer from './components/OrgChartViewer';
import { OrganizationData, TreeNode } from './types';
import DeleteIcon from '@mui/icons-material/Delete';
import './App.css';
const API_BASE = 'http://localhost:8000';
function App() {
const [orgTreeData, setOrgTreeData] = useState<TreeNode | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [uploadStatus, setUploadStatus] = useState<string | null>(null);
const [clearStatus, setClearStatus] = useState<string | null>(null);
const mapBackendTreeToFrontendTree = (nodes: OrganizationData[]): TreeNode[] => {
return nodes.map(node => ({
name: node.name,
attributes: {
id: node.id,
ownershipShare: node.ownership_share,
},
children: node.children ? mapBackendTreeToFrontendTree(node.children) : [],
}));
};
const fetchData = async () => {
setLoading(true);
setError(null);
setOrgTreeData(null);
try {
const response = await axios.get<OrganizationData[]>(`${API_BASE}/organization/structure`);
if (response.data && response.data.length > 0) {
const formattedData = mapBackendTreeToFrontendTree(response.data);
setOrgTreeData(formattedData[0] || null);
} else {
setOrgTreeData(null);
}
} catch (err) {
setError('Не удалось загрузить структуру организации.');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
const handleFileChange = (file: File | null) => {
setSelectedFile(file);
setUploadStatus(null);
};
const handleUpload = async () => {
if (!selectedFile) {
setUploadStatus("Выберите файл для загрузки.");
return;
}
setLoading(true);
setUploadStatus("Загрузка...");
setError(null);
const formData = new FormData();
formData.append("file", selectedFile);
try {
const response = await axios.post(`${API_BASE}/organization/upload-structure`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
setUploadStatus(response.data.message || "Файл успешно загружен!");
setSelectedFile(null);
fetchData();
} catch (err: any) {
setUploadStatus(null);
if (err.response && err.response.data && err.response.data.detail) {
setError(`Ошибка загрузки: ${err.response.data.detail}`);
} else {
setError('Ошибка при загрузке файла.');
}
setLoading(false);
}
};
const handleDownloadTemplate = async () => {
try {
const response = await axios.get(`${API_BASE}/organization/download-template`, {
responseType: 'blob',
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'organization_structure_template.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (err) {
setError('Не удалось скачать шаблон файла.');
}
};
const handleClear = async () => {
setLoading(true);
setClearStatus(null);
setError(null);
try {
const response = await axios.delete(`${API_BASE}/organization/clear`);
setClearStatus(response.data.message || "Данные успешно удалены.");
fetchData();
} catch (err: any) {
setClearStatus(null);
setError('Ошибка при удалении данных.');
setLoading(false);
}
};
return (
<Container className="App">
<Typography variant="h4" component="h1" gutterBottom>
Структура Организации
</Typography>
<FileUploadForm
onFileChange={handleFileChange}
onUpload={handleUpload}
onDownloadTemplate={handleDownloadTemplate}
selectedFile={selectedFile}
uploadStatus={uploadStatus}
loading={loading}
/>
<Stack direction="row" spacing={2} sx={{ mb: 2 }}>
<Button
variant="outlined"
color="error"
startIcon={<DeleteIcon />}
onClick={handleClear}
disabled={loading}
>
Очистить базу
</Button>
{clearStatus && <Typography variant="body2" color="success.main">{clearStatus}</Typography>}
</Stack>
{error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
<OrgChartViewer treeData={orgTreeData} loading={loading} error={error} />
</Container>
);
}
export default App;