1
0
Fork 0

Merge branch 'feature/kanban-dashboard'

# Conflicts:
#	CLAUDE.md
This commit is contained in:
Jonny 2026-07-08 15:51:30 +02:00
commit e038facd92
16 changed files with 752 additions and 13 deletions

15
.claude/settings.json Normal file
View File

@ -0,0 +1,15 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "python -c \"import sys,json; d=json.load(sys.stdin); fp=d.get('tool_input',{}).get('file_path') or d.get('tool_response',{}).get('filePath'); print(fp or '')\" | { IFS= read -r f; f=\"${f%$'\r'}\"; case \"$f\" in *.ts|*.tsx) root=$(git rev-parse --show-toplevel 2>/dev/null); (cd \"$root/web\" && npx eslint --fix \"$f\") 2>/dev/null;; esac; } || true"
}
]
}
]
}
}

View File

@ -0,0 +1,63 @@
---
name: curl-server-action
description: Technique for driving this project's Next.js Server Actions via curl, without a browser — for manual/live verification of forms and mutations. Use whenever you need to test a Server Action (login, form submit, a drag-triggered action) from the command line.
---
# Driving Next.js Server Actions with curl
Next.js Server Actions (`"use server"` functions used as `<form action={fn}>` or called directly) don't accept a plain `-d key=value` POST — the framework encodes the action reference into the request, and the encoding differs depending on whether the action is **bound** or **unbound**.
## Step 1: find the action encoding in the rendered HTML
```bash
curl -s http://localhost:<port>/<page> -o page.html
```
**Unbound action** (`<form action={someFn}>`, no `.bind()`): look for a single hidden field:
```bash
grep -o '\$ACTION_ID_[a-z0-9]*' page.html
```
This hash **changes on every dev-server restart/rebuild** — always re-read it fresh from the current page load, never reuse a previously-seen value.
**Bound action** (`someFn.bind(null, arg1, arg2)`): look for a triple of fields instead:
```bash
grep -o '\$ACTION_REF_[a-z0-9]*\|\$ACTION_[a-z0-9]*:[01]' page.html
```
- `$ACTION_REF_<n>` — empty-valued field referencing the action
- `$ACTION_<n>:0` — bound marker, value `"$@1"`
- `$ACTION_<n>:1` — JSON array of the bound arguments, e.g. `["abholort"]`
## Step 2: submit with the matching fields
Unbound:
```bash
HASH=$(curl -s http://localhost:<port>/login | grep -o '\$ACTION_ID_[a-z0-9]*' | head -1)
curl -s -c cookies.txt -X POST http://localhost:<port>/login \
-F "${HASH}=" \
-F 'email=admin@aushilfsfahrer.local' \
-F 'password=Admin123!' \
-L -o response.html -w "HTTP_STATUS:%{http_code} FINAL_URL:%{url_effective}\n"
```
Bound (three extra `-F` fields instead of one):
```bash
curl -s -b cookies.txt -X POST http://localhost:<port>/some-page \
-F '$ACTION_REF_3=' \
-F '$ACTION_3:0={"id":"...","bound":"$@1"}' \
-F '$ACTION_3:1=["abholort"]' \
-F 'other_form_field=value' \
-L -o response.html -w "HTTP_STATUS:%{http_code} FINAL_URL:%{url_effective}\n"
```
Reuse the cookie jar (`-b cookies.txt -c cookies.txt`) across requests to stay authenticated.
## Gotchas
- If a page renders **multiple** Server Action forms at once (e.g. a page with both a logout button and a content form), a naive `grep | head -1` may grab the wrong action's ID. Narrow the grep with surrounding context (e.g. `grep -B2 -A2 'Submit-Button-Label'`) or inspect the embedded JSON payload in the HTML, which includes `"name":"<functionName>"` next to the matching action id — use that to confirm you've got the right one.
- A plain `.env.local` misconfiguration (pointing at the wrong Supabase stack — see the `supabase-local-dev` skill) will make login *appear* to fail with a generic error even though the curl technique itself is correct. Verify the target stack before assuming the encoding is wrong.

View File

@ -0,0 +1,52 @@
---
name: rebuild-master-stack
description: Rebuilds and restarts the docker-compose "web" service with the current master branch code, then verifies it's serving. Use only when the user explicitly asks to see their changes live in the master/production-like stack (e.g. after merging a feature branch).
disable-model-invocation: true
---
# Rebuild Master Stack
Only run this when the user explicitly asks (e.g. "rebuild the container", "show me this live", "restart the stack"). Never trigger it proactively — it restarts a shared, potentially-in-use service.
## Steps
1. Confirm you're operating from the main repo checkout (not a worktree), on `master`, with the change you want to deploy already merged there.
2. Rebuild the `web` image:
```bash
docker compose build web
```
If this is the first rebuild after a task that added new npm dependencies (check `web/package.json` diff against the previous deployed state), the build step already runs `npm install` inside the Docker build — no separate action needed there. But if you're instead testing directly against a local `npm run dev` outside Docker, remember to run `npm install` in `web/` yourself first (new dependencies aren't picked up automatically).
3. Restart just the `web` container with the new image:
```bash
docker compose up -d web
```
4. Verify it's actually serving the new code, not a stale cached image:
```bash
sleep 3
curl -s -o /dev/null -w "Status: %{http_code}\n" http://localhost:3000/login
docker exec aushilfsfahrer-web-1 sh -c "ls /app/.next/server/app/<new-route-added-by-this-change> 2>&1"
```
Pick a route that's specific to whatever just shipped (e.g. a new page directory) so you're confirming the *new* build actually landed, not just that *some* build is running.
5. If the merge included new Supabase migrations, apply them to the master stack's database too — it does **not** share a database with the local Supabase CLI dev stack (see the `supabase-local-dev` skill). Check which migrations are missing:
```bash
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c "select version from supabase_migrations.schema_migrations order by version;"
```
Apply any missing migration files directly and record them:
```bash
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -v ON_ERROR_STOP=1 < supabase/migrations/<file>.sql
docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c "insert into supabase_migrations.schema_migrations (version) values ('<version>') on conflict (version) do nothing;"
```
Report the admin login URL/credentials back to the user once verified (`admin@aushilfsfahrer.local` / `Admin123!`, or the current password — see the `supabase-local-dev` skill if it's been reset).

View File

@ -0,0 +1,57 @@
---
name: supabase-local-dev
description: Reference for working with this project's self-hosted Supabase stack — CLI working directory, the two parallel stacks running on this machine, test admin credentials, and pgTAP fixture conventions. Use whenever running supabase CLI commands, writing/debugging pgTAP tests, or verifying RLS behavior live.
---
# Supabase Local Dev — Reference
## Run CLI commands from the repo root, never from `web/`
```bash
npx supabase status
npx supabase start
npx supabase db reset
npx supabase test db
```
All of these must run from the repository root (where `supabase/` lives), not from `web/`. Running them from `web/` fails silently or picks up the wrong project config.
## Two parallel stacks — don't mix them
This machine typically runs **two independent Supabase stacks at once**:
1. **Local Supabase CLI dev stack** (`npx supabase start`) — containers named `supabase_*_fundament-auth-rollen`, API on `http://127.0.0.1:54321`, Postgres on port 54322. This is the stack all automated task/review verification in this project uses.
2. **Docker-Compose "master" stack** (`docker compose up -d`, defined in the repo's `docker-compose.yaml`) — containers named `aushilfsfahrer-*`, Kong gateway on `http://localhost:8000`, Postgres on port 5432. This is what the user runs to click through the live app.
Both can be running simultaneously. `web/.env.local` (gitignored, per-worktree) determines which one a local `npm run dev` talks to — check its `NEXT_PUBLIC_SUPABASE_URL` before assuming which stack you're hitting. Get the CLI stack's current anon key and URL with `npx supabase status` (repo root) rather than hardcoding a previously-seen value — it can change between resets.
## Test admin account
`admin@aushilfsfahrer.local` / `Admin123!`, role `admin`, exists in the local CLI dev stack. Its password gets reset periodically during development (out-of-band, via the GoTrue admin API) and isn't reliably documented anywhere — if login fails, reset it yourself:
```bash
curl -s -X PUT http://127.0.0.1:54321/auth/v1/admin/users/<user-id> \
-H "apikey: <SERVICE_ROLE_KEY from npx supabase status>" \
-H "Authorization: Bearer <SERVICE_ROLE_KEY>" \
-H "Content-Type: application/json" \
-d '{"password":"Admin123!"}'
```
If the user doesn't exist at all, create it via `POST /auth/v1/admin/users` with `email_confirm: true`, then set its role in `public.profiles` via `docker exec -i supabase_db_fundament-auth-rollen psql -U postgres -d postgres`.
## pgTAP fixture conventions
Tests live in `supabase/tests/*.sql`. Standard pattern for simulating a specific user's RLS context:
```sql
insert into auth.users (id, email) values ('<uuid>', 'someone@test.local');
-- a trigger auto-creates a matching public.profiles row with role='readonly'
update public.profiles set role = 'fahrer' where id = '<uuid>';
set local role authenticated;
set local request.jwt.claims to '{"sub": "<uuid>", "role": "authenticated"}';
-- ... run assertions as this user ...
reset role;
```
Every test file wraps its whole body in `begin; ... rollback;` so fixtures never persist. Run the full suite with `npx supabase test db` (after `npx supabase db reset` to apply migrations fresh) — check the file for the current `select plan(N);` count before adding tests, and update it.

View File

@ -40,4 +40,25 @@ Müssen mehrere Fahrzeuge durch mehrere Fahrer am selben Standort überführt we
##
- Design angelehnt an https://www.widmannbewegt.de bzw https://www.mercedes-benz-widmann.de
### Must have
- Mobile first, klare Bedienung am Handy/Mobile Phone ist absolute Pflicht!
- Mobile first, klare Bedienung am Handy/Mobile Phone ist absolute Pflicht!
---
## Arbeitsweise für Claude
- Jedes Feature läuft über die `superpowers`-Skills: `brainstorming` → `writing-plans` →
`subagent-driven-development` → `finishing-a-development-branch`. Specs liegen in
`docs/superpowers/specs/`, Pläne in `docs/superpowers/plans/`. Nicht direkt drauflos
implementieren, auch bei kleinen Änderungen nicht.
- Feature-Branches bekommen einen eigenen Git-Worktree unter `.claude/worktrees/<name>/`,
Branch-Name `feature/<name>`.
- RLS ist die eigentliche Sicherheitsgrenze, App-Code-Prüfungen sind nur Defense-in-Depth/UX.
Bei neuen Server Actions: Rollen-Check nach demselben Muster wie in bestehenden Actions
ergänzen (z.B. `stornieren()` in `web/app/auftraege/[id]/actions.ts`), aber nie darauf
verlassen, dass das allein reicht — immer auch die zugrundeliegende RLS-Policy prüfen/live
verifizieren.
- Supabase-CLI-Befehle (`npx supabase db reset`, `npx supabase test db`, `npx supabase start`)
müssen vom Repo-Root laufen, nicht aus `web/`. Details zu den zwei parallel laufenden
Supabase-Stacks (lokaler CLI-Dev-Stack vs. Docker-Compose-Master-Stack) und Testzugängen:
siehe `.claude/skills/supabase-local-dev/SKILL.md`.
- Next.js Server Actions per curl testen (kein Browser nötig): siehe
`.claude/skills/curl-server-action/SKILL.md`.

View File

@ -0,0 +1,8 @@
-- Disponent braucht Sicht auf Fahrer-Profile, um beim Kanban-Board einen
-- Auftrag einem bestimmten Fahrer zuweisen zu koennen (Fahrer-Auswaehler).
-- Bewusst eingeschraenkt auf role = 'fahrer' (nicht alle Profile wie bei
-- Admin) -- Least-Privilege: Disponent sieht weiterhin keine anderen
-- Admin-/Disponent-Profile ausser dem eigenen.
create policy "Disponent sieht Fahrer-Profile"
on public.profiles for select
using (public.user_role() = 'disponent' and role = 'fahrer');

View File

@ -1,5 +1,5 @@
begin;
select plan(8);
select plan(10);
insert into auth.users (id, email) values
('11111111-1111-1111-1111-111111111111', 'admin@test.local'),
@ -72,5 +72,27 @@ select is(
'Neuer Nutzer bekommt trotz raw_user_meta_data.role=admin immer role=readonly (Privilege-Escalation-Schutz)'
);
-- Neuer Test-Fahrer fuer die Disponent-Sichtbarkeits-Pruefung (der
-- bisherige Fahrer-Testnutzer 22222222... wurde oben bereits per
-- Admin-Update zu 'disponent' geaendert).
insert into auth.users (id, email) values
('44444444-4444-4444-4444-444444444444', 'fahrer2@test.local');
update public.profiles set role = 'fahrer' where id = '44444444-4444-4444-4444-444444444444';
set local role authenticated;
set local request.jwt.claims to '{"sub": "22222222-2222-2222-2222-222222222222", "role": "authenticated"}';
select isnt_empty(
$$ select id from public.profiles where id = '44444444-4444-4444-4444-444444444444' $$,
'Disponent kann ein Fahrer-Profil sehen (neue Policy fuer Kanban-Fahrer-Auswaehler)'
);
select is_empty(
$$ select id from public.profiles where id = '11111111-1111-1111-1111-111111111111' $$,
'Disponent sieht KEIN Admin-Profil (Least-Privilege, nur role=fahrer sichtbar)'
);
reset role;
select * from finish();
rollback;

View File

@ -0,0 +1,86 @@
"use server";
// Diese drei Actions dupliziert bewusst die Kern-Update-Logik von
// `uebernehmen`/`stornieren` aus web/app/auftraege/[id]/actions.ts, statt sie
// zu refactoren: die bestehenden Actions enden mit redirect() (fuer den
// Formular-Submit-Flow auf der Detailseite), waehrend das Kanban-Board eine
// Client-Component ist, die nach einem Drop auf derselben Seite bleiben und
// bei Fehlschlag die Karte lokal zuruecksetzen muss -- das erfordert ein
// Ergebnis-Objekt statt eines Redirects. Ein Refactoring der bestehenden,
// bereits produktiven Actions ist bewusst nicht Teil dieses Plans.
import { createClient } from "@/lib/supabase/server";
import { loadProfile } from "@/lib/auth/profile";
export type MutationResult = { success: true } | { success: false; error: string };
export async function uebernehmenVomBoard(auftragId: string): Promise<MutationResult> {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return { success: false, error: "Nicht angemeldet." };
}
const { data, error } = await supabase
.from("auftraege")
.update({ status: "zugewiesen", zugewiesen_an: user.id, start_zeit: new Date().toISOString() })
.eq("id", auftragId)
.eq("status", "offen")
.select("id");
if (error || !data || data.length === 0) {
return { success: false, error: "Auftrag wurde bereits übernommen oder ist nicht mehr offen." };
}
return { success: true };
}
export async function stornierenVomBoard(auftragId: string): Promise<MutationResult> {
const profileResult = await loadProfile();
if (
profileResult.status !== "ok" ||
(profileResult.profile.role !== "admin" && profileResult.profile.role !== "disponent")
) {
return { success: false, error: "Nur Disponent/Admin duerfen einen Auftrag stornieren." };
}
const supabase = await createClient();
const { data, error } = await supabase
.from("auftraege")
.update({ status: "storniert" })
.eq("id", auftragId)
.select("id");
if (error || !data || data.length === 0) {
return { success: false, error: "Stornieren fehlgeschlagen." };
}
return { success: true };
}
export async function zuweisenAnFahrer(auftragId: string, fahrerId: string): Promise<MutationResult> {
const profileResult = await loadProfile();
if (
profileResult.status !== "ok" ||
(profileResult.profile.role !== "admin" && profileResult.profile.role !== "disponent")
) {
return { success: false, error: "Nur Disponent/Admin duerfen Auftraege zuweisen." };
}
const supabase = await createClient();
const { data, error } = await supabase
.from("auftraege")
.update({ status: "zugewiesen", zugewiesen_an: fahrerId, start_zeit: new Date().toISOString() })
.eq("id", auftragId)
.eq("status", "offen")
.select("id");
if (error || !data || data.length === 0) {
return { success: false, error: "Zuweisen fehlgeschlagen (Auftrag ist evtl. nicht mehr offen)." };
}
return { success: true };
}

View File

@ -1,21 +1,23 @@
import { loadProfile } from "@/lib/auth/profile";
import { Card } from "@/components/ui/Card";
import { listAuftraegeFuerKanban, listFahrerNutzer } from "@/lib/dashboard/queries";
import { KanbanBoard } from "@/components/dashboard/KanbanBoard";
export default async function DashboardPage() {
const result = await loadProfile();
if (result.status !== "ok") {
const profileResult = await loadProfile();
if (profileResult.status !== "ok") {
return null;
}
const kannZuweisen = profileResult.profile.role === "admin" || profileResult.profile.role === "disponent";
const [spalten, fahrerListe] = await Promise.all([
listAuftraegeFuerKanban(),
kannZuweisen ? listFahrerNutzer() : Promise.resolve([]),
]);
return (
<div className="mx-auto max-w-2xl p-4 md:p-8">
<Card>
<h1 className="text-xl font-semibold text-asphalt-grey">Dashboard</h1>
<p className="mt-2 text-asphalt-grey">
Eingeloggt als {result.profile.name} ({result.profile.role})
</p>
</Card>
<div className="mx-auto max-w-6xl p-4 md:p-8">
<h1 className="mb-6 text-xl font-semibold text-asphalt-grey">Dashboard</h1>
<KanbanBoard initialSpalten={spalten} fahrerListe={fahrerListe} rolle={profileResult.profile.role} />
</div>
);
}

View File

@ -0,0 +1,44 @@
"use client";
import { useState } from "react";
import { Card } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { FIELD_CLASSES } from "@/components/ui/FormField";
export function FahrerAuswaehler({
fahrerListe,
onBestaetigen,
onAbbrechen,
}: {
fahrerListe: { id: string; name: string }[];
onBestaetigen: (fahrerId: string) => void;
onAbbrechen: () => void;
}) {
const [ausgewaehlt, setAusgewaehlt] = useState("");
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
<Card className="w-full max-w-sm">
<h2 className="mb-4 text-base font-semibold text-asphalt-grey">Fahrer auswählen</h2>
<select value={ausgewaehlt} onChange={(e) => setAusgewaehlt(e.target.value)} className={FIELD_CLASSES}>
<option value="" disabled>
Bitte waehlen
</option>
{fahrerListe.map((fahrer) => (
<option key={fahrer.id} value={fahrer.id}>
{fahrer.name}
</option>
))}
</select>
<div className="mt-4 flex gap-3">
<Button type="button" disabled={!ausgewaehlt} onClick={() => ausgewaehlt && onBestaetigen(ausgewaehlt)}>
Zuweisen
</Button>
<Button type="button" variant="secondary" onClick={onAbbrechen}>
Abbrechen
</Button>
</div>
</Card>
</div>
);
}

View File

@ -0,0 +1,191 @@
"use client";
import { useState } from "react";
import {
DndContext,
KeyboardSensor,
PointerSensor,
useDraggable,
useDroppable,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import type { AuftragStatus } from "@/lib/auftraege/queries";
import type { KanbanAuftrag, KanbanSpalten } from "@/lib/dashboard/queries";
import type { Role } from "@/lib/auth/roles";
import { istDragErlaubt } from "@/lib/dashboard/kanban-permissions";
import { uebernehmenVomBoard, stornierenVomBoard, zuweisenAnFahrer } from "@/app/dashboard/actions";
import { Card } from "@/components/ui/Card";
import { StatusBadge } from "@/components/ui/StatusBadge";
import { Alert } from "@/components/ui/Alert";
import { FahrerAuswaehler } from "./FahrerAuswaehler";
const SPALTEN_REIHENFOLGE: AuftragStatus[] = ["offen", "zugewiesen", "unterwegs", "abgeschlossen", "storniert"];
const SPALTEN_LABELS: Record<AuftragStatus, string> = {
offen: "Offen",
zugewiesen: "Zugewiesen",
unterwegs: "Unterwegs",
abgeschlossen: "Abgeschlossen",
storniert: "Storniert",
};
function KanbanKarte({ auftrag, rolle }: { auftrag: KanbanAuftrag; rolle: Role }) {
const istReadonly = rolle === "readonly";
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
id: auftrag.id,
data: { status: auftrag.status },
disabled: istReadonly,
});
return (
<div
ref={setNodeRef}
{...(istReadonly ? {} : listeners)}
{...(istReadonly ? {} : attributes)}
style={{ transform: CSS.Translate.toString(transform), opacity: isDragging ? 0.5 : 1 }}
className="touch-none"
>
<a href={`/auftraege/${auftrag.id}`}>
<Card className={`mb-3 ${istReadonly ? "" : "cursor-grab active:cursor-grabbing"}`}>
<p className="text-sm text-asphalt-grey">
{auftrag.abholort.adresse} → {auftrag.zielort.adresse}
</p>
<p className="mt-1 text-xs text-asphalt-grey/70">{auftrag.fahrzeug.kennzeichen}</p>
{auftrag.zugewiesener_fahrer && (
<p className="mt-1 text-xs text-asphalt-grey/70">Fahrer: {auftrag.zugewiesener_fahrer.name}</p>
)}
</Card>
</a>
</div>
);
}
function KanbanSpalte({
status,
auftraege,
rolle,
}: {
status: AuftragStatus;
auftraege: KanbanAuftrag[];
rolle: Role;
}) {
const { setNodeRef, isOver } = useDroppable({ id: status });
return (
<div
ref={setNodeRef}
className={`min-w-[260px] flex-1 rounded-lg border p-3 ${
isOver ? "border-performance-blue bg-blue-50" : "border-aluminium-grey bg-white"
}`}
>
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-asphalt-grey">{SPALTEN_LABELS[status]}</h2>
<StatusBadge status={status} />
</div>
{auftraege.map((auftrag) => (
<KanbanKarte key={auftrag.id} auftrag={auftrag} rolle={rolle} />
))}
</div>
);
}
export type ZuweisenDialogState = { auftragId: string; quelle: AuftragStatus } | null;
export function KanbanBoard({
initialSpalten,
fahrerListe,
rolle,
}: {
initialSpalten: KanbanSpalten;
fahrerListe: { id: string; name: string }[];
rolle: Role;
}) {
const [spalten, setSpalten] = useState(initialSpalten);
const [fehler, setFehler] = useState<string | null>(null);
const [zuweisenDialog, setZuweisenDialog] = useState<ZuweisenDialogState>(null);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(KeyboardSensor),
);
function verschiebeKarteLokal(auftragId: string, quelle: AuftragStatus, ziel: AuftragStatus) {
setSpalten((bisher) => {
const karte = bisher[quelle].find((a) => a.id === auftragId);
if (!karte) return bisher;
return {
...bisher,
[quelle]: bisher[quelle].filter((a) => a.id !== auftragId),
[ziel]: [{ ...karte, status: ziel }, ...bisher[ziel]],
};
});
}
function macheRueckgaengig(auftragId: string, quelle: AuftragStatus, ziel: AuftragStatus) {
verschiebeKarteLokal(auftragId, ziel, quelle);
}
async function handleDragEnd(event: DragEndEvent) {
const auftragId = String(event.active.id);
const quelle = event.active.data.current?.status as AuftragStatus | undefined;
const ziel = event.over?.id as AuftragStatus | undefined;
if (!quelle || !ziel || !istDragErlaubt(rolle, quelle, ziel)) {
return;
}
if (ziel === "zugewiesen" && (rolle === "admin" || rolle === "disponent")) {
setZuweisenDialog({ auftragId, quelle });
return;
}
verschiebeKarteLokal(auftragId, quelle, ziel);
const ergebnis =
ziel === "zugewiesen" ? await uebernehmenVomBoard(auftragId) : await stornierenVomBoard(auftragId);
if (!ergebnis.success) {
macheRueckgaengig(auftragId, quelle, ziel);
setFehler(ergebnis.error);
}
}
async function bestaetigeZuweisung(fahrerId: string) {
if (!zuweisenDialog) return;
const { auftragId, quelle } = zuweisenDialog;
setZuweisenDialog(null);
verschiebeKarteLokal(auftragId, quelle, "zugewiesen");
const ergebnis = await zuweisenAnFahrer(auftragId, fahrerId);
if (!ergebnis.success) {
macheRueckgaengig(auftragId, quelle, "zugewiesen");
setFehler(ergebnis.error);
}
}
return (
<div>
{fehler && (
<div className="mb-4">
<Alert>{fehler}</Alert>
</div>
)}
<DndContext sensors={sensors} onDragEnd={handleDragEnd}>
<div className="flex gap-4 overflow-x-auto pb-4">
{SPALTEN_REIHENFOLGE.map((status) => (
<KanbanSpalte key={status} status={status} auftraege={spalten[status]} rolle={rolle} />
))}
</div>
</DndContext>
{zuweisenDialog && (
<FahrerAuswaehler
fahrerListe={fahrerListe}
onBestaetigen={bestaetigeZuweisung}
onAbbrechen={() => setZuweisenDialog(null)}
/>
)}
</div>
);
}

View File

@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { istDragErlaubt } from "./kanban-permissions";
describe("istDragErlaubt", () => {
it("erlaubt Fahrer offen -> zugewiesen (Selbst-Uebernahme)", () => {
expect(istDragErlaubt("fahrer", "offen", "zugewiesen")).toBe(true);
});
it("erlaubt Disponent und Admin offen -> zugewiesen (Fahrer-Auswaehler)", () => {
expect(istDragErlaubt("disponent", "offen", "zugewiesen")).toBe(true);
expect(istDragErlaubt("admin", "offen", "zugewiesen")).toBe(true);
});
it("verbietet Fahrer jede Karte -> storniert", () => {
expect(istDragErlaubt("fahrer", "offen", "storniert")).toBe(false);
expect(istDragErlaubt("fahrer", "zugewiesen", "storniert")).toBe(false);
});
it("erlaubt Disponent und Admin nicht-terminale Karte -> storniert", () => {
expect(istDragErlaubt("disponent", "offen", "storniert")).toBe(true);
expect(istDragErlaubt("admin", "zugewiesen", "storniert")).toBe(true);
expect(istDragErlaubt("disponent", "unterwegs", "storniert")).toBe(true);
});
it("verbietet storniert als Ziel aus abgeschlossen oder storniert", () => {
expect(istDragErlaubt("admin", "abgeschlossen", "storniert")).toBe(false);
expect(istDragErlaubt("admin", "storniert", "storniert")).toBe(false);
});
it("verbietet unterwegs und abgeschlossen immer als Ziel, fuer jede Rolle", () => {
expect(istDragErlaubt("admin", "zugewiesen", "unterwegs")).toBe(false);
expect(istDragErlaubt("admin", "unterwegs", "abgeschlossen")).toBe(false);
expect(istDragErlaubt("fahrer", "zugewiesen", "unterwegs")).toBe(false);
expect(istDragErlaubt("disponent", "unterwegs", "abgeschlossen")).toBe(false);
});
it("verbietet zugewiesen -> offen (zuruecklegen ist out of scope)", () => {
expect(istDragErlaubt("fahrer", "zugewiesen", "offen")).toBe(false);
expect(istDragErlaubt("admin", "zugewiesen", "offen")).toBe(false);
});
it("verbietet Readonly jeden Drag", () => {
expect(istDragErlaubt("readonly", "offen", "zugewiesen")).toBe(false);
expect(istDragErlaubt("readonly", "offen", "storniert")).toBe(false);
});
it("verbietet Drag auf denselben Status", () => {
expect(istDragErlaubt("admin", "offen", "offen")).toBe(false);
expect(istDragErlaubt("fahrer", "zugewiesen", "zugewiesen")).toBe(false);
});
});

View File

@ -0,0 +1,21 @@
import type { AuftragStatus } from "@/lib/auftraege/queries";
import type { Role } from "@/lib/auth/roles";
export function istDragErlaubt(rolle: Role, quelle: AuftragStatus, ziel: AuftragStatus): boolean {
if (quelle === ziel) {
return false;
}
if (ziel === "unterwegs" || ziel === "abgeschlossen" || ziel === "offen") {
return false;
}
if (ziel === "zugewiesen") {
return quelle === "offen" && (rolle === "fahrer" || rolle === "admin" || rolle === "disponent");
}
if (ziel === "storniert") {
return (
(quelle === "offen" || quelle === "zugewiesen" || quelle === "unterwegs") &&
(rolle === "admin" || rolle === "disponent")
);
}
return false;
}

View File

@ -0,0 +1,63 @@
import { createClient } from "@/lib/supabase/server";
import type { AuftragStatus, Ort, Fahrzeug } from "@/lib/auftraege/queries";
export type KanbanAuftrag = {
id: string;
status: AuftragStatus;
zugewiesen_an: string | null;
abholort: Ort;
zielort: Ort;
fahrzeug: Fahrzeug;
zugewiesener_fahrer: { id: string; name: string } | null;
};
export type KanbanSpalten = Record<AuftragStatus, KanbanAuftrag[]>;
const KANBAN_AUFTRAG_SELECT =
"id, status, zugewiesen_an, abholort:orte!auftraege_abholort_id_fkey(id, adresse, ansprechpartner), zielort:orte!auftraege_zielort_id_fkey(id, adresse, ansprechpartner), fahrzeug:fahrzeuge(id, kennzeichen, marke, modell), zugewiesener_fahrer:profiles!auftraege_zugewiesen_an_fkey(id, name)";
const TERMINAL_LIMIT = 20;
export async function listAuftraegeFuerKanban(): Promise<KanbanSpalten> {
const supabase = await createClient();
const [{ data: aktive }, { data: abgeschlossen }, { data: storniert }] = await Promise.all([
supabase
.from("auftraege")
.select(KANBAN_AUFTRAG_SELECT)
.in("status", ["offen", "zugewiesen", "unterwegs"])
.order("created_at", { ascending: false }),
supabase
.from("auftraege")
.select(KANBAN_AUFTRAG_SELECT)
.eq("status", "abgeschlossen")
.order("created_at", { ascending: false })
.limit(TERMINAL_LIMIT),
supabase
.from("auftraege")
.select(KANBAN_AUFTRAG_SELECT)
.eq("status", "storniert")
.order("created_at", { ascending: false })
.limit(TERMINAL_LIMIT),
]);
const spalten: KanbanSpalten = {
offen: [],
zugewiesen: [],
unterwegs: [],
abgeschlossen: (abgeschlossen ?? []) as unknown as KanbanAuftrag[],
storniert: (storniert ?? []) as unknown as KanbanAuftrag[],
};
for (const auftrag of (aktive ?? []) as unknown as KanbanAuftrag[]) {
spalten[auftrag.status].push(auftrag);
}
return spalten;
}
export async function listFahrerNutzer(): Promise<{ id: string; name: string }[]> {
const supabase = await createClient();
const { data } = await supabase.from("profiles").select("id, name").eq("role", "fahrer").order("name");
return data ?? [];
}

41
web/package-lock.json generated
View File

@ -8,6 +8,8 @@
"name": "web",
"version": "0.1.0",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/utilities": "^3.2.2",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.0",
"next": "16.2.10",
@ -280,6 +282,45 @@
"node": ">=6.9.0"
}
},
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/core": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@dnd-kit/utilities": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",

View File

@ -10,6 +10,8 @@
"test": "vitest run"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/utilities": "^3.2.2",
"@supabase/ssr": "^0.12.0",
"@supabase/supabase-js": "^2.110.0",
"next": "16.2.10",