Merge remote-tracking branch 'origin/main' into neue-Kennzahl-spacy

pull/94/head
Abdulrahman Dabbagh 2025-06-19 15:33:32 +02:00
commit 09c314eea3
19 changed files with 578 additions and 117 deletions

View File

@ -17,48 +17,6 @@ OCR_SERVICE_URL = os.getenv("OCR_SERVICE_URL", "http://localhost:5051")
progress_per_id = {} # {id: {kpi: 0, pdf: 0}} progress_per_id = {} # {id: {kpi: 0, pdf: 0}}
storage_lock = threading.Lock() storage_lock = threading.Lock()
def process_pdf_async(app, file_id, file_data, filename):
with app.app_context():
try:
file_obj = BytesIO(file_data)
file_obj.name = filename
files = {"file": (filename, file_obj, "application/pdf")}
data = {"id": file_id}
response = requests.post(
f"{OCR_SERVICE_URL}/ocr", files=files, data=data, timeout=600
)
if response.status_code == 200:
response_data = response.json()
if "ocr_pdf" in response_data:
import base64
ocr_pdf_data = base64.b64decode(response_data["ocr_pdf"])
file_record = PitchBookModel.query.get(file_id)
if file_record:
file_record.file = ocr_pdf_data
db.session.commit()
print("[DEBUG] PDF updated in database:")
print("[DEBUG] - Successfully saved to database")
socketio.emit("progress", {"id": file_id, "progress": 50})
else:
socketio.emit(
"error", {"id": file_id, "message": "OCR processing failed"}
)
except Exception as e:
import traceback
traceback.print_exc()
socketio.emit(
"error", {"id": file_id, "message": f"Processing failed: {str(e)}"}
)
@pitch_book_controller.route("/", methods=["POST"]) @pitch_book_controller.route("/", methods=["POST"])
def upload_file(): def upload_file():
@ -88,6 +46,7 @@ def upload_file():
files = {"file": (uploaded_file.filename, file_data, "application/pdf")} files = {"file": (uploaded_file.filename, file_data, "application/pdf")}
data = {"id": new_file.id} data = {"id": new_file.id}
socketio.emit("progress", {"id": new_file.id, "progress": 5})
response = requests.post( response = requests.post(
f"{OCR_SERVICE_URL}/ocr", files=files, data=data, timeout=600 f"{OCR_SERVICE_URL}/ocr", files=files, data=data, timeout=600
) )

View File

@ -15,7 +15,7 @@ def extract_text_from_ocr_json():
pitchbook_id = json_data["id"] pitchbook_id = json_data["id"]
pages_data = json_data["extracted_text_per_page"] pages_data = json_data["extracted_text_per_page"]
entities_json = extract_with_exxeta(pages_data) entities_json = extract_with_exxeta(pages_data, pitchbook_id)
entities = json.loads(entities_json) if isinstance(entities_json, str) else entities_json entities = json.loads(entities_json) if isinstance(entities_json, str) else entities_json
validate_payload = { validate_payload = {
@ -39,4 +39,4 @@ def extract_text_from_ocr_json():
if __name__ == "__main__": if __name__ == "__main__":
app.run(host="0.0.0.0", port=5053, debug=True) app.run(host="0.0.0.0", port=5053, debug=True)

View File

@ -9,6 +9,7 @@ MODEL = "gpt-4o-mini"
EXXETA_BASE_URL = "https://ai.exxeta.com/api/v2/azure/openai" EXXETA_BASE_URL = "https://ai.exxeta.com/api/v2/azure/openai"
load_dotenv() load_dotenv()
EXXETA_API_KEY = os.getenv("API_KEY") EXXETA_API_KEY = os.getenv("API_KEY")
COORDINATOR_URL = os.getenv("COORDINATOR_URL", "http://localhost:5050")
MAX_RETRIES = 3 MAX_RETRIES = 3
TIMEOUT = 180 TIMEOUT = 180
@ -16,14 +17,20 @@ TIMEOUT = 180
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def extract_with_exxeta(pages_json): def extract_with_exxeta(pages_json, pitchbook_id):
results = [] results = []
if not EXXETA_API_KEY: if not EXXETA_API_KEY:
logger.warning("EXXETA_API_KEY nicht gesetzt. Rückgabe eines leeren JSON.") logger.warning("EXXETA_API_KEY nicht gesetzt. Rückgabe eines leeren JSON.")
return json.dumps(results, indent=2, ensure_ascii=False) return json.dumps(results, indent=2, ensure_ascii=False)
i = 0
for page_data in pages_json: for page_data in pages_json:
i += 1
if i % 8 == 0:
requests.post(COORDINATOR_URL + "/api/progress", json={"id": pitchbook_id, "progress": 35 + 60/len(pages_json)*i})
page_num = page_data.get("page") page_num = page_data.get("page")
page_data.get("page") page_data.get("page")
text = page_data.get("text", "") text = page_data.get("text", "")
@ -57,7 +64,7 @@ def extract_with_exxeta(pages_json):
prompt = ( prompt = (
"Bitte extrahiere relevante Fondskennzahlen aus dem folgenden Pitchbook-Text. " "Bitte extrahiere relevante Fondskennzahlen aus dem folgenden Pitchbook-Text. "
"Analysiere den Text sorgfältig, um **nur exakt benannte und relevante Werte** zu extrahieren.\n\n" "Analysiere den Text sorgfältig, um **nur exakt benannte und relevante Werte** zu extrahieren.\n\n"
"ZU EXTRAHIERENDE KENNZAHLEN (immer exakt wie unten angegeben):\n" "ZU EXTRAHIERENDE KENNZAHLEN (immer exakt wie unten angegeben):\n"
"- FONDSNAME\n" "- FONDSNAME\n"
"- FONDSMANAGER\n" "- FONDSMANAGER\n"
@ -74,14 +81,14 @@ def extract_with_exxeta(pages_json):
"- MANAGEMENTGEBÜHREN (ggf. mit Staffelung und Bezug auf NAV/GAV)\n" "- MANAGEMENTGEBÜHREN (ggf. mit Staffelung und Bezug auf NAV/GAV)\n"
"- SEKTORENALLOKATION (z. B. BÜRO, LOGISTIK, WOHNEN... inkl. %-Angaben)\n" "- SEKTORENALLOKATION (z. B. BÜRO, LOGISTIK, WOHNEN... inkl. %-Angaben)\n"
"- LÄNDERALLOKATION (z. B. DEUTSCHLAND, FRANKREICH, etc. inkl. %-Angaben)\n\n" "- LÄNDERALLOKATION (z. B. DEUTSCHLAND, FRANKREICH, etc. inkl. %-Angaben)\n\n"
"WICHTIG:\n" "WICHTIG:\n"
"- Gib **nur eine Entität pro Kennzahl** an - keine Listen oder Interpretationen.\n" "- Gib **nur eine Entität pro Kennzahl** an - keine Listen oder Interpretationen.\n"
"- Wenn mehrere Varianten genannt werden (z. B. \"Core und Core+\"), gib sie im Originalformat als **eine entity** an.\n" "- Wenn mehrere Varianten genannt werden (z. B. \"Core und Core+\"), gib sie im Originalformat als **eine entity** an.\n"
"- **Keine Vermutungen oder Ergänzungen**. Wenn keine Information enthalten ist, gib die Kennzahl **nicht aus**.\n" "- **Keine Vermutungen oder Ergänzungen**. Wenn keine Information enthalten ist, gib die Kennzahl **nicht aus**.\n"
"- Extrahiere **nur wörtlich vorkommende Inhalte** (keine Berechnungen, keine Zusammenfassungen).\n" "- Extrahiere **nur wörtlich vorkommende Inhalte** (keine Berechnungen, keine Zusammenfassungen).\n"
"- Jeder gefundene Wert muss einem der obigen Label **eindeutig zuordenbar** sein.\n\n" "- Jeder gefundene Wert muss einem der obigen Label **eindeutig zuordenbar** sein.\n\n"
"FORMAT:\n" "FORMAT:\n"
"Antworte als **reines JSON-Array** mit folgendem Format:\n" "Antworte als **reines JSON-Array** mit folgendem Format:\n"
"[\n" "[\n"
@ -92,7 +99,7 @@ def extract_with_exxeta(pages_json):
" },\n" " },\n"
" ...\n" " ...\n"
"]\n\n" "]\n\n"
f"Falls keine Kennzahl enthalten ist, gib ein leeres Array [] zurück.\n\n" f"Falls keine Kennzahl enthalten ist, gib ein leeres Array [] zurück.\n\n"
f"Nur JSON-Antwort - keine Kommentare, keine Erklärungen, kein Text außerhalb des JSON.\n\n" f"Nur JSON-Antwort - keine Kommentare, keine Erklärungen, kein Text außerhalb des JSON.\n\n"
f"TEXT:\n{text}" f"TEXT:\n{text}"
@ -144,4 +151,6 @@ def extract_with_exxeta(pages_json):
if attempt == MAX_RETRIES: if attempt == MAX_RETRIES:
results.extend([]) results.extend([])
return json.dumps(results, indent=2, ensure_ascii=False)
requests.post(COORDINATOR_URL + "/api/progress", json={"id": pitchbook_id, "progress": 95})
return json.dumps(results, indent=2, ensure_ascii=False)

View File

@ -41,6 +41,7 @@ def convert_pdf_async(temp_path, pitchbook_id):
logger.info("Sending payload to EXXETA and SPACY services") logger.info("Sending payload to EXXETA and SPACY services")
requests.post(COORDINATOR_URL + "/api/progress", json={"id": pitchbook_id, "progress": 35})
try: try:
exxeta_response = requests.post(EXXETA_URL, json=payload, timeout=600) exxeta_response = requests.post(EXXETA_URL, json=payload, timeout=600)
logger.info(f"EXXETA response: {exxeta_response.status_code}") logger.info(f"EXXETA response: {exxeta_response.status_code}")
@ -59,9 +60,8 @@ def convert_pdf_async(temp_path, pitchbook_id):
headers = {} headers = {}
try: try:
requests.put(f"{COORDINATOR_URL}/api/pitch_book/{pitchbook_id}", files=files, timeout=600, headers=headers)
requests.post(COORDINATOR_URL + "/api/progress", json={"id": pitchbook_id, "progress": 50}, timeout=600) requests.put(f"{COORDINATOR_URL}/api/pitch_book/{pitchbook_id}", files=files, timeout=600, headers=headers)
logger.info("COORDINATOR response: Progress + File updated") logger.info("COORDINATOR response: Progress + File updated")
except Exception as e: except Exception as e:
logger.error(f"Error calling COORDINATOR: {e}") logger.error(f"Error calling COORDINATOR: {e}")

View File

@ -10,7 +10,7 @@ import json
app = Flask(__name__) app = Flask(__name__)
load_dotenv() load_dotenv()
coordinator_url = os.getenv("COORDINATOR_URL", "http://localhost:5000") COORDINATOR_URL = os.getenv("COORDINATOR_URL", "http://localhost:5000")
# todo add persistence layer # todo add persistence layer
data_storage = {} # {id: {spacy_data: [], exxeta_data: []}} data_storage = {} # {id: {spacy_data: [], exxeta_data: []}}
@ -19,7 +19,7 @@ storage_lock = threading.Lock()
def send_to_coordinator_service(processed_data, request_id): def send_to_coordinator_service(processed_data, request_id):
if not coordinator_url: if not COORDINATOR_URL:
print("Not processed, missing url", processed_data) print("Not processed, missing url", processed_data)
return return
@ -28,7 +28,7 @@ def send_to_coordinator_service(processed_data, request_id):
"kpi": json.dumps(processed_data), "kpi": json.dumps(processed_data),
} }
requests.put( requests.put(
coordinator_url + "/api/pitch_book/" + str(request_id), COORDINATOR_URL + "/api/pitch_book/" + str(request_id),
data=payload, data=payload,
) )
print(f"Result PitchBook {request_id} sent to coordinator") print(f"Result PitchBook {request_id} sent to coordinator")
@ -40,6 +40,7 @@ def send_to_coordinator_service(processed_data, request_id):
def process_data_async(request_id, spacy_data, exxeta_data): def process_data_async(request_id, spacy_data, exxeta_data):
try: try:
requests.post(COORDINATOR_URL + "/api/progress", json={"id": request_id, "progress": 95})
print(f"Start asynchronous processing for PitchBook: {request_id}") print(f"Start asynchronous processing for PitchBook: {request_id}")
# Perform merge # Perform merge

View File

@ -47,6 +47,7 @@ services:
environment: environment:
- EXXETA_SERVICE_URL=http://exxeta:5000/extract - EXXETA_SERVICE_URL=http://exxeta:5000/extract
- SPACY_SERVICE_URL=http://spacy:5052/extract - SPACY_SERVICE_URL=http://spacy:5052/extract
- COORDINATOR_URL=http://coordinator:5000
ports: ports:
- 5051:5000 - 5051:5000
@ -68,6 +69,7 @@ services:
- .env - .env
environment: environment:
- VALIDATE_SERVICE_URL=http://validate:5000/validate - VALIDATE_SERVICE_URL=http://validate:5000/validate
- COORDINATOR_URL=http://coordinator:5000
ports: ports:
- 5053:5000 - 5053:5000

View File

@ -7,7 +7,11 @@ import { getDisplayType } from "../types/kpi";
import { fetchKennzahlen as fetchK } from "../util/api"; import { fetchKennzahlen as fetchK } from "../util/api";
import { API_HOST } from "../util/api"; import { API_HOST } from "../util/api";
export function ConfigTable() { type ConfigTableProps = {
from?: string;
};
export function ConfigTable({ from }: ConfigTableProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const [kennzahlen, setKennzahlen] = useState<Kennzahl[]>([]); const [kennzahlen, setKennzahlen] = useState<Kennzahl[]>([]);
const [draggedItem, setDraggedItem] = useState<Kennzahl | null>(null); const [draggedItem, setDraggedItem] = useState<Kennzahl | null>(null);
@ -161,12 +165,10 @@ export function ConfigTable() {
return; return;
} }
console.log("Navigating to detail page for KPI:", kennzahl);
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() },
search: from ? { from } : undefined,
}); });
}; };

View File

@ -34,6 +34,7 @@ interface KennzahlenTableProps {
source: string; source: string;
}[]; }[];
}; };
from?: string;
} }
export default function KennzahlenTable({ export default function KennzahlenTable({
@ -41,10 +42,11 @@ export default function KennzahlenTable({
data, data,
pdfId, pdfId,
settings, settings,
from
}: KennzahlenTableProps) { }: KennzahlenTableProps) {
const [editingIndex, setEditingIndex] = useState<string>(""); const [editingIndex, setEditingIndex] = useState<string>("");
const [editValue, setEditValue] = useState(""); const [editValue, setEditValue] = useState("");
const navigate = useNavigate({ from: "/extractedResult/$pitchBook" }); const navigate = useNavigate();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -120,6 +122,7 @@ export default function KennzahlenTable({
pitchBook: pdfId, pitchBook: pdfId,
kpi: settingName, kpi: settingName,
}, },
search: { from: from ?? undefined },
}); });
}; };
@ -297,18 +300,22 @@ export default function KennzahlenTable({
)} )}
</TableCell> </TableCell>
<TableCell align="center"> <TableCell align="center">
<Link {(row.extractedValues.at(0)?.page ?? 0) > 0 ? (
component="button" <Link
onClick={() => component="button"
onPageClick?.( onClick={() => {
Number(row.extractedValues.at(0)?.page), const extractedValue = row.extractedValues.at(0);
row.extractedValues.at(0)?.entity || "", if (extractedValue?.page && extractedValue.page > 0) {
) onPageClick?.(Number(extractedValue.page), extractedValue.entity || "");
} }
sx={{ cursor: "pointer" }} }}
> sx={{ cursor: "pointer" }}
{row.extractedValues.at(0)?.page} >
</Link> {row.extractedValues.at(0)?.page}
</Link>
) : (
""
)}
</TableCell> </TableCell>
</TableRow> </TableRow>
); );

View File

@ -0,0 +1,186 @@
import { Box, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography, CircularProgress, Chip } from "@mui/material";
import { useSuspenseQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { pitchBooksQueryOptions } from "../util/query";
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty';
interface PitchBook {
id: number;
filename: string;
created_at: string;
kpi?: string | {
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
};
status?: 'processing' | 'completed';
}
export function PitchBooksTable() {
const navigate = useNavigate();
const { data: pitchBooks, isLoading } = useSuspenseQuery(pitchBooksQueryOptions());
const handleRowClick = (pitchBookId: number) => {
navigate({
to: "/extractedResult/$pitchBook",
params: { pitchBook: pitchBookId.toString() },
search: { from: "overview" }
});
};
const getKPIValue = (pitchBook: PitchBook, fieldName: string): string => {
if (!pitchBook.kpi || typeof pitchBook.kpi === 'string') {
try {
const parsedKPI = JSON.parse(pitchBook.kpi as string);
// Convert array to object format if needed
const kpiObj = Array.isArray(parsedKPI) ?
parsedKPI.reduce((acc: any, item: any) => {
if (!acc[item.label]) acc[item.label] = [];
acc[item.label].push(item);
return acc;
}, {}) : parsedKPI;
return kpiObj[fieldName]?.[0]?.entity || 'N/A';
} catch {
return 'N/A';
}
}
return (pitchBook.kpi as any)[fieldName]?.[0]?.entity || 'N/A';
};
const getStatus = (pitchBook: PitchBook) => {
if (pitchBook.kpi &&
((typeof pitchBook.kpi === 'string' && pitchBook.kpi !== '{}') ||
(typeof pitchBook.kpi === 'object' && Object.keys(pitchBook.kpi).length > 0))) {
return 'completed';
}
return 'processing';
};
if (isLoading) {
return (
<Box display="flex" justifyContent="center" alignItems="center" height="400px">
<CircularProgress sx={{ color: "#383838" }} />
</Box>
);
}
return (
<TableContainer
component={Paper}
sx={{
width: "85%",
maxWidth: 1200,
boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
}}
>
<Table>
<TableHead>
<TableRow sx={{ backgroundColor: "#f5f5f5" }}>
<TableCell sx={{ width: "60px" }}></TableCell>
<TableCell sx={{ fontWeight: "bold" }}>Fondsname</TableCell>
<TableCell sx={{ fontWeight: "bold" }}>Fondsmanager</TableCell>
<TableCell sx={{ fontWeight: "bold" }}>Dateiname</TableCell>
<TableCell sx={{ fontWeight: "bold", width: "120px" }}>Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{pitchBooks.map((pitchBook: PitchBook) => {
const status = getStatus(pitchBook);
const fundName = getKPIValue(pitchBook, 'FONDSNAME') ||
getKPIValue(pitchBook, 'FUND_NAME') ||
getKPIValue(pitchBook, 'NAME');
const manager = getKPIValue(pitchBook, 'FONDSMANAGER') ||
getKPIValue(pitchBook, 'MANAGER') ||
getKPIValue(pitchBook, 'PORTFOLIO_MANAGER');
return (
<TableRow
key={pitchBook.id}
onClick={() => handleRowClick(pitchBook.id)}
sx={{
cursor: "pointer",
"&:hover": {
backgroundColor: "#f9f9f9",
},
}}
>
<TableCell>
<Box
sx={{
width: 40,
height: 50,
backgroundColor: "#f0f0f0",
borderRadius: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
border: "1px solid #e0e0e0",
}}
>
<PictureAsPdfIcon fontSize="small" sx={{ color: "#666" }} />
</Box>
</TableCell>
<TableCell>
<Typography variant="body2" fontWeight="medium">
{fundName}
</Typography>
</TableCell>
<TableCell>{manager}</TableCell>
<TableCell>
<Typography variant="body2" color="text.secondary" fontSize="0.875rem">
{pitchBook.filename}
</Typography>
</TableCell>
<TableCell>
{status === 'completed' ? (
<Chip
icon={<CheckCircleIcon />}
label="Abgeschlossen"
size="small"
sx={{
backgroundColor: "#e8f5e9",
color: "#2e7d32",
"& .MuiChip-icon": {
color: "#2e7d32",
},
}}
/>
) : (
<Chip
icon={<HourglassEmptyIcon />}
label="In Bearbeitung"
size="small"
sx={{
backgroundColor: "#fff3e0",
color: "#e65100",
"& .MuiChip-icon": {
color: "#e65100",
},
}}
/>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
{pitchBooks.length === 0 && (
<Box p={4} textAlign="center">
<Typography color="text.secondary">
Keine Pitch Books vorhanden
</Typography>
</Box>
)}
</TableContainer>
);
}

View File

@ -7,8 +7,6 @@ import { socket } from "../socket";
import { CircularProgressWithLabel } from "./CircularProgressWithLabel"; import { CircularProgressWithLabel } from "./CircularProgressWithLabel";
import { API_HOST } from "../util/api"; import { API_HOST } from "../util/api";
const PROGRESS = true;
export default function UploadPage() { export default function UploadPage() {
const [files, setFiles] = useState<File[]>([]); const [files, setFiles] = useState<File[]>([]);
const [pageId, setPageId] = useState<string | null>(null); const [pageId, setPageId] = useState<string | null>(null);
@ -28,17 +26,11 @@ export default function UploadPage() {
console.log("File uploaded successfully"); console.log("File uploaded successfully");
const data = await response.json(); const data = await response.json();
setPageId(data.id.toString()); setPageId(data.id.toString());
setLoadingState(0); setLoadingState(5);
!PROGRESS &&
navigate({
to: "/extractedResult/$pitchBook",
params: { pitchBook: data.id.toString() },
});
} else { } else {
console.error("Failed to upload file"); console.error("Failed to upload file");
} }
}, [files, navigate]); }, [files]);
const onConnection = useCallback(() => { const onConnection = useCallback(() => {
console.log("connected"); console.log("connected");
@ -80,18 +72,16 @@ export default function UploadPage() {
return ( return (
<> <>
{PROGRESS && ( <Backdrop
<Backdrop sx={(theme) => ({ color: "#fff", zIndex: theme.zIndex.drawer + 1 })}
sx={(theme) => ({ color: "#fff", zIndex: theme.zIndex.drawer + 1 })} open={pageId !== null && loadingState !== null && loadingState < 100}
open={pageId !== null && loadingState !== null && loadingState < 100} >
> <CircularProgressWithLabel
<CircularProgressWithLabel color="inherit"
color="inherit" value={loadingState || 0}
value={loadingState || 0} size={60}
size={60} />
/> </Backdrop>
</Backdrop>
)}
<Box <Box
display="flex" display="flex"
flexDirection="column" flexDirection="column"
@ -179,7 +169,20 @@ export default function UploadPage() {
> >
Kennzahlen extrahieren Kennzahlen extrahieren
</Button> </Button>
<Button
variant="contained"
sx={{
position: "absolute",
bottom: 32,
left: 32,
backgroundColor: "#383838",
"&:hover": { backgroundColor: "#2e2e2e" },
}}
onClick={() => navigate({ to: "/pitchbooks" })}
>
Alle Pitch Books anzeigen
</Button>
</Box> </Box>
</> </>
); );
} }

View File

@ -11,6 +11,7 @@
// Import Routes // Import Routes
import { Route as rootRoute } from './routes/__root' import { Route as rootRoute } from './routes/__root'
import { Route as PitchbooksImport } from './routes/pitchbooks'
import { Route as ConfigAddImport } from './routes/config-add' import { Route as ConfigAddImport } from './routes/config-add'
import { Route as ConfigImport } from './routes/config' import { Route as ConfigImport } from './routes/config'
import { Route as IndexImport } from './routes/index' import { Route as IndexImport } from './routes/index'
@ -20,6 +21,12 @@ import { Route as ExtractedResultPitchBookKpiImport } from './routes/extractedRe
// Create/Update Routes // Create/Update Routes
const PitchbooksRoute = PitchbooksImport.update({
id: '/pitchbooks',
path: '/pitchbooks',
getParentRoute: () => rootRoute,
} as any)
const ConfigAddRoute = ConfigAddImport.update({ const ConfigAddRoute = ConfigAddImport.update({
id: '/config-add', id: '/config-add',
path: '/config-add', path: '/config-add',
@ -82,6 +89,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ConfigAddImport preLoaderRoute: typeof ConfigAddImport
parentRoute: typeof rootRoute parentRoute: typeof rootRoute
} }
'/pitchbooks': {
id: '/pitchbooks'
path: '/pitchbooks'
fullPath: '/pitchbooks'
preLoaderRoute: typeof PitchbooksImport
parentRoute: typeof rootRoute
}
'/config-detail/$kpiId': { '/config-detail/$kpiId': {
id: '/config-detail/$kpiId' id: '/config-detail/$kpiId'
path: '/config-detail/$kpiId' path: '/config-detail/$kpiId'
@ -112,6 +126,7 @@ export interface FileRoutesByFullPath {
'/': typeof IndexRoute '/': typeof IndexRoute
'/config': typeof ConfigRoute '/config': typeof ConfigRoute
'/config-add': typeof ConfigAddRoute '/config-add': typeof ConfigAddRoute
'/pitchbooks': typeof PitchbooksRoute
'/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute '/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute
'/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute '/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute
'/extractedResult/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute '/extractedResult/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute
@ -121,6 +136,7 @@ export interface FileRoutesByTo {
'/': typeof IndexRoute '/': typeof IndexRoute
'/config': typeof ConfigRoute '/config': typeof ConfigRoute
'/config-add': typeof ConfigAddRoute '/config-add': typeof ConfigAddRoute
'/pitchbooks': typeof PitchbooksRoute
'/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute '/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute
'/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute '/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute
'/extractedResult/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute '/extractedResult/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute
@ -131,6 +147,7 @@ export interface FileRoutesById {
'/': typeof IndexRoute '/': typeof IndexRoute
'/config': typeof ConfigRoute '/config': typeof ConfigRoute
'/config-add': typeof ConfigAddRoute '/config-add': typeof ConfigAddRoute
'/pitchbooks': typeof PitchbooksRoute
'/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute '/config-detail/$kpiId': typeof ConfigDetailKpiIdRoute
'/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute '/extractedResult/$pitchBook': typeof ExtractedResultPitchBookRoute
'/extractedResult_/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute '/extractedResult_/$pitchBook/$kpi': typeof ExtractedResultPitchBookKpiRoute
@ -142,6 +159,7 @@ export interface FileRouteTypes {
| '/' | '/'
| '/config' | '/config'
| '/config-add' | '/config-add'
| '/pitchbooks'
| '/config-detail/$kpiId' | '/config-detail/$kpiId'
| '/extractedResult/$pitchBook' | '/extractedResult/$pitchBook'
| '/extractedResult/$pitchBook/$kpi' | '/extractedResult/$pitchBook/$kpi'
@ -150,6 +168,7 @@ export interface FileRouteTypes {
| '/' | '/'
| '/config' | '/config'
| '/config-add' | '/config-add'
| '/pitchbooks'
| '/config-detail/$kpiId' | '/config-detail/$kpiId'
| '/extractedResult/$pitchBook' | '/extractedResult/$pitchBook'
| '/extractedResult/$pitchBook/$kpi' | '/extractedResult/$pitchBook/$kpi'
@ -158,6 +177,7 @@ export interface FileRouteTypes {
| '/' | '/'
| '/config' | '/config'
| '/config-add' | '/config-add'
| '/pitchbooks'
| '/config-detail/$kpiId' | '/config-detail/$kpiId'
| '/extractedResult/$pitchBook' | '/extractedResult/$pitchBook'
| '/extractedResult_/$pitchBook/$kpi' | '/extractedResult_/$pitchBook/$kpi'
@ -168,6 +188,7 @@ export interface RootRouteChildren {
IndexRoute: typeof IndexRoute IndexRoute: typeof IndexRoute
ConfigRoute: typeof ConfigRoute ConfigRoute: typeof ConfigRoute
ConfigAddRoute: typeof ConfigAddRoute ConfigAddRoute: typeof ConfigAddRoute
PitchbooksRoute: typeof PitchbooksRoute
ConfigDetailKpiIdRoute: typeof ConfigDetailKpiIdRoute ConfigDetailKpiIdRoute: typeof ConfigDetailKpiIdRoute
ExtractedResultPitchBookRoute: typeof ExtractedResultPitchBookRoute ExtractedResultPitchBookRoute: typeof ExtractedResultPitchBookRoute
ExtractedResultPitchBookKpiRoute: typeof ExtractedResultPitchBookKpiRoute ExtractedResultPitchBookKpiRoute: typeof ExtractedResultPitchBookKpiRoute
@ -177,6 +198,7 @@ const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute, IndexRoute: IndexRoute,
ConfigRoute: ConfigRoute, ConfigRoute: ConfigRoute,
ConfigAddRoute: ConfigAddRoute, ConfigAddRoute: ConfigAddRoute,
PitchbooksRoute: PitchbooksRoute,
ConfigDetailKpiIdRoute: ConfigDetailKpiIdRoute, ConfigDetailKpiIdRoute: ConfigDetailKpiIdRoute,
ExtractedResultPitchBookRoute: ExtractedResultPitchBookRoute, ExtractedResultPitchBookRoute: ExtractedResultPitchBookRoute,
ExtractedResultPitchBookKpiRoute: ExtractedResultPitchBookKpiRoute, ExtractedResultPitchBookKpiRoute: ExtractedResultPitchBookKpiRoute,
@ -195,6 +217,7 @@ export const routeTree = rootRoute
"/", "/",
"/config", "/config",
"/config-add", "/config-add",
"/pitchbooks",
"/config-detail/$kpiId", "/config-detail/$kpiId",
"/extractedResult/$pitchBook", "/extractedResult/$pitchBook",
"/extractedResult_/$pitchBook/$kpi" "/extractedResult_/$pitchBook/$kpi"
@ -209,6 +232,9 @@ export const routeTree = rootRoute
"/config-add": { "/config-add": {
"filePath": "config-add.tsx" "filePath": "config-add.tsx"
}, },
"/pitchbooks": {
"filePath": "pitchbooks.tsx"
},
"/config-detail/$kpiId": { "/config-detail/$kpiId": {
"filePath": "config-detail.$kpiId.tsx" "filePath": "config-detail.$kpiId.tsx"
}, },

View File

@ -7,10 +7,23 @@ import { API_HOST } from "../util/api";
export const Route = createFileRoute("/config-add")({ export const Route = createFileRoute("/config-add")({
component: ConfigAddPage, component: ConfigAddPage,
validateSearch: (search: Record<string, unknown>): { from?: string } => {
return {
from: search.from as string | undefined,
};
},
}); });
function ConfigAddPage() { function ConfigAddPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { from } = Route.useSearch();
const handleBack = () => {
navigate({
to: "/config",
search: from ? { from } : undefined,
});
};
const handleSave = async (formData: Partial<Kennzahl>) => { const handleSave = async (formData: Partial<Kennzahl>) => {
try { try {
@ -69,7 +82,7 @@ function ConfigAddPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={() => navigate({ to: "/config" })}> <IconButton onClick={handleBack}>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/> <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton> </IconButton>
<Typography variant="h5" fontWeight="bold" ml={3}> <Typography variant="h5" fontWeight="bold" ml={3}>

View File

@ -10,16 +10,29 @@ import { API_HOST } from "../util/api";
export const Route = createFileRoute("/config-detail/$kpiId")({ export const Route = createFileRoute("/config-detail/$kpiId")({
component: KPIDetailPage, component: KPIDetailPage,
validateSearch: (search: Record<string, unknown>): { from?: string } => {
return {
from: search.from as string | undefined,
};
},
}); });
function KPIDetailPage() { function KPIDetailPage() {
const { kpiId } = Route.useParams(); const { kpiId } = Route.useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { from } = Route.useSearch();
const [kennzahl, setKennzahl] = useState<Kennzahl | null>(null); const [kennzahl, setKennzahl] = useState<Kennzahl | null>(null);
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const handleBack = () => {
navigate({
to: "/config",
search: from ? { from } : undefined
});
};
useEffect(() => { useEffect(() => {
const fetchKennzahl = async () => { const fetchKennzahl = async () => {
try { try {
@ -139,7 +152,7 @@ function KPIDetailPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={() => navigate({ to: "/config" })}> <IconButton onClick={handleBack}>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/> <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton> </IconButton>
<Typography variant="h5" fontWeight="bold" ml={3}> <Typography variant="h5" fontWeight="bold" ml={3}>
@ -250,7 +263,7 @@ function KPIDetailPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={() => navigate({ to: "/config" })}> <IconButton onClick={handleBack}>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/> <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton> </IconButton>
<Typography variant="h5" fontWeight="bold" ml={3}> <Typography variant="h5" fontWeight="bold" ml={3}>

View File

@ -6,13 +6,29 @@ import { ConfigTable } from "../components/ConfigTable";
export const Route = createFileRoute("/config")({ export const Route = createFileRoute("/config")({
component: ConfigPage, component: ConfigPage,
validateSearch: (search: Record<string, unknown>): { from?: string } => {
const from = typeof search.from === "string" ? search.from : undefined;
return { from };
}
}); });
function ConfigPage() { function ConfigPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { from } = Route.useSearch();
const handleAddNewKPI = () => { const handleAddNewKPI = () => {
navigate({ to: "/config-add" }); navigate({
to: "/config-add",
search: from ? { from } : undefined
});
};
const handleBack = () => {
if (from === "pitchbooks") {
navigate({ to: "/pitchbooks" });
} else {
navigate({ to: "/" });
}
}; };
return ( return (
@ -34,7 +50,7 @@ function ConfigPage() {
px={4} px={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={() => navigate({ to: "/" })}> <IconButton onClick={handleBack}>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/> <ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton> </IconButton>
<Typography variant="h5" fontWeight="bold" ml={3}> <Typography variant="h5" fontWeight="bold" ml={3}>
@ -53,7 +69,7 @@ function ConfigPage() {
</Button> </Button>
</Box> </Box>
<Box sx={{ width: "100%", mt: 4, display: "flex", justifyContent: "center" }}> <Box sx={{ width: "100%", mt: 4, display: "flex", justifyContent: "center" }}>
<ConfigTable /> <ConfigTable from={from} />
</Box> </Box>
</Box> </Box>
); );

View File

@ -1,26 +1,42 @@
import ContentPasteIcon from "@mui/icons-material/ContentPaste"; import ContentPasteIcon from "@mui/icons-material/ContentPaste";
import { Box, Button, Paper, Typography } from "@mui/material"; import { Box, Button, Paper, Typography, Snackbar, Alert, IconButton } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { useSuspenseQuery } from "@tanstack/react-query"; import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useCallback, useState } from "react"; import { useCallback, useState, useMemo } from "react";
import KennzahlenTable from "../components/KennzahlenTable"; import KennzahlenTable from "../components/KennzahlenTable";
import PDFViewer from "../components/pdfViewer"; import PDFViewer from "../components/pdfViewer";
import { kpiQueryOptions, settingsQueryOptions } from "../util/query"; import { kpiQueryOptions, settingsQueryOptions } from "../util/query";
import { redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/extractedResult/$pitchBook")({ export const Route = createFileRoute("/extractedResult/$pitchBook")({
component: ExtractedResultsPage, component: ExtractedResultsPage,
loader: ({ context: { queryClient }, params: { pitchBook } }) => validateSearch: (search: Record<string, unknown>): { from?: string } => {
Promise.allSettled([ return {
from: search.from as string | undefined,
};
},
loader: async ({ context: { queryClient }, params: { pitchBook } }) => {
const results = await Promise.allSettled([
queryClient.ensureQueryData(kpiQueryOptions(pitchBook)), queryClient.ensureQueryData(kpiQueryOptions(pitchBook)),
queryClient.ensureQueryData(settingsQueryOptions()), queryClient.ensureQueryData(settingsQueryOptions()),
]), ]);
if (results[0].status === "rejected") {
throw redirect({
to: "/"
});
}
return results;
}
}); });
function ExtractedResultsPage() { function ExtractedResultsPage() {
const { pitchBook } = Route.useParams(); const { pitchBook } = Route.useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const status: "green" | "yellow" | "red" = "red"; const { from } = Route.useSearch();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [copied, setCopied] = useState(false);
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [focusHighlight, setFocusHighlight] = useState({ const [focusHighlight, setFocusHighlight] = useState({
page: 5, page: 5,
text: "Langjährige", text: "Langjährige",
@ -31,18 +47,106 @@ function ExtractedResultsPage() {
setFocusHighlight({ page, text: entity }); setFocusHighlight({ page, text: entity });
}, []); }, []);
const { data: kpi } = useSuspenseQuery(kpiQueryOptions(pitchBook));
const { data: settings } = useSuspenseQuery(settingsQueryOptions());
const status = useMemo(() => {
let hasRedBorders = false;
let hasYellowBorders = false;
settings
.filter((setting) => setting.active)
.forEach((setting) => {
const values = kpi[setting.name.toUpperCase()] || [];
const hasNoValue = setting.mandatory && (values.length === 0 || values[0]?.entity === "");
const hasMultipleValues = values.length > 1;
if (hasNoValue) {
hasRedBorders = true;
} else if (hasMultipleValues) {
hasYellowBorders = true;
}
});
if (hasRedBorders) return "red";
if (hasYellowBorders) return "yellow";
return "green";
}, [kpi, settings]);
const statusColor = { const statusColor = {
red: "#f43131", red: "#f43131",
yellow: "#f6ed48", yellow: "#f6ed48",
green: "#3fd942", green: "#3fd942",
}[status]; }[status];
const { data: kpi } = useSuspenseQuery(kpiQueryOptions(pitchBook)); const prepareClipboardData = () => {
const { data: settings } = useSuspenseQuery(settingsQueryOptions()); const activeSettings = settings
.filter(setting => setting.active)
.sort((a, b) => a.position - b.position);
const values = activeSettings.map(setting => {
const settingData = kpi[setting.name.toUpperCase()];
if (!settingData || settingData.length === 0) {
return "";
}
let value = settingData[0]?.entity || "";
value = value
.replace(/[\r\n]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
value = value.replace(/\t/g, ' ');
return value;
});
return values.join('\t');
};
const handleCopyToClipboard = async () => {
try {
const textToCopy = prepareClipboardData();
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': new Blob([textToCopy], { type: 'text/plain' })
})
]);
} else {
const textArea = document.createElement("textarea");
textArea.value = textToCopy;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
textArea.remove();
}
setCopied(true);
setSnackbarOpen(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Fallback to copy failed');
}
};
const handleCloseSnackbar = () => {
setSnackbarOpen(false);
};
return ( return (
<Box p={4}> <Box p={4}>
<Box display="flex" alignItems="center" gap={3}> <Box display="flex" alignItems="center" gap={3}>
{from === "overview" && (
<IconButton
onClick={() => navigate({ to: "/pitchbooks" })}
sx={{ ml: -1 }}
>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton>
)}
<Box <Box
sx={{ sx={{
width: 45, width: 45,
@ -84,6 +188,7 @@ function ExtractedResultsPage() {
onPageClick={onSiteClick} onPageClick={onSiteClick}
data={kpi} data={kpi}
pdfId={pitchBook} pdfId={pitchBook}
from={from}
/> />
</Paper> </Paper>
<Box <Box
@ -130,9 +235,10 @@ function ExtractedResultsPage() {
gap={2} gap={2}
sx={{ flexShrink: 0 }} sx={{ flexShrink: 0 }}
> >
<Button variant="contained" sx={{ backgroundColor: "#383838" }}> <Button variant="contained" sx={{ backgroundColor: "#383838" }}
onClick={handleCopyToClipboard}>
<ContentPasteIcon sx={{ fontSize: 18, mr: 1 }} /> <ContentPasteIcon sx={{ fontSize: 18, mr: 1 }} />
Kennzahlenzeile kopieren {copied ? "Kopiert!" : "Kennzahlenzeile kopieren"}
</Button> </Button>
<Button <Button
variant="contained" variant="contained"
@ -144,6 +250,21 @@ function ExtractedResultsPage() {
</Box> </Box>
</Box> </Box>
</Box> </Box>
<Snackbar
open={snackbarOpen}
autoHideDuration={3000}
onClose={handleCloseSnackbar}
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
>
<Alert
onClose={handleCloseSnackbar}
severity="success"
sx={{ width: '100%' }}
>
Kennzahlen erfolgreich in die Zwischenablage kopiert!
</Alert>
</Snackbar>
</Box> </Box>
); );
} }

View File

@ -30,11 +30,24 @@ import { useEffect, useState } from "react";
import PDFViewer from "../components/pdfViewer"; import PDFViewer from "../components/pdfViewer";
import { fetchPutKPI } from "../util/api"; import { fetchPutKPI } from "../util/api";
import { kpiQueryOptions } from "../util/query"; import { kpiQueryOptions } from "../util/query";
import { redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/extractedResult_/$pitchBook/$kpi")({ export const Route = createFileRoute("/extractedResult_/$pitchBook/$kpi")({
component: ExtractedResultsPage, component: ExtractedResultsPage,
loader: ({ context: { queryClient }, params: { pitchBook } }) => validateSearch: (search: Record<string, unknown>) => {
queryClient.ensureQueryData(kpiQueryOptions(pitchBook)), return {
from: typeof search.from === "string" ? search.from : undefined,
};
},
loader: async ({ context: { queryClient }, params: { pitchBook } }) => {
try {
return await queryClient.ensureQueryData(kpiQueryOptions(pitchBook));
} catch (err) {
throw redirect({
to: "/"
});
}
},
}); });
function ExtractedResultsPage() { function ExtractedResultsPage() {
@ -42,6 +55,7 @@ function ExtractedResultsPage() {
const { pitchBook, kpi } = params; const { pitchBook, kpi } = params;
const navigate = useNavigate(); const navigate = useNavigate();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { from } = Route.useSearch();
const { data: kpiData } = useSuspenseQuery(kpiQueryOptions(pitchBook)); const { data: kpiData } = useSuspenseQuery(kpiQueryOptions(pitchBook));
@ -62,9 +76,21 @@ function ExtractedResultsPage() {
const { mutate: updateKPI } = useMutation({ const { mutate: updateKPI } = useMutation({
mutationFn: () => { mutationFn: () => {
const updatedData = { ...kpiData }; const updatedData = { ...kpiData };
let baseObject;
if (selectedIndex >= 0) {
baseObject = kpiValues[selectedIndex];
} else {
baseObject = {
label: kpi.toUpperCase(),
entity: selectedValue,
page: 0,
status: "single-source",
source: "manual",
};
}
updatedData[kpi.toUpperCase()] = [ updatedData[kpi.toUpperCase()] = [
{ {
...kpiValues[0], ...baseObject,
entity: selectedValue, entity: selectedValue,
}, },
]; ];
@ -77,6 +103,7 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
}, },
onError: (error) => { onError: (error) => {
@ -117,6 +144,7 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
} }
}; };
@ -126,6 +154,7 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
}; };
@ -385,4 +414,4 @@ function ExtractedResultsPage() {
</Dialog> </Dialog>
</Box> </Box>
); );
} }

View File

@ -0,0 +1,59 @@
import { createFileRoute } from "@tanstack/react-router";
import { Box, Typography, IconButton } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import SettingsIcon from "@mui/icons-material/Settings";
import { useNavigate } from "@tanstack/react-router";
import { PitchBooksTable } from "../components/PitchBooksTable";
import { pitchBooksQueryOptions } from "../util/query";
export const Route = createFileRoute("/pitchbooks")({
component: PitchBooksPage,
loader: ({ context: { queryClient } }) =>
queryClient.ensureQueryData(pitchBooksQueryOptions()),
});
function PitchBooksPage() {
const navigate = useNavigate();
return (
<Box
minHeight="100vh"
width="100vw"
bgcolor="white"
display="flex"
flexDirection="column"
alignItems="center"
pt={3}
pb={4}
>
<Box
width="100%"
display="flex"
justifyContent="space-between"
alignItems="center"
px={4}
mb={4}
>
<Box display="flex" alignItems="center">
<IconButton onClick={() => navigate({ to: "/" })}>
<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }}/>
</IconButton>
<Typography variant="h5" fontWeight="bold" ml={3}>
Übersicht aller Pitch Books
</Typography>
</Box>
<IconButton
onClick={() => navigate({
to: "/config",
search: { from: "pitchbooks" }
})}
>
<SettingsIcon fontSize="large" sx={{ color: '#383838' }} />
</IconButton>
</Box>
<Box sx={{ width: "100%", display: "flex", justifyContent: "center" }}>
<PitchBooksTable />
</Box>
</Box>
);
}

View File

@ -111,3 +111,11 @@ export const fetchKennzahlen = async (): Promise<Kennzahl[]> => {
const data = await response.json(); const data = await response.json();
return data; return data;
}; };
export async function fetchPitchBooks() {
const response = await fetch(`${API_HOST}/api/pitch_book/`);
if (!response.ok) {
throw new Error("Failed to fetch pitch books");
}
return response.json();
}

View File

@ -1,5 +1,5 @@
import { queryOptions } from "@tanstack/react-query"; import { queryOptions } from "@tanstack/react-query";
import { fetchKPI, fetchKennzahlen } from "./api"; import { fetchKPI, fetchKennzahlen, fetchPitchBooks } from "./api";
export const kpiQueryOptions = (pitchBookId: string) => export const kpiQueryOptions = (pitchBookId: string) =>
queryOptions({ queryOptions({
@ -12,3 +12,10 @@ export const settingsQueryOptions = () =>
queryKey: ["pitchBookSettings"], queryKey: ["pitchBookSettings"],
queryFn: () => fetchKennzahlen(), queryFn: () => fetchKennzahlen(),
}); });
export const pitchBooksQueryOptions = () =>
queryOptions({
queryKey: ["pitchBooks"],
queryFn: fetchPitchBooks,
staleTime: 30000,
});