Compare commits

..

No commits in common. "017670f95e3716c0820441b472490da94cbc6eec" and "b3e4dd634e31c5c6ad2f813fb705c245b9db2d6b" have entirely different histories.

28 changed files with 234 additions and 944 deletions

View File

@ -17,4 +17,4 @@ COPY . .
ENV PYTHONUNBUFFERED=1 ENV PYTHONUNBUFFERED=1
CMD ["gunicorn", "--timeout", "600", "--workers", "1", "--bind", "0.0.0.0:5000", "app:app"] CMD ["gunicorn", "--timeout", "600", "--workers", "2", "--bind", "0.0.0.0:5000", "app:app"]

View File

@ -5,6 +5,7 @@ from dotenv import load_dotenv
from controller import register_routes from controller import register_routes
from model.database import init_db from model.database import init_db
from controller.socketIO import socketio from controller.socketIO import socketio
from controller.kennzahlen import kennzahlen_bp
app = Flask(__name__) app = Flask(__name__)
CORS(app) CORS(app)
@ -21,6 +22,9 @@ init_db(app)
register_routes(app) register_routes(app)
# Register blueprints
app.register_blueprint(kennzahlen_bp)
@app.route("/health") @app.route("/health")
def health_check(): def health_check():
return "OK" return "OK"

View File

@ -0,0 +1,61 @@
from flask import Blueprint, jsonify, request
from model.kennzahl import Kennzahl
from model.database import db
kennzahlen_bp = Blueprint('kennzahlen', __name__)
# Beispieldaten
EXAMPLE_DATA = [
{"pdf_id": "example", "label": "Fondsname", "value": "Fund Real Estate Prime Europe", "page": 1, "status": "ok"},
{"pdf_id": "example", "label": "Fondsmanager", "value": "", "page": 1, "status": "error"},
{"pdf_id": "example", "label": "Risikoprofil", "value": "Core/Core+", "page": 10, "status": "warning"},
{"pdf_id": "example", "label": "LTV", "value": "30-35 %", "page": 8, "status": "ok"},
{"pdf_id": "example", "label": "Ausschüttungsrendite", "value": "4%", "page": 34, "status": "ok"}
]
@kennzahlen_bp.route('/api/kennzahlen/init', methods=['POST'])
def init_kennzahlen():
try:
# Lösche existierende Beispieldaten
Kennzahl.query.filter_by(pdf_id='example').delete()
# Füge Beispieldaten ein
for data in EXAMPLE_DATA:
kennzahl = Kennzahl(
pdf_id=data['pdf_id'],
label=data['label'],
value=data['value'],
page=data['page'],
status=data['status']
)
db.session.add(kennzahl)
db.session.commit()
return jsonify({"message": "Kennzahlen erfolgreich initialisiert"})
except Exception as e:
db.session.rollback()
return jsonify({"error": str(e)}), 500
@kennzahlen_bp.route('/api/kennzahlen', methods=['GET'])
def get_kennzahlen():
pdf_id = request.args.get('pdf_id', 'example') # Default zu 'example' für Beispieldaten
kennzahlen = Kennzahl.query.filter_by(pdf_id=pdf_id).all()
return jsonify([k.to_dict() for k in kennzahlen])
@kennzahlen_bp.route('/api/kennzahlen/<label>', methods=['PUT'])
def update_kennzahl(label):
data = request.get_json()
pdf_id = request.args.get('pdf_id', 'example') # Default zu 'example' für Beispieldaten
kennzahl = Kennzahl.query.filter_by(pdf_id=pdf_id, label=label).first()
if not kennzahl:
return jsonify({'error': 'Kennzahl nicht gefunden'}), 404
kennzahl.value = data.get('value', kennzahl.value)
db.session.commit()
return jsonify(kennzahl.to_dict())

View File

@ -35,7 +35,7 @@ def create_kpi_setting():
"translation", "translation",
"example", "example",
"position", "position",
"active", "active"
] ]
for field in required_fields: for field in required_fields:
if field not in data: if field not in data:
@ -61,7 +61,7 @@ def create_kpi_setting():
translation=data["translation"], translation=data["translation"],
example=data["example"], example=data["example"],
position=data["position"], position=data["position"],
active=data["active"], active=data["active"]
) )
db.session.add(new_kpi_setting) db.session.add(new_kpi_setting)
@ -136,12 +136,7 @@ def update_kpi_positions():
try: try:
for update_item in data: for update_item in data:
if "id" not in update_item or "position" not in update_item: if "id" not in update_item or "position" not in update_item:
return ( return jsonify({"error": "Each item must have 'id' and 'position' fields"}), 400
jsonify(
{"error": "Each item must have 'id' and 'position' fields"}
),
400,
)
kpi_setting = KPISettingModel.query.get_or_404(update_item["id"]) kpi_setting = KPISettingModel.query.get_or_404(update_item["id"])
kpi_setting.position = update_item["position"] kpi_setting.position = update_item["position"]

View File

@ -19,6 +19,6 @@ def progress():
): ):
return jsonify({"error": "Invalid progress value"}), 400 return jsonify({"error": "Invalid progress value"}), 400
socketio.emit("progress", {"id": int(data["id"]), "progress": data["progress"]}) socketio.emit("progress", {"id": data["id"], "progress": data["progress"]})
# Process the data and return a response # Process the data and return a response
return jsonify({"message": "Progress updated"}) return jsonify({"message": "Progress updated"})

View File

@ -14,5 +14,4 @@ def init_db(app):
with app.app_context(): with app.app_context():
db.create_all() db.create_all()
from model.seed_data import seed_default_kpi_settings from model.seed_data import seed_default_kpi_settings
seed_default_kpi_settings() seed_default_kpi_settings()

View File

@ -0,0 +1,26 @@
from .database import db
class Kennzahl(db.Model):
__tablename__ = 'kennzahlen'
id = db.Column(db.Integer, primary_key=True)
pdf_id = db.Column(db.String(100), nullable=False) # ID des PDFs
label = db.Column(db.String(100), nullable=False)
value = db.Column(db.String(100))
page = db.Column(db.Integer)
status = db.Column(db.String(20))
# Zusammengesetzter Unique-Constraint für pdf_id und label
__table_args__ = (
db.UniqueConstraint('pdf_id', 'label', name='unique_pdf_kennzahl'),
)
def to_dict(self):
return {
'pdf_id': self.pdf_id,
'label': self.label,
'value': self.value,
'page': self.page,
'status': self.status
}

View File

@ -38,12 +38,10 @@ class KPISettingModel(db.Model):
"translation": self.translation, "translation": self.translation,
"example": self.example, "example": self.example,
"position": self.position, "position": self.position,
"active": self.active, "active": self.active
} }
def __init__( def __init__(self, name, description, mandatory, type, translation, example, position, active):
self, name, description, mandatory, type, translation, example, position, active
):
self.name = name self.name = name
self.description = description self.description = description
self.mandatory = mandatory self.mandatory = mandatory

View File

@ -1,7 +1,6 @@
from model.database import db from model.database import db
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import LargeBinary from sqlalchemy import LargeBinary
from datetime import datetime
class PitchBookModel(db.Model): class PitchBookModel(db.Model):
@ -9,15 +8,9 @@ class PitchBookModel(db.Model):
filename: Mapped[str] = mapped_column() filename: Mapped[str] = mapped_column()
file: Mapped[bytes] = mapped_column(LargeBinary) file: Mapped[bytes] = mapped_column(LargeBinary)
kpi: Mapped[str | None] kpi: Mapped[str | None]
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
def to_dict(self): def to_dict(self):
return { return {"id": self.id, "filename": self.filename, "kpi": self.kpi}
"id": self.id,
"filename": self.filename,
"kpi": self.kpi,
"created_at": self.created_at.isoformat() if self.created_at else None,
}
def __init__(self, filename, file): def __init__(self, filename, file):
self.filename = filename self.filename = filename

View File

@ -1,7 +1,6 @@
from model.database import db from model.database import db
from model.kpi_setting_model import KPISettingModel, KPISettingType from model.kpi_setting_model import KPISettingModel, KPISettingType
def seed_default_kpi_settings(): def seed_default_kpi_settings():
if KPISettingModel.query.first() is not None: if KPISettingModel.query.first() is not None:
print("KPI Settings bereits vorhanden, Seeding übersprungen") print("KPI Settings bereits vorhanden, Seeding übersprungen")
@ -16,7 +15,7 @@ def seed_default_kpi_settings():
"translation": "Fund Name", "translation": "Fund Name",
"example": "Alpha Real Estate Fund I", "example": "Alpha Real Estate Fund I",
"position": 1, "position": 1,
"active": True, "active": True
}, },
{ {
"name": "Fondsmanager", "name": "Fondsmanager",
@ -26,7 +25,7 @@ def seed_default_kpi_settings():
"translation": "Fund Manager", "translation": "Fund Manager",
"example": "Max Mustermann", "example": "Max Mustermann",
"position": 2, "position": 2,
"active": True, "active": True
}, },
{ {
"name": "AIFM", "name": "AIFM",
@ -36,7 +35,7 @@ def seed_default_kpi_settings():
"translation": "AIFM", "translation": "AIFM",
"example": "Alpha Investment Management GmbH", "example": "Alpha Investment Management GmbH",
"position": 3, "position": 3,
"active": True, "active": True
}, },
{ {
"name": "Datum", "name": "Datum",
@ -46,7 +45,7 @@ def seed_default_kpi_settings():
"translation": "Date", "translation": "Date",
"example": "05.05.2025", "example": "05.05.2025",
"position": 4, "position": 4,
"active": True, "active": True
}, },
{ {
"name": "Risikoprofil", "name": "Risikoprofil",
@ -56,7 +55,7 @@ def seed_default_kpi_settings():
"translation": "Risk Profile", "translation": "Risk Profile",
"example": "Core/Core++", "example": "Core/Core++",
"position": 5, "position": 5,
"active": True, "active": True
}, },
{ {
"name": "Artikel", "name": "Artikel",
@ -66,7 +65,7 @@ def seed_default_kpi_settings():
"translation": "Article", "translation": "Article",
"example": "Artikel 8", "example": "Artikel 8",
"position": 6, "position": 6,
"active": True, "active": True
}, },
{ {
"name": "Zielrendite", "name": "Zielrendite",
@ -76,7 +75,7 @@ def seed_default_kpi_settings():
"translation": "Target Return", "translation": "Target Return",
"example": "6.5", "example": "6.5",
"position": 7, "position": 7,
"active": True, "active": True
}, },
{ {
"name": "Rendite", "name": "Rendite",
@ -86,7 +85,7 @@ def seed_default_kpi_settings():
"translation": "Return", "translation": "Return",
"example": "5.8", "example": "5.8",
"position": 8, "position": 8,
"active": True, "active": True
}, },
{ {
"name": "Zielausschüttung", "name": "Zielausschüttung",
@ -96,7 +95,7 @@ def seed_default_kpi_settings():
"translation": "Target Distribution", "translation": "Target Distribution",
"example": "4.0", "example": "4.0",
"position": 9, "position": 9,
"active": True, "active": True
}, },
{ {
"name": "Ausschüttung", "name": "Ausschüttung",
@ -106,7 +105,7 @@ def seed_default_kpi_settings():
"translation": "Distribution", "translation": "Distribution",
"example": "3.8", "example": "3.8",
"position": 10, "position": 10,
"active": True, "active": True
}, },
{ {
"name": "Laufzeit", "name": "Laufzeit",
@ -116,7 +115,7 @@ def seed_default_kpi_settings():
"translation": "Duration", "translation": "Duration",
"example": "7 Jahre, 10, Evergreen", "example": "7 Jahre, 10, Evergreen",
"position": 11, "position": 11,
"active": True, "active": True
}, },
{ {
"name": "LTV", "name": "LTV",
@ -126,7 +125,7 @@ def seed_default_kpi_settings():
"translation": "LTV", "translation": "LTV",
"example": "65.0", "example": "65.0",
"position": 12, "position": 12,
"active": True, "active": True
}, },
{ {
"name": "Managementgebühren", "name": "Managementgebühren",
@ -136,7 +135,7 @@ def seed_default_kpi_settings():
"translation": "Management Fees", "translation": "Management Fees",
"example": "1.5", "example": "1.5",
"position": 13, "position": 13,
"active": True, "active": True
}, },
{ {
"name": "Sektorenallokation", "name": "Sektorenallokation",
@ -146,7 +145,7 @@ def seed_default_kpi_settings():
"translation": "Sector Allocation", "translation": "Sector Allocation",
"example": "Büro, Wohnen, Logistik, Studentenwohnen", "example": "Büro, Wohnen, Logistik, Studentenwohnen",
"position": 14, "position": 14,
"active": True, "active": True
}, },
{ {
"name": "Länderallokation", "name": "Länderallokation",
@ -156,8 +155,8 @@ def seed_default_kpi_settings():
"translation": "Country Allocation", "translation": "Country Allocation",
"example": "Deutschland,Frankreich, Österreich, Schweiz", "example": "Deutschland,Frankreich, Österreich, Schweiz",
"position": 15, "position": 15,
"active": True, "active": True
}, }
] ]
print("Füge Standard KPI Settings hinzu...") print("Füge Standard KPI Settings hinzu...")
@ -171,16 +170,14 @@ def seed_default_kpi_settings():
translation=kpi_data["translation"], translation=kpi_data["translation"],
example=kpi_data["example"], example=kpi_data["example"],
position=kpi_data["position"], position=kpi_data["position"],
active=kpi_data["active"], active=kpi_data["active"]
) )
db.session.add(kpi_setting) db.session.add(kpi_setting)
try: try:
db.session.commit() db.session.commit()
print( print(f"Erfolgreich {len(default_kpi_settings)} Standard KPI Settings hinzugefügt")
f"Erfolgreich {len(default_kpi_settings)} Standard KPI Settings hinzugefügt"
)
except Exception as e: except Exception as e:
db.session.rollback() db.session.rollback()
print(f"Fehler beim Hinzufügen der Standard KPI Settings: {e}") print(f"Fehler beim Hinzufügen der Standard KPI Settings: {e}")

View File

@ -4,9 +4,6 @@ services:
context: frontend context: frontend
ports: ports:
- 8080:80 - 8080:80
environment:
- API_HOST=http://localhost:5050
db: db:
image: postgres:17-alpine image: postgres:17-alpine
env_file: env_file:

View File

@ -8,21 +8,8 @@ RUN bun install --frozen-lockfile
COPY . . COPY . .
# dummy environment variable for build - DONT CHANGE!!!
ENV VITE_API_HOST=SECRET_HOST
RUN bun run build RUN bun run build
FROM nginx:1.28.0-alpine3.21 FROM nginx:1.28.0-alpine3.21
# default environment variable that will be replaced at runtime
ENV API_HOST=http://localhost:5050
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=base /usr/src/app/dist /usr/share/nginx/html COPY --from=base /usr/src/app/dist /usr/share/nginx/html
# entrypoint script
COPY docker/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
CMD ["/docker-entrypoint.sh"]

View File

@ -1,23 +0,0 @@
#!/bin/sh
# Replace API host in built JavaScript files
echo "Replacing SECRET_HOST with ${API_HOST}"
# Replace in main JS files
for i in /usr/share/nginx/html/*.js; do
if [ -f "$i" ]; then
sed -i "s|SECRET_HOST|${API_HOST}|g" "$i"
fi
done
# Replace in assets folder JS files
for i in /usr/share/nginx/html/assets/*.js; do
if [ -f "$i" ]; then
sed -i "s|SECRET_HOST|${API_HOST}|g" "$i"
fi
done
echo "Replacement completed. Starting nginx..."
# Start nginx and replace the shell process
exec nginx -g 'daemon off;'

View File

@ -5,13 +5,8 @@ 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"; import { fetchKennzahlen as fetchK } from "../util/api";
import { API_HOST } from "../util/api";
type ConfigTableProps = { export function ConfigTable() {
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);
@ -47,7 +42,7 @@ export function ConfigTable({ from }: ConfigTableProps) {
try { try {
const response = await fetch( const response = await fetch(
`${API_HOST}/api/kpi_setting/${id}`, `http://localhost:5050/api/kpi_setting/${id}`,
{ {
method: "PUT", method: "PUT",
headers: { headers: {
@ -84,7 +79,7 @@ export function ConfigTable({ from }: ConfigTableProps) {
})); }));
const response = await fetch( const response = await fetch(
`${API_HOST}/api/kpi_setting/update-kpi-positions`, `http://localhost:5050/api/kpi_setting/update-kpi-positions`,
{ {
method: "PUT", method: "PUT",
headers: { headers: {
@ -165,10 +160,12 @@ export function ConfigTable({ from }: ConfigTableProps) {
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,7 +34,6 @@ interface KennzahlenTableProps {
source: string; source: string;
}[]; }[];
}; };
from?: string;
} }
export default function KennzahlenTable({ export default function KennzahlenTable({
@ -42,11 +41,10 @@ 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(); const navigate = useNavigate({ from: "/extractedResult/$pitchBook" });
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -122,7 +120,6 @@ export default function KennzahlenTable({
pitchBook: pdfId, pitchBook: pdfId,
kpi: settingName, kpi: settingName,
}, },
search: { from: from ?? undefined },
}); });
}; };
@ -228,23 +225,6 @@ export default function KennzahlenTable({
</Box> </Box>
</Tooltip> </Tooltip>
) : ( ) : (
<Tooltip
title={
hasNoValue ? (
<>
<b>Problem</b>
<br />
Es wurden keine Kennzahlen gefunden. Bitte
ergänzen!
</>
) : (
""
)
}
placement="bottom"
arrow
>
<span>
<Box <Box
sx={{ sx={{
border: `2px solid ${borderColor}`, border: `2px solid ${borderColor}`,
@ -266,10 +246,7 @@ export default function KennzahlenTable({
}} }}
> >
{hasNoValue && ( {hasNoValue && (
<ErrorOutlineIcon <ErrorOutlineIcon fontSize="small" color="error" />
fontSize="small"
color="error"
/>
)} )}
{editingIndex === row.setting.name ? ( {editingIndex === row.setting.name ? (
<TextField <TextField
@ -303,30 +280,21 @@ export default function KennzahlenTable({
}} }}
/> />
</Box> </Box>
</span>
</Tooltip>
)} )}
</TableCell> </TableCell>
<TableCell align="center"> <TableCell align="center">
{(row.extractedValues.at(0)?.page ?? 0) > 0 ? (
<Link <Link
component="button" component="button"
onClick={() => { onClick={() =>
const extractedValue = row.extractedValues.at(0);
if (extractedValue?.page && extractedValue.page > 0) {
onPageClick?.( onPageClick?.(
Number(extractedValue.page), Number(row.extractedValues.at(0)?.page),
extractedValue.entity || "", row.extractedValues.at(0)?.entity || "",
); )
} }
}}
sx={{ cursor: "pointer" }} sx={{ cursor: "pointer" }}
> >
{row.extractedValues.at(0)?.page} {row.extractedValues.at(0)?.page}
</Link> </Link>
) : (
""
)}
</TableCell> </TableCell>
</TableRow> </TableRow>
); );

View File

@ -1,388 +0,0 @@
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import HourglassEmptyIcon from "@mui/icons-material/HourglassEmpty";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import {
Box,
Chip,
CircularProgress,
LinearProgress,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from "@mui/material";
import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useState } from "react";
import { socket } from "../socket";
import { fetchPitchBooksById } from "../util/api";
import { pitchBooksQueryOptions } from "../util/query";
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 [loadingPitchBooks, setLoadingPitchBooks] = useState<
{
id: number;
progress: number;
filename?: string;
buffer: number;
intervalId?: number;
}[]
>([]);
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 onConnection = useCallback(() => {
console.log("connected");
}, []);
const queryClient = useQueryClient();
const onProgress = useCallback(
(progress: { id: number; progress: number }) => {
if (progress.progress === 100) {
setLoadingPitchBooks((prev) => {
const intervalId = prev.find(
(item) => item.id === progress.id,
)?.intervalId;
console.log(intervalId, prev);
intervalId && clearInterval(intervalId);
return [...prev.filter((item) => item.id !== progress.id)];
});
queryClient.invalidateQueries({
queryKey: pitchBooksQueryOptions().queryKey,
});
} else {
setLoadingPitchBooks((prev) => {
const oldItem = prev.find((item) => item.id === progress.id);
let intervalId = oldItem?.intervalId;
if (!oldItem) {
intervalId = setInterval(() => {
setLoadingPitchBooks((prev) => {
const oldItem = prev.find((item) => item.id === progress.id);
if (!oldItem) return prev;
return [
...prev.filter((e) => e.id !== progress.id),
{
id: progress.id,
progress: oldItem?.progress ?? progress.progress,
filename: oldItem?.filename,
buffer: oldItem ? oldItem.buffer + 0.5 : 0,
intervalId: oldItem.intervalId,
},
];
});
}, 400);
fetchPitchBooksById(progress.id)
.then((res) => {
setLoadingPitchBooks((prev) => [
...prev.filter((item) => item.id !== progress.id),
{
id: progress.id,
progress: progress.progress,
filename: res.filename,
buffer: 0,
intervalId,
},
]);
})
.catch((err) => {
console.error(err);
});
}
return [
...prev.filter((item) => item.id !== progress.id),
{
id: progress.id,
progress: progress.progress,
filename: oldItem?.filename,
buffer: 0,
intervalId,
},
];
});
}
},
[queryClient],
);
useEffect(() => {
socket.on("connect", onConnection);
socket.on("progress", onProgress);
return () => {
socket.off("connect", onConnection);
socket.off("progress", onProgress);
};
}, [onConnection, onProgress]);
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, item) => {
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[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 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
.filter(
(pitchbook: PitchBook) =>
!loadingPitchBooks.some((e) => e.id === pitchbook.id),
)
.sort(
(a: PitchBook, b: PitchBook) =>
new Date(a.created_at).getTime() -
new Date(b.created_at).getTime(),
)
.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>
);
})}
{loadingPitchBooks
.sort((a, b) => a.id - b.id)
.map((pitchBook) => (
<TableRow key={pitchBook.id}>
<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 colSpan={2}>
<LinearProgress
variant="buffer"
value={pitchBook.progress}
valueBuffer={
pitchBook.buffer
? pitchBook.progress + pitchBook.buffer
: pitchBook.progress
}
/>
</TableCell>
<TableCell>
{" "}
<Typography
variant="body2"
color="text.secondary"
fontSize="0.875rem"
>
{pitchBook.filename}
</Typography>
</TableCell>
<TableCell>
<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

@ -1,10 +1,9 @@
import SettingsIcon from "@mui/icons-material/Settings"; import SettingsIcon from "@mui/icons-material/Settings";
import { Backdrop, Box, Button, IconButton, Paper } from "@mui/material"; import { Backdrop, Box, Button, IconButton, Paper } from "@mui/material";
import { useNavigate, useRouter } from "@tanstack/react-router"; import { useNavigate } from "@tanstack/react-router";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import FileUpload from "react-material-file-upload"; import FileUpload from "react-material-file-upload";
import { socket } from "../socket"; import { socket } from "../socket";
import { API_HOST } from "../util/api";
import { CircularProgressWithLabel } from "./CircularProgressWithLabel"; import { CircularProgressWithLabel } from "./CircularProgressWithLabel";
export default function UploadPage() { export default function UploadPage() {
@ -13,12 +12,11 @@ export default function UploadPage() {
const [loadingState, setLoadingState] = useState<number | null>(null); const [loadingState, setLoadingState] = useState<number | null>(null);
const fileTypes = ["pdf"]; const fileTypes = ["pdf"];
const navigate = useNavigate(); const navigate = useNavigate();
const router = useRouter();
const uploadFile = useCallback(async () => { const uploadFile = useCallback(async () => {
const formData = new FormData(); const formData = new FormData();
formData.append("file", files[0]); formData.append("file", files[0]);
const response = await fetch(`${API_HOST}/api/pitch_book`, { const response = await fetch("http://localhost:5050/api/pitch_book", {
method: "POST", method: "POST",
body: formData, body: formData,
}); });
@ -170,20 +168,6 @@ 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" },
}}
onMouseEnter={() => router.preloadRoute({ to: "/pitchbooks" })}
onClick={() => navigate({ to: "/pitchbooks" })}
>
Alle Pitch Books anzeigen
</Button>
</Box> </Box>
</> </>
); );

View File

@ -10,7 +10,6 @@ import type {
OnGetTextSuccess, OnGetTextSuccess,
} from "node_modules/react-pdf/dist/esm/shared/types"; } from "node_modules/react-pdf/dist/esm/shared/types";
import { socket } from "../socket"; import { socket } from "../socket";
import { API_HOST } from "../util/api";
import { highlightPattern } from "../util/highlighting"; import { highlightPattern } from "../util/highlighting";
interface PDFViewerProps { interface PDFViewerProps {
@ -111,8 +110,7 @@ export default function PDFViewer({
) { ) {
for ( for (
let k = textItems[i].i; let k = textItems[i].i;
k < textItems[i + s.split(" ").length]?.i || k < textItems[i + s.split(" ").length].i;
k < textItems[i + s.split(" ").length - 1]?.i;
k++ k++
) { ) {
tmpPos.push(textContent[k].posKey); tmpPos.push(textContent[k].posKey);
@ -130,8 +128,7 @@ export default function PDFViewer({
) { ) {
for ( for (
let k = textItems[i].i; let k = textItems[i].i;
k < textItems[i + focusHighlight.text.split(" ").length]?.i || k < textItems[i + focusHighlight.text.split(" ").length].i;
k < textItems[i + focusHighlight.text.split(" ").length - 1]?.i;
k++ k++
) { ) {
tmpPosHighlight.push(textContent[k].posKey); tmpPosHighlight.push(textContent[k].posKey);
@ -175,7 +172,7 @@ export default function PDFViewer({
> >
<Document <Document
key={pdfKey} key={pdfKey}
file={`${API_HOST}/api/pitch_book/${pitchBookId}/download`} file={`http://localhost:5050/api/pitch_book/${pitchBookId}/download`}
onLoadSuccess={onDocumentLoadSuccess} onLoadSuccess={onDocumentLoadSuccess}
onLoadError={(error) => onLoadError={(error) =>
console.error("Es gab ein Fehler beim Laden des PDFs:", error) console.error("Es gab ein Fehler beim Laden des PDFs:", error)

View File

@ -11,7 +11,6 @@
// 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'
@ -21,12 +20,6 @@ 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',
@ -89,13 +82,6 @@ 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'
@ -126,7 +112,6 @@ 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
@ -136,7 +121,6 @@ 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
@ -147,7 +131,6 @@ 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
@ -159,7 +142,6 @@ 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,7 +150,6 @@ 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'
@ -177,7 +158,6 @@ 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'
@ -188,7 +168,6 @@ 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
@ -198,7 +177,6 @@ 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,
@ -217,7 +195,6 @@ 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"
@ -232,9 +209,6 @@ 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

@ -3,31 +3,17 @@ import { Box, Typography, IconButton } from "@mui/material";
import ArrowBackIcon from "@mui/icons-material/ArrowBack"; import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { KPIForm } from "../components/KPIForm"; import { KPIForm } from "../components/KPIForm";
import type { Kennzahl } from "../types/kpi"; import type { Kennzahl } from "../types/kpi";
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 {
const existingKPIsResponse = await fetch(`${API_HOST}/api/kpi_setting/`); const existingKPIsResponse = await fetch('http://localhost:5050/api/kpi_setting/');
const existingKPIs = await existingKPIsResponse.json(); const existingKPIs = await existingKPIsResponse.json();
const maxPosition = existingKPIs.length > 0 const maxPosition = existingKPIs.length > 0
? Math.max(...existingKPIs.map((kpi: Kennzahl) => kpi.position)) ? Math.max(...existingKPIs.map((kpi: Kennzahl) => kpi.position))
@ -39,7 +25,7 @@ function ConfigAddPage() {
active: formData.active !== false active: formData.active !== false
}; };
const response = await fetch(`${API_HOST}/api/kpi_setting/`, { const response = await fetch('http://localhost:5050/api/kpi_setting/', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -82,7 +68,7 @@ function ConfigAddPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={handleBack}> <IconButton onClick={() => navigate({ to: "/config" })}>
<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,38 +6,24 @@ import { useEffect, useState } from "react";
import type { Kennzahl } from "../types/kpi"; import type { Kennzahl } from "../types/kpi";
import { KPIForm } from "../components/KPIForm"; import { KPIForm } from "../components/KPIForm";
import { typeDisplayMapping } from "../types/kpi"; import { typeDisplayMapping } from "../types/kpi";
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 {
setLoading(true); setLoading(true);
const response = await fetch(`${API_HOST}/api/kpi_setting/${kpiId}`); const response = await fetch(`http://localhost:5050/api/kpi_setting/${kpiId}`);
if (!response.ok) { if (!response.ok) {
if (response.status === 404) { if (response.status === 404) {
setError('KPI not found'); setError('KPI not found');
@ -61,7 +47,7 @@ function KPIDetailPage() {
const handleSave = async (formData: Partial<Kennzahl>) => { const handleSave = async (formData: Partial<Kennzahl>) => {
try { try {
const response = await fetch(`${API_HOST}/api/kpi_setting/${kpiId}`, { const response = await fetch(`http://localhost:5050/api/kpi_setting/${kpiId}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -152,7 +138,7 @@ function KPIDetailPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={handleBack}> <IconButton onClick={() => navigate({ to: "/config" })}>
<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}>
@ -263,7 +249,7 @@ function KPIDetailPage() {
mb={4} mb={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={handleBack}> <IconButton onClick={() => navigate({ to: "/config" })}>
<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,29 +6,13 @@ 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({ navigate({ to: "/config-add" });
to: "/config-add",
search: from ? { from } : undefined
});
};
const handleBack = () => {
if (from === "pitchbooks") {
navigate({ to: "/pitchbooks" });
} else {
navigate({ to: "/" });
}
}; };
return ( return (
@ -50,7 +34,7 @@ function ConfigPage() {
px={4} px={4}
> >
<Box display="flex" alignItems="center"> <Box display="flex" alignItems="center">
<IconButton onClick={handleBack}> <IconButton onClick={() => navigate({ to: "/" })}>
<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}>
@ -69,7 +53,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 from={from} /> <ConfigTable />
</Box> </Box>
</Box> </Box>
); );

View File

@ -1,42 +1,26 @@
import ContentPasteIcon from "@mui/icons-material/ContentPaste"; import ContentPasteIcon from "@mui/icons-material/ContentPaste";
import { Box, Button, Paper, Typography, Snackbar, Alert, IconButton } from "@mui/material"; import { Box, Button, Paper, Typography } 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, useMemo } from "react"; import { useCallback, 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, 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,
validateSearch: (search: Record<string, unknown>): { from?: string } => { loader: ({ context: { queryClient }, params: { pitchBook } }) =>
return { Promise.allSettled([
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 { from } = Route.useSearch(); const status: "green" | "yellow" | "red" = "red";
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",
@ -47,106 +31,18 @@ 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 prepareClipboardData = () => { const { data: kpi } = useSuspenseQuery(kpiQueryOptions(pitchBook));
const activeSettings = settings const { data: settings } = useSuspenseQuery(settingsQueryOptions());
.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,
@ -188,7 +84,6 @@ function ExtractedResultsPage() {
onPageClick={onSiteClick} onPageClick={onSiteClick}
data={kpi} data={kpi}
pdfId={pitchBook} pdfId={pitchBook}
from={from}
/> />
</Paper> </Paper>
<Box <Box
@ -235,10 +130,9 @@ 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 }} />
{copied ? "Kopiert!" : "Kennzahlenzeile kopieren"} Kennzahlenzeile kopieren
</Button> </Button>
<Button <Button
variant="contained" variant="contained"
@ -250,21 +144,6 @@ 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,24 +30,11 @@ 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,
validateSearch: (search: Record<string, unknown>) => { loader: ({ context: { queryClient }, params: { pitchBook } }) =>
return { queryClient.ensureQueryData(kpiQueryOptions(pitchBook)),
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() {
@ -55,7 +42,6 @@ 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));
@ -76,21 +62,9 @@ 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()] = [
{ {
...baseObject, ...kpiValues[0],
entity: selectedValue, entity: selectedValue,
}, },
]; ];
@ -103,7 +77,6 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
}, },
onError: (error) => { onError: (error) => {
@ -144,7 +117,6 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
} }
}; };
@ -154,7 +126,6 @@ function ExtractedResultsPage() {
navigate({ navigate({
to: "/extractedResult/$pitchBook", to: "/extractedResult/$pitchBook",
params: { pitchBook }, params: { pitchBook },
search: from ? { from } : undefined
}); });
}; };

View File

@ -1,59 +0,0 @@
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

@ -1,7 +1,6 @@
import { io } from "socket.io-client"; import { io } from "socket.io-client";
import { API_HOST } from "./util/api";
// "undefined" means the URL will be computed from the `window.location` object // "undefined" means the URL will be computed from the `window.location` object
// const URL = process.env.NODE_ENV === 'production' ? undefined : 'http://localhost:4000'; // const URL = process.env.NODE_ENV === 'production' ? undefined : 'http://localhost:4000';
export const socket = io(`${API_HOST}`); export const socket = io("http://localhost:5050");

View File

@ -1,9 +1,5 @@
import type { Kennzahl } from "@/types/kpi"; import type { Kennzahl } from "@/types/kpi";
const API_HOST = import.meta.env.VITE_API_HOST || "http://localhost:5050";
export { API_HOST };
export const fetchKPI = async ( export const fetchKPI = async (
pitchBookId: string, pitchBookId: string,
): Promise<{ ): Promise<{
@ -15,7 +11,9 @@ export const fetchKPI = async (
source: string; source: string;
}[]; }[];
}> => { }> => {
const response = await fetch(`${API_HOST}/api/pitch_book/${pitchBookId}`); const response = await fetch(
`http://localhost:5050/api/pitch_book/${pitchBookId}`,
);
const data = await response.json(); const data = await response.json();
return data.kpi ? getKPI(data.kpi) : {}; return data.kpi ? getKPI(data.kpi) : {};
@ -44,10 +42,13 @@ export const fetchPutKPI = async (
const formData = new FormData(); const formData = new FormData();
formData.append("kpi", JSON.stringify(flattenKPIArray(kpi))); formData.append("kpi", JSON.stringify(flattenKPIArray(kpi)));
const response = await fetch(`${API_HOST}/api/pitch_book/${pitchBookId}`, { const response = await fetch(
`http://localhost:5050/api/pitch_book/${pitchBookId}`,
{
method: "PUT", method: "PUT",
body: formData, body: formData,
}); },
);
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
@ -98,7 +99,7 @@ export const flattenKPIArray = (kpi: {
}; };
export const fetchKennzahlen = async (): Promise<Kennzahl[]> => { export const fetchKennzahlen = async (): Promise<Kennzahl[]> => {
const response = await fetch(`${API_HOST}/api/kpi_setting/`); const response = await fetch("http://localhost:5050/api/kpi_setting/");
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
@ -106,19 +107,3 @@ 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();
}
export async function fetchPitchBooksById(id: number) {
const response = await fetch(`${API_HOST}/api/pitch_book/${id}`);
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, fetchPitchBooks } from "./api"; import { fetchKPI, fetchKennzahlen } from "./api";
export const kpiQueryOptions = (pitchBookId: string) => export const kpiQueryOptions = (pitchBookId: string) =>
queryOptions({ queryOptions({
@ -12,10 +12,3 @@ export const settingsQueryOptions = () =>
queryKey: ["pitchBookSettings"], queryKey: ["pitchBookSettings"],
queryFn: () => fetchKennzahlen(), queryFn: () => fetchKennzahlen(),
}); });
export const pitchBooksQueryOptions = () =>
queryOptions({
queryKey: ["pitchBooks"],
queryFn: fetchPitchBooks,
staleTime: 30000,
});