Stelle den Frontend-MVP und die v0.3-API auf develop bereit, damit Dev API und PWA zusammen deployen.
Deploy Development / deploy (push) Successful in 1m19s
Test Suite / pytest-backend (push) Successful in 31s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-checks (push) Successful in 28s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-04 13:04:59 +02:00
1 parent 827e6a2a11
commit b276758ee1
152 files changed
+25846 -34

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
+12
View File
@@ -0,0 +1,12 @@
# Buying Agent Frontend
React + TypeScript + Vite PWA. Das Frontend konsumiert ausschließlich `/api/v1`.
```bash
npm install
npm run dev
npm test
npm run build
```
Lokaler Vite-Devserver proxyt `/api` auf `http://127.0.0.1:8000`.
+7
View File
@@ -0,0 +1,7 @@
import { expect, test } from "@playwright/test";
test("opens the project list on desktop and mobile viewports", async ({ page }) => {
const response = await page.goto("/projects");
if (!response || response.status() >= 500) test.skip(true, "frontend not running");
await expect(page.getByRole("heading", { name: "Projekte" })).toBeVisible();
});
+6
View File
@@ -0,0 +1,6 @@
import tseslint from "typescript-eslint";
export default tseslint.config(
tseslint.configs.recommended,
{ ignores: ["dist"] },
);
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#111318" />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<title>Buying Agent</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+21
View File
@@ -0,0 +1,21 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://api:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /health {
proxy_pass http://api:8000;
proxy_set_header Host $host;
}
location / {
try_files $uri $uri/ /index.html;
}
}
+8837
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
{
"name": "buying-agent-frontend",
"private": true,
"version": "0.3.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -p tsconfig.app.json --noEmit && vite build",
"preview": "vite preview",
"lint": "eslint src",
"typecheck": "tsc -p tsconfig.app.json --pretty false --noEmit",
"test": "vitest run",
"e2e": "playwright test"
},
"dependencies": {
"@tanstack/react-query": "^5.90.2",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-router-dom": "^7.9.3"
},
"devDependencies": {
"@playwright/test": "^1.55.1",
"@testing-library/jest-dom": "^6.8.0",
"@testing-library/react": "^16.3.0",
"@types/react": "^19.1.13",
"@types/react-dom": "^19.1.9",
"@vitejs/plugin-react": "^5.0.3",
"eslint": "^9.36.0",
"jsdom": "^27.0.0",
"typescript": "^5.9.2",
"typescript-eslint": "^8.44.1",
"vite": "^7.1.7",
"vite-plugin-pwa": "^1.0.3",
"vitest": "^3.2.4"
}
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "./e2e",
use: { baseURL: process.env.PLAYWRIGHT_BASE_URL || "http://127.0.0.1:4173" },
projects: [
{ name: "desktop", use: { ...devices["Desktop Chrome"] } },
{ name: "mobile", use: { ...devices["Pixel 5"] } },
],
});
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#1d4ed8"/>
<path d="M16 40V24l16-8 16 8v16l-16 8-16-8z" fill="none" stroke="#fff" stroke-width="3"/>
</svg>

After

Width:  |  Height:  |  Size: 216 B

+9
View File
@@ -0,0 +1,9 @@
{
"name": "Buying Agent",
"short_name": "BuyingAgent",
"start_url": "/",
"display": "standalone",
"background_color": "#111318",
"theme_color": "#111318",
"icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" }]
}
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Offline</title>
</head>
<body>
<p>Buying Agent ist offline. Bitte Verbindung prüfen und erneut versuchen.</p>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
import { NavLink, Route, Routes } from "react-router-dom";
import { AdminPage } from "./pages/AdminPage";
import { CandidateDetailPage } from "./pages/CandidateDetailPage";
import { ProjectDetailPage } from "./pages/ProjectDetailPage";
import { ProjectListPage } from "./pages/ProjectListPage";
import { WizardPage } from "./pages/WizardPage";
function Nav() {
return (
<>
<NavLink to="/projects" end>
Projekte
</NavLink>
<NavLink to="/projects/new">Neu</NavLink>
<NavLink to="/admin/sources">Admin</NavLink>
</>
);
}
export function App() {
return (
<div className="app">
<aside className="sidebar">
<div className="brand">Buying Agent</div>
<nav className="nav">
<Nav />
</nav>
</aside>
<main className="main">
<Routes>
<Route path="/" element={<ProjectListPage />} />
<Route path="/projects" element={<ProjectListPage />} />
<Route path="/projects/new" element={<WizardPage />} />
<Route path="/projects/:projectId/*" element={<ProjectDetailPage />} />
<Route path="/projects/:projectId/candidates/:candidateId" element={<CandidateDetailPage />} />
<Route path="/admin/sources/*" element={<AdminPage />} />
</Routes>
</main>
<nav className="bottom-nav">
<Nav />
</nav>
</div>
);
}
+152
View File
@@ -0,0 +1,152 @@
const API = "/api/v1";
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`${API}${path}`, {
headers: { "Content-Type": "application/json", ...(init?.headers || {}) },
...init,
});
const body = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(body.message || `HTTP ${response.status}`);
}
return body as T;
}
export const api = {
productCategories: () => request<{ items: ProductCategory[] }>("/product-categories"),
categorySources: (id: string) => request<{ items: CategorySource[] }>(`/product-categories/${id}/sources`),
availableCriteria: (id: string, source: string) =>
request<AvailableCriteria>(`/product-categories/${id}/available-criteria?source=${encodeURIComponent(source)}`),
templates: () => request<{ items: BuyingTemplate[] }>("/buying-templates"),
projects: () => request<{ items: ProjectSummary[] }>("/buying-projects"),
project: (id: string) => request<ProjectDetail>(`/buying-projects/${id}`),
createProject: (payload: unknown) => request<ProjectDetail>("/buying-projects", { method: "POST", body: JSON.stringify(payload) }),
patchProject: (id: string, payload: unknown) =>
request<ProjectDetail>(`/buying-projects/${id}`, { method: "PATCH", body: JSON.stringify(payload) }),
putCriteria: (id: string, payload: unknown) =>
request<ProjectDetail>(`/buying-projects/${id}/criteria`, { method: "PUT", body: JSON.stringify(payload) }),
searches: (projectId: string) => request<{ items: DiscoverySearch[] }>(`/buying-projects/${projectId}/discovery-searches`),
createSearch: (projectId: string, payload: unknown) =>
request<DiscoverySearch>(`/buying-projects/${projectId}/discovery-searches`, { method: "POST", body: JSON.stringify(payload) }),
generateQuery: (searchId: string) => request<DiscoverySearch>(`/discovery-searches/${searchId}/generate-query`, { method: "POST" }),
runSearch: (searchId: string) => request<SearchRun>(`/discovery-searches/${searchId}/run`, { method: "POST" }),
runs: (searchId: string) => request<{ items: SearchRun[] }>(`/discovery-searches/${searchId}/runs`),
candidates: (projectId: string) => request<{ items: Candidate[] }>(`/buying-projects/${projectId}/candidates`),
candidate: (projectId: string, candidateId: string) =>
request<Candidate>(`/buying-projects/${projectId}/candidates/${candidateId}`),
observations: (projectId: string, candidateId: string) =>
request<{ items: Observation[] }>(`/buying-projects/${projectId}/candidates/${candidateId}/observations`),
shortlist: (projectId: string) => request<{ items: Candidate[] }>(`/buying-projects/${projectId}/shortlist`),
sources: () => request<{ items: Source[] }>("/sources"),
sourceCategories: (source: string) => request<{ items: SourceCategory[] }>(`/sources/${source}/categories`),
discoverTaxonomy: (source: string, category: string) =>
request<unknown>(`/sources/${source}/categories/${category}/discover-taxonomy`, { method: "POST" }),
filters: (source: string, category: string) => request<{ filters: SourceFilter[] }>(`/sources/${source}/categories/${category}/filters`),
};
export type ProductCategory = { id: string; name: string; status: string };
export type CategorySource = { source: string; source_category_id: string; display_name: string; status: string };
export type BuyingTemplate = { id: string; version: number; name: string; product_category_id?: string; market?: string; currency?: string };
export type ProjectSummary = {
id: string;
name: string;
product_category?: ProductCategory;
status: string;
last_successful_run_at?: string | null;
next_run_at?: string | null;
discovery_status?: string | null;
candidate_count: number;
shortlist_count: number;
new_count: number;
changed_count: number;
missing_count: number;
};
export type ProjectDetail = {
id: string;
name: string;
status: string;
product_category_id: string;
market: string;
currency: string;
target_budget?: string | null;
shortlist_size: number;
criteria_version: number;
ranking_status: string;
criteria?: { items: ProjectCriterion[] };
};
export type ProjectCriterion = {
id: string;
criterion_definition_id: string;
criterion?: string;
operator: string;
value: unknown;
enabled_for_discovery: boolean;
};
export type AvailableCriterion = {
criterion_definition_id: string;
label: string;
origin: string;
filter_type?: string | null;
unit?: string | null;
operators: string[];
options?: { source_value: string; normalized_value: unknown }[];
mapping_status?: string | null;
supports_discovery: boolean;
scoring_attribute_key?: string | null;
};
export type AvailableCriteria = { product_category_id: string; source: string; criteria: AvailableCriterion[] };
export type DiscoverySearch = {
id: string;
status: string;
generated_url: string;
schedule_interval_minutes: number;
next_run_at?: string | null;
last_successful_run_at?: string | null;
source_id: string;
source_category_id: string;
};
export type SearchRun = {
id: string;
status: string;
started_at: string;
finished_at?: string | null;
result_count: number;
page_count: number;
new_count: number;
changed_count: number;
unchanged_count: number;
missing_count: number;
error_code?: string | null;
};
export type Candidate = {
candidate_id: string;
title?: string;
manufacturer?: string | null;
model?: string | null;
source_url?: string | null;
current_best_price?: string | null;
currency?: string | null;
current_dynamic_attributes?: { raw_name: string; normalized_value: unknown; unit?: string | null }[];
product_score?: number | null;
product_eligibility?: string | null;
ranking_status: string;
shortlist_status: string;
current_diff_status?: string | null;
product_lifecycle_status?: string | null;
match_status?: string;
first_seen_at?: string;
last_seen_at?: string;
current_observation?: Observation | null;
};
export type Observation = {
observation_id: string;
observed_at: string;
best_price?: string | null;
currency?: string | null;
availability?: string | null;
seller_count?: number | null;
dynamic_attributes?: { raw_name: string; normalized_value: unknown }[];
};
export type Source = { id: string; name: string };
export type SourceCategory = { external_category_key: string; name: string; status: string };
export type SourceFilter = { label: string; external_filter_key: string; filter_type: string; status: string };
@@ -0,0 +1,33 @@
import { render, screen } from "@testing-library/react";
import { CriteriaControl, pickSource } from "./CriteriaControl";
const base = {
criterion_definition_id: "1",
label: "Arbeitsspeicher",
origin: "SOURCE",
operators: [">="],
supports_discovery: true,
};
test("renders numeric threshold without notebook-specific fields", () => {
render(
<CriteriaControl
criterion={{ ...base, filter_type: "NUMERIC_THRESHOLD", unit: "GB" }}
operator=">="
value={24}
onChange={() => undefined}
/>,
);
expect(screen.getByDisplayValue("24")).toBeInTheDocument();
expect(screen.queryByLabelText("RAM GB")).not.toBeInTheDocument();
});
test("picks a single active source automatically", () => {
expect(pickSource([{ source: "geizhals", status: "ACTIVE" }])).toBe("geizhals");
expect(
pickSource([
{ source: "geizhals", status: "ACTIVE" },
{ source: "idealo", status: "ACTIVE" },
]),
).toBeNull();
});
@@ -0,0 +1,71 @@
import type { AvailableCriterion } from "../api";
export function CriteriaControl({
criterion,
value,
operator,
onChange,
}: {
criterion: AvailableCriterion;
value: unknown;
operator: string;
onChange: (next: { operator: string; value: unknown }) => void;
}) {
const type = criterion.filter_type || "TEXT";
return (
<div className="grid">
<label>
Operator
<select value={operator} onChange={(event) => onChange({ operator: event.target.value, value })}>
{(criterion.operators.length ? criterion.operators : [">=", "<=", "="]).map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
</label>
{type === "BOOLEAN" ? (
<label>
Wert
<select
value={String(value ?? "true")}
onChange={(event) => onChange({ operator, value: event.target.value === "true" })}
>
<option value="true">ja</option>
<option value="false">nein</option>
</select>
</label>
) : type === "ENUM" || type === "MULTI_ENUM" ? (
<label>
Wert
<select
value={String(value ?? "")}
onChange={(event) => onChange({ operator, value: event.target.value })}
>
<option value="">Bitte wählen</option>
{(criterion.options || []).map((option) => (
<option key={option.source_value} value={String(option.normalized_value ?? option.source_value)}>
{option.source_value}
</option>
))}
</select>
</label>
) : (
<label>
Wert
<input
value={value == null ? "" : String(value)}
onChange={(event) => onChange({ operator, value: event.target.value })}
placeholder={criterion.unit || ""}
/>
</label>
)}
</div>
);
}
export function pickSource(sources: { source: string; status: string }[]) {
const active = sources.filter((item) => item.status === "ACTIVE");
if (active.length === 1) return active[0].source;
return null;
}
+20
View File
@@ -0,0 +1,20 @@
export function LoadingState() {
return <div className="state">Laden …</div>;
}
export function ErrorState({ message, onRetry }: { message: string; onRetry?: () => void }) {
return (
<div className="state">
<p className="danger">{message}</p>
{onRetry ? (
<button className="button" onClick={onRetry}>
Erneut versuchen
</button>
) : null}
</div>
);
}
export function EmptyState({ children }: { children: string }) {
return <div className="state">{children}</div>;
}
+18
View File
@@ -0,0 +1,18 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { App } from "./App";
import "./styles.css";
const client = new QueryClient();
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={client}>
<BrowserRouter>
<App />
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
);
+63
View File
@@ -0,0 +1,63 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { api } from "../api";
import { EmptyState, LoadingState } from "../components/State";
export function AdminPage() {
const sources = useQuery({ queryKey: ["sources"], queryFn: api.sources });
const source = sources.data?.items.find((item) => item.id === "geizhals")?.id || sources.data?.items[0]?.id || "";
const categories = useQuery({
queryKey: ["source-categories", source],
queryFn: () => api.sourceCategories(source),
enabled: Boolean(source),
});
const category = categories.data?.items[0]?.external_category_key || "";
const filters = useQuery({
queryKey: ["filters", source, category],
queryFn: () => api.filters(source, category),
enabled: Boolean(source && category),
});
const discover = useMutation({
mutationFn: () => api.discoverTaxonomy(source, category),
onSuccess: () => filters.refetch(),
});
if (sources.isLoading) return <LoadingState />;
return (
<section className="grid">
<h1>Quellen und Taxonomie</h1>
<p className="muted">Technische IDs sind nur hier sichtbar.</p>
<div className="card">
<p>Source: {source || "–"}</p>
<p>Kategorie: {category || "–"}</p>
<button className="button" disabled={!source || !category} onClick={() => discover.mutate()}>
Taxonomie laden
</button>
</div>
{!filters.data?.filters.length ? (
<EmptyState>Taxonomie wurde noch nicht geladen.</EmptyState>
) : (
<div className="card">
<table>
<thead>
<tr>
<th>Label</th>
<th>Filter</th>
<th>Typ</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{filters.data.filters.map((item) => (
<tr key={item.external_filter_key}>
<td>{item.label}</td>
<td>{item.external_filter_key}</td>
<td>{item.filter_type}</td>
<td>{item.status}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
@@ -0,0 +1,53 @@
import { useQuery } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { api } from "../api";
import { EmptyState, ErrorState, LoadingState } from "../components/State";
export function CandidateDetailPage() {
const { projectId = "", candidateId = "" } = useParams();
const detail = useQuery({
queryKey: ["candidate", projectId, candidateId],
queryFn: () => api.candidate(projectId, candidateId),
});
const history = useQuery({
queryKey: ["observations", projectId, candidateId],
queryFn: () => api.observations(projectId, candidateId),
});
if (detail.isLoading) return <LoadingState />;
if (detail.isError) return <ErrorState message={(detail.error as Error).message} />;
const item = detail.data!;
return (
<section className="grid">
<h1>{item.title}</h1>
<div className="card">
<p>
{item.manufacturer} {item.model}
</p>
<p>
Preis: {item.current_best_price || "–"} {item.currency || ""}
</p>
<p>Ranking: {item.ranking_status}</p>
<p>Diff: {item.current_diff_status}</p>
<p>Lifecycle: {item.product_lifecycle_status}</p>
</div>
<div className="card">
<h2>Attribute</h2>
{(item.current_dynamic_attributes || []).map((attr) => (
<p key={attr.raw_name}>
{attr.raw_name}: {String(attr.normalized_value ?? "")} {attr.unit || ""}
</p>
))}
</div>
<div className="card">
<h2>Historie</h2>
{history.isLoading ? <LoadingState /> : null}
{(history.data?.items || []).length === 0 ? <EmptyState>Noch keine Beobachtungen.</EmptyState> : null}
{(history.data?.items || []).map((obs) => (
<p key={obs.observation_id}>
{obs.observed_at}: {obs.best_price} {obs.currency}
</p>
))}
</div>
</section>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { api } from "../api";
import { EmptyState, ErrorState, LoadingState } from "../components/State";
export function CandidateList({ projectId, shortlist = false }: { projectId: string; shortlist?: boolean }) {
const project = useQuery({ queryKey: ["project", projectId], queryFn: () => api.project(projectId) });
const query = useQuery({
queryKey: [shortlist ? "shortlist" : "candidates", projectId],
queryFn: () => (shortlist ? api.shortlist(projectId) : api.candidates(projectId)),
});
if (query.isLoading || project.isLoading) return <LoadingState />;
if (query.isError) return <ErrorState message={(query.error as Error).message} />;
const items = query.data?.items || [];
if (shortlist && project.data?.ranking_status === "NOT_CONFIGURED") {
return <EmptyState>Ranking ist noch nicht konfiguriert.</EmptyState>;
}
if (!items.length) return <EmptyState>Noch keine Kandidaten gefunden.</EmptyState>;
return (
<div className="card">
<table>
<thead>
<tr>
<th>Titel</th>
<th>Preis</th>
<th>Diff</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.candidate_id}>
<td>
<Link to={`/projects/${projectId}/candidates/${item.candidate_id}`}>{item.title || "Kandidat"}</Link>
</td>
<td>{item.current_best_price ? `${item.current_best_price} ${item.currency || ""}` : "–"}</td>
<td>{item.current_diff_status || "–"}</td>
<td>{item.ranking_status === "NOT_CONFIGURED" ? "n/a" : item.product_score ?? "–"}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+127
View File
@@ -0,0 +1,127 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { NavLink, Route, Routes, useParams } from "react-router-dom";
import { api } from "../api";
import { EmptyState, ErrorState, LoadingState } from "../components/State";
import { CandidateList } from "./CandidateList";
export function ProjectDetailPage() {
const { projectId = "" } = useParams();
const project = useQuery({ queryKey: ["project", projectId], queryFn: () => api.project(projectId) });
if (project.isLoading) return <LoadingState />;
if (project.isError) return <ErrorState message={(project.error as Error).message} />;
const data = project.data!;
return (
<section>
<h1>{data.name}</h1>
<p className="muted">
{data.product_category_id} · {data.market}/{data.currency} · Version {data.criteria_version}
</p>
<div className="tabs">
<NavLink to={`/projects/${projectId}`} end>
Übersicht
</NavLink>
<NavLink to={`/projects/${projectId}/candidates`}>Kandidaten</NavLink>
<NavLink to={`/projects/${projectId}/shortlist`}>Shortlist</NavLink>
<NavLink to={`/projects/${projectId}/criteria`}>Kriterien</NavLink>
<NavLink to={`/projects/${projectId}/history`}>Historie</NavLink>
</div>
<Routes>
<Route index element={<Overview projectId={projectId} />} />
<Route path="candidates" element={<CandidateList projectId={projectId} />} />
<Route path="shortlist" element={<CandidateList projectId={projectId} shortlist />} />
<Route path="criteria" element={<CriteriaPanel projectId={projectId} />} />
<Route path="history" element={<HistoryPanel projectId={projectId} />} />
</Routes>
</section>
);
}
function Overview({ projectId }: { projectId: string }) {
const searches = useQuery({ queryKey: ["searches", projectId], queryFn: () => api.searches(projectId) });
const run = useMutation({
mutationFn: async (searchId: string) => {
await api.generateQuery(searchId);
return api.runSearch(searchId);
},
});
if (searches.isLoading) return <LoadingState />;
const items = searches.data?.items || [];
if (!items.length) return <EmptyState>Noch kein SearchRun ausgeführt.</EmptyState>;
return (
<div className="grid">
{items.map((search) => (
<div className="card" key={search.id}>
<p>Status: {search.status}</p>
{search.status === "OUT_OF_SYNC" ? <p>Suchparameter wurden geändert. Die externe Suche muss aktualisiert werden.</p> : null}
<button className="button" onClick={() => run.mutate(search.id)}>
Suche aktualisieren
</button>
</div>
))}
</div>
);
}
function CriteriaPanel({ projectId }: { projectId: string }) {
const client = useQueryClient();
const project = useQuery({ queryKey: ["project", projectId], queryFn: () => api.project(projectId) });
const save = useMutation({
mutationFn: () => api.putCriteria(projectId, { items: project.data?.criteria?.items || [] }),
onSuccess: () => client.invalidateQueries({ queryKey: ["project", projectId] }),
});
if (project.isLoading) return <LoadingState />;
const items = project.data?.criteria?.items || [];
return (
<div className="card grid">
{items.map((item) => (
<p key={item.id}>
{item.criterion || item.criterion_definition_id} {item.operator} {String(item.value)}
</p>
))}
<button className="button secondary" onClick={() => save.mutate()}>
Kriterienversion fortschreiben
</button>
</div>
);
}
function HistoryPanel({ projectId }: { projectId: string }) {
const searches = useQuery({ queryKey: ["searches", projectId], queryFn: () => api.searches(projectId) });
const searchId = searches.data?.items[0]?.id;
const runs = useQuery({
queryKey: ["runs", searchId],
queryFn: () => api.runs(searchId!),
enabled: Boolean(searchId),
});
if (!searchId) return <EmptyState>Noch kein SearchRun ausgeführt.</EmptyState>;
if (runs.isLoading) return <LoadingState />;
const items = runs.data?.items || [];
return (
<div className="card">
<table>
<thead>
<tr>
<th>Zeit</th>
<th>Status</th>
<th>Treffer</th>
<th>NEW</th>
<th>CHANGED</th>
<th>MISSING</th>
</tr>
</thead>
<tbody>
{items.map((run) => (
<tr key={run.id}>
<td>{run.started_at}</td>
<td>{run.status}</td>
<td>{run.result_count}</td>
<td>{run.new_count}</td>
<td>{run.changed_count}</td>
<td>{run.missing_count}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+53
View File
@@ -0,0 +1,53 @@
import { useQuery } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { api } from "../api";
import { EmptyState, ErrorState, LoadingState } from "../components/State";
export function ProjectListPage() {
const query = useQuery({ queryKey: ["projects"], queryFn: api.projects });
if (query.isLoading) return <LoadingState />;
if (query.isError) return <ErrorState message={(query.error as Error).message} onRetry={() => query.refetch()} />;
const items = query.data?.items || [];
return (
<section>
<div className="row">
<h1>Projekte</h1>
<Link className="button" to="/projects/new">
Neues Projekt
</Link>
</div>
{items.length === 0 ? (
<EmptyState>Noch keine Projekte vorhanden.</EmptyState>
) : (
<div className="card">
<table>
<thead>
<tr>
<th>Name</th>
<th>Kategorie</th>
<th>Status</th>
<th>Suche</th>
<th>Kandidaten</th>
<th>Neu</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
<td>
<Link to={`/projects/${item.id}`}>{item.name}</Link>
</td>
<td>{item.product_category?.name || "–"}</td>
<td>{item.status}</td>
<td>{item.discovery_status || "–"}</td>
<td>{item.candidate_count}</td>
<td>{item.new_count}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
);
}
+185
View File
@@ -0,0 +1,185 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api, type AvailableCriterion } from "../api";
import { CriteriaControl, pickSource } from "../components/CriteriaControl";
import { EmptyState, ErrorState, LoadingState } from "../components/State";
type Draft = Record<string, { operator: string; value: unknown }>;
export function WizardPage() {
const navigate = useNavigate();
const categories = useQuery({ queryKey: ["product-categories"], queryFn: api.productCategories });
const [name, setName] = useState("");
const [categoryId, setCategoryId] = useState("");
const [market, setMarket] = useState("DE");
const [currency, setCurrency] = useState("EUR");
const [budget, setBudget] = useState("");
const [sourceOverride, setSourceOverride] = useState<string | null>(null);
const [selected, setSelected] = useState<string[]>([]);
const [draft, setDraft] = useState<Draft>({});
const sources = useQuery({
queryKey: ["category-sources", categoryId],
queryFn: () => api.categorySources(categoryId),
enabled: Boolean(categoryId),
});
const source = sourceOverride || pickSource(sources.data?.items || []);
const criteria = useQuery({
queryKey: ["available-criteria", categoryId, source],
queryFn: () => api.availableCriteria(categoryId, source!),
enabled: Boolean(categoryId && source),
});
const create = useMutation({
mutationFn: async () => {
if (!source || !sources.data) throw new Error("Keine Source verfügbar");
const chosen = (criteria.data?.criteria || []).filter((item) => selected.includes(item.criterion_definition_id));
const project = await api.createProject({
name,
product_category_id: categoryId,
market,
currency,
target_budget: budget || null,
criteria: {
items: chosen.map((item) => ({
criterion_definition_id: item.criterion_definition_id,
operator: draft[item.criterion_definition_id]?.operator || item.operators[0] || ">=",
value: coerce(item, draft[item.criterion_definition_id]?.value),
enabled_for_discovery: true,
})),
},
});
const sourceRow = sources.data.items.find((item) => item.source === source) || sources.data.items[0];
await api.createSearch(project.id, {
source_id: sourceRow.source,
source_category_id: sourceRow.source_category_id,
});
return project;
},
onSuccess: (project) => navigate(`/projects/${project.id}`),
});
const sourceItems = sources.data?.items || [];
const needsPicker = sourceItems.filter((item) => item.status === "ACTIVE").length > 1;
const visible = useMemo(() => criteria.data?.criteria || [], [criteria.data]);
if (categories.isLoading) return <LoadingState />;
if (categories.isError) return <ErrorState message={(categories.error as Error).message} />;
return (
<section className="grid">
<h1>Neues Projekt</h1>
<div className="card grid">
<label>
Projektname
<input value={name} onChange={(event) => setName(event.target.value)} />
</label>
<label>
Produktkategorie
<select
value={categoryId}
onChange={(event) => {
setCategoryId(event.target.value);
setSourceOverride(null);
setSelected([]);
}}
>
<option value="">Bitte wählen</option>
{(categories.data?.items || []).map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<div className="row">
<label>
Markt
<input value={market} onChange={(event) => setMarket(event.target.value)} />
</label>
<label>
Währung
<input value={currency} onChange={(event) => setCurrency(event.target.value)} />
</label>
<label>
Zielbudget optional
<input value={budget} onChange={(event) => setBudget(event.target.value)} />
</label>
</div>
</div>
{categoryId && sources.isLoading ? <LoadingState /> : null}
{categoryId && !sources.isLoading && sourceItems.length === 0 ? (
<EmptyState>Keine Source für diese Produktkategorie verfügbar.</EmptyState>
) : null}
{needsPicker ? (
<label>
Quelle
<select value={source || ""} onChange={(event) => setSourceOverride(event.target.value)}>
{sourceItems.map((item) => (
<option key={item.source} value={item.source}>
{item.display_name}
</option>
))}
</select>
</label>
) : source ? (
<p className="muted">Quelle: {source}</p>
) : null}
{criteria.isLoading ? <LoadingState /> : null}
{visible.length > 0 ? (
<div className="card grid">
{visible.map((item) => {
const on = selected.includes(item.criterion_definition_id);
return (
<div key={item.criterion_definition_id}>
<label>
<input
type="checkbox"
checked={on}
onChange={(event) => {
setSelected((current) =>
event.target.checked
? [...current, item.criterion_definition_id]
: current.filter((id) => id !== item.criterion_definition_id),
);
setDraft((current) => ({
...current,
[item.criterion_definition_id]: current[item.criterion_definition_id] || {
operator: item.operators[0] || ">=",
value: "",
},
}));
}}
/>{" "}
{item.label}
</label>
{on ? (
<CriteriaControl
criterion={item}
operator={draft[item.criterion_definition_id]?.operator || item.operators[0] || ">="}
value={draft[item.criterion_definition_id]?.value}
onChange={(next) => setDraft((current) => ({ ...current, [item.criterion_definition_id]: next }))}
/>
) : null}
</div>
);
})}
</div>
) : null}
{create.isError ? <ErrorState message={(create.error as Error).message} /> : null}
<button className="button" disabled={!name || !categoryId || selected.length === 0 || create.isPending} onClick={() => create.mutate()}>
Projekt speichern
</button>
</section>
);
}
function coerce(criterion: AvailableCriterion, value: unknown) {
if (value == null || value === "") return value;
if ((criterion.filter_type || "").startsWith("NUMERIC")) return Number(value);
return value;
}
+41
View File
@@ -0,0 +1,41 @@
:root {
color-scheme: dark;
font-family: "Segoe UI", sans-serif;
background: #111318;
color: #e8eaed;
}
* { box-sizing: border-box; }
body { margin: 0; }
a { color: inherit; text-decoration: none; }
button, input, select { font: inherit; }
.app { min-height: 100vh; display: flex; }
.sidebar { width: 220px; padding: 20px 16px; border-right: 1px solid #2a2d36; display: flex; flex-direction: column; gap: 12px; }
.brand { font-weight: 700; letter-spacing: 0.04em; }
.nav a, .bottom-nav a { display: block; padding: 8px 10px; border-radius: 8px; color: #b8bcc6; }
.nav a.active, .bottom-nav a.active { background: #1d4ed8; color: white; }
.main { flex: 1; padding: 24px; }
.bottom-nav { display: none; }
h1 { font-size: 24px; margin: 0 0 16px; }
h2 { font-size: 18px; }
.card { background: #181b22; border: 1px solid #2a2d36; border-radius: 12px; padding: 16px; }
.row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
.grid { display: grid; gap: 12px; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 8px 6px; border-bottom: 1px solid #2a2d36; }
.muted { color: #9aa0ad; }
.danger { color: #f87171; }
.button { background: #1d4ed8; color: white; border: 0; border-radius: 8px; padding: 8px 14px; cursor: pointer; }
.button.secondary { background: #2a2d36; }
input, select { background: #111318; color: #e8eaed; border: 1px solid #3a3f4b; border-radius: 8px; padding: 8px; width: 100%; }
label { display: grid; gap: 6px; font-size: 14px; }
.tabs { display: flex; gap: 8px; margin-bottom: 16px; }
.tabs a { padding: 6px 10px; border-radius: 8px; background: #181b22; }
.tabs a.active { background: #1d4ed8; }
.state { padding: 24px; color: #9aa0ad; }
@media (max-width: 800px) {
.app { flex-direction: column; }
.sidebar { display: none; }
.bottom-nav { display: flex; position: sticky; bottom: 0; background: #181b22; border-top: 1px solid #2a2d36; }
.bottom-nav a { flex: 1; text-align: center; }
.main { padding: 16px 16px 72px; }
}
+1
View File
@@ -0,0 +1 @@
import "@testing-library/jest-dom/vitest";
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"types": ["vitest/globals"]
},
"include": ["src"]
}
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }]
}
+46
View File
@@ -0,0 +1,46 @@
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { VitePWA } from "vite-plugin-pwa";
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: "autoUpdate",
manifest: {
name: "Buying Agent",
short_name: "BuyingAgent",
start_url: "/",
display: "standalone",
background_color: "#111318",
theme_color: "#111318",
icons: [
{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any" },
],
},
workbox: {
navigateFallback: "/offline.html",
runtimeCaching: [
{
urlPattern: ({ request }) => request.mode === "navigate",
handler: "NetworkFirst",
},
],
},
}),
],
server: {
port: 5173,
proxy: {
"/api": "http://127.0.0.1:8000",
"/health": "http://127.0.0.1:8000",
},
},
test: {
environment: "jsdom",
globals: true,
setupFiles: "./src/test-setup.ts",
exclude: ["e2e/**", "node_modules/**"],
},
});