diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..0744987 --- /dev/null +++ b/.claude/settings.json @@ -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" + } + ] + } + ] + } +} diff --git a/.claude/skills/curl-server-action/SKILL.md b/.claude/skills/curl-server-action/SKILL.md new file mode 100644 index 0000000..6dcb581 --- /dev/null +++ b/.claude/skills/curl-server-action/SKILL.md @@ -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 `
` 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:/ -o page.html +``` + +**Unbound action** (``, 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_` — empty-valued field referencing the action +- `$ACTION_:0` — bound marker, value `"$@1"` +- `$ACTION_:1` — JSON array of the bound arguments, e.g. `["abholort"]` + +## Step 2: submit with the matching fields + +Unbound: + +```bash +HASH=$(curl -s http://localhost:/login | grep -o '\$ACTION_ID_[a-z0-9]*' | head -1) +curl -s -c cookies.txt -X POST http://localhost:/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:/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":""` 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. diff --git a/.claude/skills/rebuild-master-stack/SKILL.md b/.claude/skills/rebuild-master-stack/SKILL.md new file mode 100644 index 0000000..0e457e7 --- /dev/null +++ b/.claude/skills/rebuild-master-stack/SKILL.md @@ -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/ 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/.sql + docker exec -i aushilfsfahrer-db-1 psql -U postgres -d postgres -c "insert into supabase_migrations.schema_migrations (version) values ('') 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). diff --git a/.claude/skills/supabase-local-dev/SKILL.md b/.claude/skills/supabase-local-dev/SKILL.md new file mode 100644 index 0000000..f2e0efe --- /dev/null +++ b/.claude/skills/supabase-local-dev/SKILL.md @@ -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/ \ + -H "apikey: " \ + -H "Authorization: Bearer " \ + -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 ('', 'someone@test.local'); +-- a trigger auto-creates a matching public.profiles row with role='readonly' +update public.profiles set role = 'fahrer' where id = ''; + +set local role authenticated; +set local request.jwt.claims to '{"sub": "", "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. diff --git a/CLAUDE.md b/CLAUDE.md index 00e5216..a6651f8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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! \ No newline at end of file +- 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//`, + Branch-Name `feature/`. +- 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`. diff --git a/supabase/migrations/20260707090000_disponent_sieht_fahrer_profile.sql b/supabase/migrations/20260707090000_disponent_sieht_fahrer_profile.sql new file mode 100644 index 0000000..39046ca --- /dev/null +++ b/supabase/migrations/20260707090000_disponent_sieht_fahrer_profile.sql @@ -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'); diff --git a/supabase/tests/profiles_rls_test.sql b/supabase/tests/profiles_rls_test.sql index 8cfcac0..38c10e0 100644 --- a/supabase/tests/profiles_rls_test.sql +++ b/supabase/tests/profiles_rls_test.sql @@ -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; diff --git a/web/app/dashboard/actions.ts b/web/app/dashboard/actions.ts new file mode 100644 index 0000000..3e8be50 --- /dev/null +++ b/web/app/dashboard/actions.ts @@ -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 { + 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 { + 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 { + 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 }; +} diff --git a/web/app/dashboard/page.tsx b/web/app/dashboard/page.tsx index b9338c0..1c8805a 100644 --- a/web/app/dashboard/page.tsx +++ b/web/app/dashboard/page.tsx @@ -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 ( -
- -

Dashboard

-

- Eingeloggt als {result.profile.name} ({result.profile.role}) -

-
+
+

Dashboard

+
); } diff --git a/web/components/dashboard/FahrerAuswaehler.tsx b/web/components/dashboard/FahrerAuswaehler.tsx new file mode 100644 index 0000000..0e04679 --- /dev/null +++ b/web/components/dashboard/FahrerAuswaehler.tsx @@ -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 ( +
+ +

Fahrer auswählen

+ +
+ + +
+
+
+ ); +} diff --git a/web/components/dashboard/KanbanBoard.tsx b/web/components/dashboard/KanbanBoard.tsx new file mode 100644 index 0000000..5997d51 --- /dev/null +++ b/web/components/dashboard/KanbanBoard.tsx @@ -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 = { + 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 ( + + ); +} + +function KanbanSpalte({ + status, + auftraege, + rolle, +}: { + status: AuftragStatus; + auftraege: KanbanAuftrag[]; + rolle: Role; +}) { + const { setNodeRef, isOver } = useDroppable({ id: status }); + + return ( +
+
+

{SPALTEN_LABELS[status]}

+ +
+ {auftraege.map((auftrag) => ( + + ))} +
+ ); +} + +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(null); + const [zuweisenDialog, setZuweisenDialog] = useState(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 ( +
+ {fehler && ( +
+ {fehler} +
+ )} + +
+ {SPALTEN_REIHENFOLGE.map((status) => ( + + ))} +
+
+ {zuweisenDialog && ( + setZuweisenDialog(null)} + /> + )} +
+ ); +} diff --git a/web/lib/dashboard/kanban-permissions.test.ts b/web/lib/dashboard/kanban-permissions.test.ts new file mode 100644 index 0000000..96aaf8d --- /dev/null +++ b/web/lib/dashboard/kanban-permissions.test.ts @@ -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); + }); +}); diff --git a/web/lib/dashboard/kanban-permissions.ts b/web/lib/dashboard/kanban-permissions.ts new file mode 100644 index 0000000..906cd2d --- /dev/null +++ b/web/lib/dashboard/kanban-permissions.ts @@ -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; +} diff --git a/web/lib/dashboard/queries.ts b/web/lib/dashboard/queries.ts new file mode 100644 index 0000000..6e40465 --- /dev/null +++ b/web/lib/dashboard/queries.ts @@ -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; + +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 { + 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 ?? []; +} diff --git a/web/package-lock.json b/web/package-lock.json index 9b0fcf0..6c992a3 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -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", diff --git a/web/package.json b/web/package.json index 8c0c9f8..5ab80b9 100644 --- a/web/package.json +++ b/web/package.json @@ -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",