Lade Daten der kpi für kennzahlen-tabelle #65

Merged
3019483 merged 1 commits from #56-data-fetching-part-2 into main 2025-06-14 10:33:43 +02:00
5 changed files with 377 additions and 321 deletions

View File

@ -1,9 +1,10 @@
import { Box, Tooltip, CircularProgress, Typography } from "@mui/material";
import DragIndicatorIcon from "@mui/icons-material/DragIndicator"; import DragIndicatorIcon from "@mui/icons-material/DragIndicator";
import { useEffect, useState } from "react"; import { Box, CircularProgress, Tooltip, Typography } from "@mui/material";
import { useNavigate } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import type { Kennzahl } from "../types/kpi"; import type { Kennzahl } from "../types/kpi";
import { getDisplayType } from "../types/kpi"; import { getDisplayType } from "../types/kpi";
import { fetchKennzahlen as fetchK } from "../util/api";
export function ConfigTable() { export function ConfigTable() {
const navigate = useNavigate(); const navigate = useNavigate();
@ -16,21 +17,18 @@ export function ConfigTable() {
const fetchKennzahlen = async () => { const fetchKennzahlen = async () => {
while (true) { while (true) {
try { try {
console.log('Fetching kennzahlen from API...'); console.log("Fetching kennzahlen from API...");
const response = await fetch(`http://localhost:5050/api/kpi_setting/`); const data = await fetchK();
if (!response.ok) { console.log("Fetched kennzahlen:", data);
throw new Error(`HTTP error! status: ${response.status}`); const sortedData = data.sort(
} (a: Kennzahl, b: Kennzahl) => a.position - b.position,
);
const data = await response.json();
console.log('Fetched kennzahlen:', data);
const sortedData = data.sort((a: Kennzahl, b: Kennzahl) => a.position - b.position);
setKennzahlen(sortedData); setKennzahlen(sortedData);
setLoading(false); setLoading(false);
break; break;
} catch (err) { } catch (err) {
console.error('Error fetching kennzahlen:', err); console.error("Error fetching kennzahlen:", err);
await new Promise(resolve => setTimeout(resolve, 2000)); await new Promise((resolve) => setTimeout(resolve, 2000));
} }
} }
}; };
@ -39,36 +37,35 @@ export function ConfigTable() {
}, []); }, []);
const handleToggleActive = async (id: number) => { const handleToggleActive = async (id: number) => {
const kennzahl = kennzahlen.find(k => k.id === id); const kennzahl = kennzahlen.find((k) => k.id === id);
if (!kennzahl) return; if (!kennzahl) return;
try { try {
const response = await fetch(`http://localhost:5050/api/kpi_setting/${id}`, { const response = await fetch(
method: 'PUT', `http://localhost:5050/api/kpi_setting/${id}`,
{
method: "PUT",
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
active: !kennzahl.active active: !kennzahl.active,
}), }),
}); },
);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
const updatedKennzahl = await response.json(); const updatedKennzahl = await response.json();
setKennzahlen(prev => setKennzahlen((prev) =>
prev.map(item => prev.map((item) => (item.id === id ? updatedKennzahl : item)),
item.id === id ? updatedKennzahl : item
)
); );
} catch (err) { } catch (err) {
console.error('Error toggling active status:', err); console.error("Error toggling active status:", err);
setKennzahlen(prev => setKennzahlen((prev) =>
prev.map(item => prev.map((item) => (item.id === id ? kennzahl : item)),
item.id === id ? kennzahl : item
)
); );
} }
}; };
@ -78,16 +75,19 @@ export function ConfigTable() {
try { try {
const positionUpdates = reorderedKennzahlen.map((kennzahl, index) => ({ const positionUpdates = reorderedKennzahlen.map((kennzahl, index) => ({
id: kennzahl.id, id: kennzahl.id,
position: index + 1 position: index + 1,
})); }));
const response = await fetch(`http://localhost:5050/api/kpi_setting/update-kpi-positions`, { const response = await fetch(
method: 'PUT', `http://localhost:5050/api/kpi_setting/update-kpi-positions`,
{
method: "PUT",
headers: { headers: {
'Content-Type': 'application/json', "Content-Type": "application/json",
}, },
body: JSON.stringify(positionUpdates), body: JSON.stringify(positionUpdates),
}); },
);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
@ -96,14 +96,17 @@ export function ConfigTable() {
const updatedKennzahlen = await response.json(); const updatedKennzahlen = await response.json();
setKennzahlen(updatedKennzahlen); setKennzahlen(updatedKennzahlen);
} catch (err) { } catch (err) {
console.error('Error updating positions:', err); console.error("Error updating positions:", err);
window.location.reload(); window.location.reload();
} finally { } finally {
setIsUpdatingPositions(false); setIsUpdatingPositions(false);
} }
}; };
const handleDragStart = (e: React.DragEvent<HTMLTableRowElement>, item: Kennzahl) => { const handleDragStart = (
e: React.DragEvent<HTMLTableRowElement>,
item: Kennzahl,
) => {
setDraggedItem(item); setDraggedItem(item);
e.dataTransfer.effectAllowed = "move"; e.dataTransfer.effectAllowed = "move";
}; };
@ -113,12 +116,19 @@ export function ConfigTable() {
e.dataTransfer.dropEffect = "move"; e.dataTransfer.dropEffect = "move";
}; };
const handleDrop = async (e: React.DragEvent<HTMLTableRowElement>, targetItem: Kennzahl) => { const handleDrop = async (
e: React.DragEvent<HTMLTableRowElement>,
targetItem: Kennzahl,
) => {
e.preventDefault(); e.preventDefault();
if (!draggedItem || draggedItem.id === targetItem.id) return; if (!draggedItem || draggedItem.id === targetItem.id) return;
const draggedIndex = kennzahlen.findIndex(item => item.id === draggedItem.id); const draggedIndex = kennzahlen.findIndex(
const targetIndex = kennzahlen.findIndex(item => item.id === targetItem.id); (item) => item.id === draggedItem.id,
);
const targetIndex = kennzahlen.findIndex(
(item) => item.id === targetItem.id,
);
const newKennzahlen = [...kennzahlen]; const newKennzahlen = [...kennzahlen];
const [removed] = newKennzahlen.splice(draggedIndex, 1); const [removed] = newKennzahlen.splice(draggedIndex, 1);
@ -139,20 +149,23 @@ export function ConfigTable() {
} }
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
if (target.tagName === 'INPUT' && (target as HTMLInputElement).type === 'checkbox') { if (
target.tagName === "INPUT" &&
(target as HTMLInputElement).type === "checkbox"
) {
return; return;
} }
if (target.closest('.drag-handle')) { if (target.closest(".drag-handle")) {
return; return;
} }
console.log('Navigating to detail page for KPI:', kennzahl); console.log("Navigating to detail page for KPI:", kennzahl);
console.log('KPI ID:', kennzahl.id); console.log("KPI ID:", kennzahl.id);
navigate({ navigate({
to: `/config-detail/$kpiId`, to: `/config-detail/$kpiId`,
params: { kpiId: kennzahl.id.toString() } params: { kpiId: kennzahl.id.toString() },
}); });
}; };
@ -166,7 +179,7 @@ export function ConfigTable() {
flexDirection="column" flexDirection="column"
mt={8} mt={8}
> >
<CircularProgress sx={{ color: '#383838', mb: 2 }} /> <CircularProgress sx={{ color: "#383838", mb: 2 }} />
<Typography>Lade Kennzahlen-Konfiguration...</Typography> <Typography>Lade Kennzahlen-Konfiguration...</Typography>
</Box> </Box>
); );
@ -182,47 +195,56 @@ export function ConfigTable() {
backgroundColor: "white", backgroundColor: "white",
overflow: "hidden", overflow: "hidden",
opacity: isUpdatingPositions ? 0.7 : 1, opacity: isUpdatingPositions ? 0.7 : 1,
pointerEvents: isUpdatingPositions ? 'none' : 'auto' pointerEvents: isUpdatingPositions ? "none" : "auto",
}} }}
> >
<table style={{ <table
style={{
width: "100%", width: "100%",
borderCollapse: "collapse" borderCollapse: "collapse",
}}> }}
>
<thead> <thead>
<tr style={{ backgroundColor: "#f5f5f5" }}> <tr style={{ backgroundColor: "#f5f5f5" }}>
<th style={{ <th
style={{
padding: "16px 12px", padding: "16px 12px",
textAlign: "left", textAlign: "left",
fontWeight: "bold", fontWeight: "bold",
width: "60px", width: "60px",
borderBottom: "1px solid #e0e0e0" borderBottom: "1px solid #e0e0e0",
}}> }}
</th> />
<th style={{ <th
style={{
padding: "16px 12px", padding: "16px 12px",
textAlign: "left", textAlign: "left",
fontWeight: "bold", fontWeight: "bold",
width: "80px", width: "80px",
borderBottom: "1px solid #e0e0e0" borderBottom: "1px solid #e0e0e0",
}}> }}
>
Aktiv Aktiv
</th> </th>
<th style={{ <th
style={{
padding: "16px 12px", padding: "16px 12px",
textAlign: "left", textAlign: "left",
fontWeight: "bold", fontWeight: "bold",
borderBottom: "1px solid #e0e0e0" borderBottom: "1px solid #e0e0e0",
}}> }}
>
Name Name
</th> </th>
<th style={{ <th
style={{
padding: "16px 12px", padding: "16px 12px",
textAlign: "left", textAlign: "left",
fontWeight: "bold", fontWeight: "bold",
width: "160px", width: "160px",
borderBottom: "1px solid #e0e0e0" borderBottom: "1px solid #e0e0e0",
}}> }}
>
Format Format
</th> </th>
</tr> </tr>
@ -240,8 +262,9 @@ export function ConfigTable() {
style={{ style={{
borderBottom: "1px solid #e0e0e0", borderBottom: "1px solid #e0e0e0",
cursor: isUpdatingPositions ? "default" : "pointer", cursor: isUpdatingPositions ? "default" : "pointer",
backgroundColor: draggedItem?.id === kennzahl.id ? "#f0f0f0" : "white", backgroundColor:
opacity: draggedItem?.id === kennzahl.id ? 0.5 : 1 draggedItem?.id === kennzahl.id ? "#f0f0f0" : "white",
opacity: draggedItem?.id === kennzahl.id ? 0.5 : 1,
}} }}
onMouseEnter={(e) => { onMouseEnter={(e) => {
if (!draggedItem && !isUpdatingPositions) { if (!draggedItem && !isUpdatingPositions) {
@ -259,8 +282,10 @@ export function ConfigTable() {
<Tooltip <Tooltip
title={ title={
<> <>
<b>Neuanordnung der Kennzahlen</b><br /> <b>Neuanordnung der Kennzahlen</b>
Hier können Sie die Kennzahlen nach Belieben per Drag and Drop neu anordnen. <br />
Hier können Sie die Kennzahlen nach Belieben per Drag
and Drop neu anordnen.
</> </>
} }
placement="left" placement="left"
@ -270,7 +295,9 @@ export function ConfigTable() {
sx={{ sx={{
color: isUpdatingPositions ? "#ccc" : "#999", color: isUpdatingPositions ? "#ccc" : "#999",
cursor: isUpdatingPositions ? "default" : "grab", cursor: isUpdatingPositions ? "default" : "grab",
"&:active": { cursor: isUpdatingPositions ? "default" : "grabbing" } "&:active": {
cursor: isUpdatingPositions ? "default" : "grabbing",
},
}} }}
/> />
</Tooltip> </Tooltip>
@ -286,30 +313,34 @@ export function ConfigTable() {
width: "18px", width: "18px",
height: "18px", height: "18px",
cursor: isUpdatingPositions ? "default" : "pointer", cursor: isUpdatingPositions ? "default" : "pointer",
accentColor: "#383838" accentColor: "#383838",
}} }}
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
/> />
</td> </td>
<td style={{ <td
style={{
padding: "12px", padding: "12px",
fontSize: "14px", fontSize: "14px",
color: "#333" color: "#333",
}}> }}
>
<span title={`Click to view details (ID: ${kennzahl.id})`}> <span title={`Click to view details (ID: ${kennzahl.id})`}>
{kennzahl.name} {kennzahl.name}
</span> </span>
</td> </td>
<td style={{ padding: "12px" }}> <td style={{ padding: "12px" }}>
<span style={{ <span
style={{
color: "#333", color: "#333",
padding: "4px 12px", padding: "4px 12px",
borderRadius: "16px", borderRadius: "16px",
fontSize: "12px", fontSize: "12px",
fontWeight: "500", fontWeight: "500",
border: "1px solid #ddd", border: "1px solid #ddd",
backgroundColor: "#f8f9fa" backgroundColor: "#f8f9fa",
}}> }}
>
{getDisplayType(kennzahl.type)} {getDisplayType(kennzahl.type)}
</span> </span>
</td> </td>

View File

@ -1,3 +1,4 @@
import type { Kennzahl } from "@/types/kpi";
import EditIcon from "@mui/icons-material/Edit"; import EditIcon from "@mui/icons-material/Edit";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline"; import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
import SearchIcon from "@mui/icons-material/Search"; import SearchIcon from "@mui/icons-material/Search";
@ -20,19 +21,10 @@ import { useState } from "react";
import type { KeyboardEvent } from "react"; import type { KeyboardEvent } from "react";
import { fetchPutKPI } from "../util/api"; import { fetchPutKPI } from "../util/api";
const SETTINGS = [
{ name: "Rendite", position: 1, active: true, mandatory: true },
{ name: "Ausschüttungsrendite", position: 2, active: true, mandatory: true },
{ name: "Laufzeit", position: 3, active: true, mandatory: true },
{ name: "Länderallokation", position: 4, active: true, mandatory: true },
{ name: "Managmentgebühren", position: 5, active: true, mandatory: true },
{ name: "Risikoprofil", position: 6, active: false, mandatory: true },
{ name: "Irgendwas", position: 7, active: true, mandatory: true },
];
interface KennzahlenTableProps { interface KennzahlenTableProps {
onPageClick?: (page: number) => void; onPageClick?: (page: number) => void;
pdfId: string; pdfId: string;
settings: Kennzahl[];
data: { data: {
[key: string]: { [key: string]: {
label: string; label: string;
@ -48,6 +40,7 @@ export default function KennzahlenTable({
onPageClick, onPageClick,
data, data,
pdfId, pdfId,
settings,
}: KennzahlenTableProps) { }: KennzahlenTableProps) {
const [editingIndex, setEditingIndex] = useState<string>(""); const [editingIndex, setEditingIndex] = useState<string>("");
const [editValue, setEditValue] = useState(""); const [editValue, setEditValue] = useState("");
@ -148,7 +141,8 @@ export default function KennzahlenTable({
</TableHead> </TableHead>
<TableBody> <TableBody>
{SETTINGS.filter((setting) => setting.active) {settings
.filter((setting) => setting.active)
.sort((a, b) => a.position - b.position) .sort((a, b) => a.position - b.position)
.map((setting) => ({ .map((setting) => ({
setting: setting, setting: setting,
@ -157,7 +151,8 @@ export default function KennzahlenTable({
.map((row) => { .map((row) => {
let borderColor = "transparent"; let borderColor = "transparent";
const hasMultipleValues = row.extractedValues.length > 1; const hasMultipleValues = row.extractedValues.length > 1;
const hasNoValue = row.setting.mandatory && const hasNoValue =
row.setting.mandatory &&
(row.extractedValues.length === 0 || (row.extractedValues.length === 0 ||
row.extractedValues.at(0)?.entity === ""); row.extractedValues.at(0)?.entity === "");
@ -188,7 +183,8 @@ export default function KennzahlenTable({
<Tooltip <Tooltip
title={ title={
<> <>
<b>Problem</b><br /> <b>Problem</b>
<br />
Mehrere Werte für die Kennzahl gefunden. Mehrere Werte für die Kennzahl gefunden.
</> </>
} }
@ -205,9 +201,9 @@ export default function KennzahlenTable({
justifyContent: "space-between", justifyContent: "space-between",
width: "100%", width: "100%",
cursor: "pointer", cursor: "pointer",
'&:hover': { "&:hover": {
backgroundColor: '#f5f5f5' backgroundColor: "#f5f5f5",
} },
}} }}
> >
<Box <Box

View File

@ -5,12 +5,15 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react"; import { useState } from "react";
import KennzahlenTable from "../components/KennzahlenTable"; import KennzahlenTable from "../components/KennzahlenTable";
import PDFViewer from "../components/pdfViewer"; import PDFViewer from "../components/pdfViewer";
import { kpiQueryOptions } from "../util/query"; import { kpiQueryOptions, settingsQueryOptions } from "../util/query";
export const Route = createFileRoute("/extractedResult/$pitchBook")({ export const Route = createFileRoute("/extractedResult/$pitchBook")({
component: ExtractedResultsPage, component: ExtractedResultsPage,
loader: ({ context: { queryClient }, params: { pitchBook } }) => loader: ({ context: { queryClient }, params: { pitchBook } }) =>
Promise.allSettled([
queryClient.ensureQueryData(kpiQueryOptions(pitchBook)), queryClient.ensureQueryData(kpiQueryOptions(pitchBook)),
queryClient.ensureQueryData(settingsQueryOptions()),
]),
}); });
function ExtractedResultsPage() { function ExtractedResultsPage() {
@ -26,6 +29,7 @@ function ExtractedResultsPage() {
}[status]; }[status];
const { data: kpi } = useSuspenseQuery(kpiQueryOptions(pitchBook)); const { data: kpi } = useSuspenseQuery(kpiQueryOptions(pitchBook));
const { data: settings } = useSuspenseQuery(settingsQueryOptions());
return ( return (
<Box p={4}> <Box p={4}>
@ -67,6 +71,7 @@ function ExtractedResultsPage() {
}} }}
> >
<KennzahlenTable <KennzahlenTable
settings={settings}
onPageClick={setCurrentPage} onPageClick={setCurrentPage}
data={kpi} data={kpi}
pdfId={pitchBook} pdfId={pitchBook}
@ -79,7 +84,7 @@ function ExtractedResultsPage() {
gap={3} gap={3}
sx={{ sx={{
width: "55%", width: "55%",
maxHeight: "95%" maxHeight: "95%",
}} }}
> >
<Paper <Paper
@ -93,7 +98,7 @@ function ExtractedResultsPage() {
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
overflow: "auto", overflow: "auto",
padding: 2 padding: 2,
}} }}
> >
<PDFViewer <PDFViewer
@ -102,7 +107,13 @@ function ExtractedResultsPage() {
onPageChange={setCurrentPage} onPageChange={setCurrentPage}
/> />
</Paper> </Paper>
<Box mt={2} display="flex" justifyContent="flex-end" gap={2} sx={{ flexShrink: 0 }}> <Box
mt={2}
display="flex"
justifyContent="flex-end"
gap={2}
sx={{ flexShrink: 0 }}
>
<Button variant="contained" sx={{ backgroundColor: "#383838" }}> <Button variant="contained" sx={{ backgroundColor: "#383838" }}>
<ContentPasteIcon sx={{ fontSize: 18, mr: 1 }} /> <ContentPasteIcon sx={{ fontSize: 18, mr: 1 }} />
Kennzahlenzeile kopieren Kennzahlenzeile kopieren

View File

@ -1,3 +1,5 @@
import type { Kennzahl } from "@/types/kpi";
export const fetchKPI = async ( export const fetchKPI = async (
pitchBookId: string, pitchBookId: string,
): Promise<{ ): Promise<{
@ -14,7 +16,7 @@ export const fetchKPI = async (
); );
const data = await response.json(); const data = await response.json();
return getKPI(data.kpi); return data.kpi ? getKPI(data.kpi) : {};
}; };
export const fetchPutKPI = async ( export const fetchPutKPI = async (
@ -95,3 +97,13 @@ export const flattenKPIArray = (kpi: {
}) => { }) => {
return Object.values(kpi).flat(); return Object.values(kpi).flat();
}; };
export const fetchKennzahlen = async (): Promise<Kennzahl[]> => {
const response = await fetch("http://localhost:5050/api/kpi_setting/");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
};

View File

@ -1,8 +1,14 @@
import { queryOptions } from "@tanstack/react-query"; import { queryOptions } from "@tanstack/react-query";
import { fetchKPI } from "./api"; import { fetchKPI, fetchKennzahlen } from "./api";
export const kpiQueryOptions = (pitchBookId: string) => export const kpiQueryOptions = (pitchBookId: string) =>
queryOptions({ queryOptions({
queryKey: ["pitchBookKPI", pitchBookId], queryKey: ["pitchBookKPI", pitchBookId],
queryFn: () => fetchKPI(pitchBookId), queryFn: () => fetchKPI(pitchBookId),
}); });
export const settingsQueryOptions = () =>
queryOptions({
queryKey: ["pitchBookSettings"],
queryFn: () => fetchKennzahlen(),
});