Compare commits
69
Commits
804b7637e7
...
main
No files matched your search
@@ -17,8 +17,22 @@ SESSION_COOKIE_SECRET=please-change-me-in-prod-at-least-32-chars
|
||||
# --- Cron Bearer (Story 2.6 + 5.1 + 6.3) ---
|
||||
CRON_BEARER_TOKEN=please-change-me-in-prod
|
||||
|
||||
# --- Backup-Sidecar (Story 6.3, nur Prod) ---
|
||||
# Täglicher pg_dump im service "backup". Beide optional (Defaults: 03 / 14).
|
||||
# BACKUP_HOUR=03
|
||||
# BACKUP_RETENTION_DAYS=14
|
||||
|
||||
# --- App ---
|
||||
NODE_ENV=development
|
||||
LOG_LEVEL=info
|
||||
PORT=3000
|
||||
PUBLIC_BASE_URL=http://localhost:5173
|
||||
|
||||
# --- Kimai-Sync (optional, ENTWICKLUN-9) ---
|
||||
# Nur wenn ALLE vier gesetzt sind, synct ebw beim Check-In/Out nach Kimai
|
||||
# (sonst No-Op). API-Token in Kimai unter Benutzerprofil → API-Zugriff.
|
||||
# PROJECT/ACTIVITY = numerische IDs des Default-Projekts/-Tätigkeit in Kimai.
|
||||
# KIMAI_BASE_URL=https://kimai.tool-ctrl.de
|
||||
# KIMAI_API_TOKEN=
|
||||
# KIMAI_PROJECT_ID=
|
||||
# KIMAI_ACTIVITY_ID=
|
||||
@@ -0,0 +1,50 @@
|
||||
# Gitea Actions Deploy für das Cockpit.
|
||||
# Läuft NUR bei Push auf main und deployt auf dem Homeserver, auf dem auch
|
||||
# Gitea und der act_runner laufen. Der Job läuft im Host-Executor (runs-on: host),
|
||||
# damit er Zugriff auf den Docker-Daemon und die Host-Pfade hat:
|
||||
# /opt/build/cockpit → Source-Checkout (Build-Context, gehört dem Runner-User)
|
||||
# /opt/stacks/cockpit → docker-compose.yml + .env (root-owned → via sudo)
|
||||
|
||||
name: deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: deploy-cockpit
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: host
|
||||
steps:
|
||||
- name: Source-Checkout auf origin/main aktualisieren
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git -C /opt/build/cockpit fetch --prune origin
|
||||
git -C /opt/build/cockpit reset --hard origin/main
|
||||
echo "Deployed commit:"
|
||||
git -C /opt/build/cockpit log --oneline -1
|
||||
|
||||
- name: Container bauen & neu starten
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd /opt/stacks/cockpit
|
||||
sudo docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Auf API-Health warten
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for i in $(seq 1 36); do
|
||||
status=$(sudo docker inspect -f '{{.State.Health.Status}}' cockpit-api 2>/dev/null || echo "missing")
|
||||
echo " api health: $status"
|
||||
if [ "$status" = "healthy" ]; then
|
||||
echo "✅ cockpit-api ist healthy."
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "❌ cockpit-api wurde nicht rechtzeitig healthy." >&2
|
||||
sudo docker logs --tail 80 cockpit-api || true
|
||||
exit 1
|
||||
@@ -9,20 +9,23 @@ Internes Web-Tool von **ToolCTRL** für den täglichen Überblick über alle Pro
|
||||
## Was die App tut
|
||||
|
||||
| Bereich | Feature |
|
||||
|---|---|
|
||||
| **Dashboard** (`/dashboard`) | Unternehmens-Übersicht: Bereichs-Ampelstatus, „Heute fehlt"-Liste, bereichsübergreifende Blocker, Pflicht-Minimum-Übersicht, Jourfixe-Hinweis, „Heute im Team" (ToDos), „Zeit im Team heute" (Live-Tracking), Vortags-Feed |
|
||||
| **Bereich** (`/bereich`, `/bereich/<slug>`) | Tab-Switcher über Entwicklung / Vertrieb / Marketing — pro Bereich Projekt-Liste (Kundenprojekte / Interne Projekte) mit Pflicht-Minimum-Indicator |
|
||||
| **Projekt** (`/projekt/:id`) | Detail: Verlinkungen (Outline-Steckbrief, Plane-Board, Risikoliste), Pflicht-Minimum-Status, Meilenstein-Checkliste, DoD, Projekt-Abschluss (P1) |
|
||||
| **Heute** (`/heute`) | Tagesrhythmus: Lock-in mit ToDo-Liste, Auto-Carryover offener ToDos vom Vortag, ToDo-Editor, Zeiterfassungs-Timeline mit Edit/Delete/Nachtrag |
|
||||
| **Reflexion** (`/reflexion`) | Abend-Reflexion: ToDos abhaken, Freitext, Ampel + Trend, optional Blocker. Editierbar bis 00:00 Berlin |
|
||||
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Dashboard** (`/dashboard`) | Unternehmens-Übersicht: Bereichs-Ampelstatus, **Showstopper** (offene Showstopper-Risiken), **Projekte in Eskalation/Taskforce**, „Heute fehlt"-Liste, bereichsübergreifende Blocker, Pflicht-Minimum-Übersicht, Jourfixe-Hinweis, „Heute im Team" (ToDos), „Zeit im Team heute" (Live-Tracking, Wall-Clock), Vortags-Feed |
|
||||
| **Bereich** (`/bereich`, `/bereich/<slug>`) | Tab-Switcher Entwicklung / Vertrieb / Marketing — Projekt-Liste (Kundenprojekte / Interne Projekte) mit Pflicht-Minimum- & Modus-Indicator. **Vertrieb** zusätzlich: Lead-Teaser + „Projekte mit Vertriebsaktivität" (bereichsübergreifend) |
|
||||
| **Projekt** (`/projekt/:id`) | Detail: Ziel/Maxime/Nicht-Ziele/Liefergegenstände + Zieldreieck, **Phasen-Lebenszyklus mit Gate-Reviews**, **Statusbericht** (Ampel/Trend + Verlauf), **Stakeholder-Matrix**, **Risiko- & Chancen-Register**, **verknüpfte Leads**, **Änderungs-Log**, Verlinkungen, Pflicht-Minimum, Meilensteine (mit Ergebnis/Kundennutzen + Datums-Warnung), DoD, Projekt-Abschluss (Checkliste + Vermerk, P1), Projekt-Modus |
|
||||
| **Leads** (`/leads`, `/lead/:id`) | Vertriebs-CRM: Lead-Liste nach Status (Cold/Warm/Hot/Won/Lost), Dossier (Stammdaten, Pain & Bedarf, Soft Factors, Strategie), Kontaktpersonen, Austausch-Log, **CSV-Import**, Lead→Deal-Promotion, **Projekt-Verknüpfung** |
|
||||
| **Heute** (`/heute`) | Tagesrhythmus: Lock-in mit ToDo-Liste, Auto-Carryover offener ToDos vom Vortag, **ToDos mitten am Tag hinzufügen**, Timer pro ToDo, Zeiterfassungs-Timeline mit Edit/Delete/Nachtrag |
|
||||
| **Reflexion** (`/reflexion`) | Abend-Reflexion: ToDos abhaken + **Titel inline korrigieren**, Freitext, Ampel + Trend, optional Blocker. Editierbar bis 00:00 Berlin |
|
||||
| **Archiv** (`/archiv`) | Abgeschlossene Projekte, gruppiert nach Bereich |
|
||||
|
||||
**Querschnittsfunktionen**
|
||||
|
||||
- **Zeiterfassung**: Persistente Timer-Pill in der TopNav (Live-Sekundenzähler), Quick-Picker mit ToDos + Kategorien + Freitext, retroaktiver Nachtrag-Dialog, Bindung an ToDo optional. Personenübergreifend sichtbar im Dashboard.
|
||||
- **Leads / CRM**: Qualitative Lead-Dossiers im Vertrieb, **CSV-Import** (header-basiert, Dedup über Firmenname, Adresse → Standort, Notizen → Austausch-Log), optionale **Verknüpfung zu einem Projekt** (egal welcher Bereich) → Projekte mit Leads erscheinen in der Vertriebs-Sicht, ohne redundant angelegt zu werden.
|
||||
- **Projektmanagement-Tiefe** (operationalisiert Leitfaden v3.0): Projekt-Modus (Relax/Standard/Eskalation/Taskforce), 4-Phasen-Lebenszyklus mit Gate-Reviews, Statusbericht (Ampel/Trend/Text + Verlauf), Stakeholder-Analyse mit Macht/Interesse-Matrix, Risiko- & Chancen-Register (W×A, Showstopper, Owner, Strategie), Änderungs-Log (Scope-Creep), Zieldreieck, strukturierter Abschluss.
|
||||
- **Zeiterfassung**: Persistente Timer-Pill in der TopNav (Live-Sekundenzähler), Quick-Picker mit ToDos + Kategorien + Freitext, retroaktiver Nachtrag. „Gesamt" pro Person ist **Wall-Clock** (überlappende parallele Tasks zählen einmal); pro Aufgabe wird die Summe getrennt ausgewiesen („getrackt").
|
||||
- **Blocker**: Inline in der Reflexion oder über `n`-Shortcut bzw. den globalen „Neuer Blocker"-Dialog. Auflösung nur durch den Projekt-P1.
|
||||
- **Pflicht-Minimum-Check** (Leitfaden §9): 6-Punkte-Checkliste pro Projekt, einer davon (Status-Ampel aktuell) wird stündlich per Cron aus den Reflexions-Zeitstempeln aktualisiert.
|
||||
- **Streak**: aufeinanderfolgende Werktage mit voller Reflexion. Flammen-Pill rechts oben.
|
||||
- **Pflicht-Minimum-Check** (Leitfaden §9): 6-Punkte-Checkliste pro Projekt; Punkt „Status-Ampel aktuell (≤ 7 Werktage)" wird per Cron **pro Projekt** aus dem jüngsten Statusbericht berechnet.
|
||||
- **Streak**: aufeinanderfolgende Werktage mit voller Reflexion. Wochenenden, **bundesweite Feiertage** und gemeldete Abwesenheiten sind neutral (brechen nicht). Flammen-Pill rechts oben.
|
||||
- **Keyboard-Shortcuts**: `g d/b/h/a` Navigation, `g e/v/m` direkt in Entwicklung/Vertrieb/Marketing, `n` Neuer Blocker, `?` Cheatsheet.
|
||||
|
||||
---
|
||||
@@ -30,7 +33,7 @@ Internes Web-Tool von **ToolCTRL** für den täglichen Überblick über alle Pro
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Wahl |
|
||||
|---|---|
|
||||
| ------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Sprache | **TypeScript** strict, ESM überall |
|
||||
| Repo-Layout | **pnpm**-Monorepo (`pnpm-workspace.yaml`) |
|
||||
| Node | **22+** |
|
||||
@@ -66,9 +69,10 @@ Internes Web-Tool von **ToolCTRL** für den täglichen Überblick über alle Pro
|
||||
│ │ │ │ └── ui/ Button, Card, KeyCaret, SkeletonCard, ToolCtrlLogo
|
||||
│ │ │ ├── hooks/ useCurrentUser
|
||||
│ │ │ ├── lib/ router, trpc, trpc-provider, voice,
|
||||
│ │ │ │ format-duration, time-categories
|
||||
│ │ │ │ format-duration, time-categories,
|
||||
│ │ │ │ lead-meta, project-meta
|
||||
│ │ │ ├── routes/ dashboard, bereich, projekt, heute, reflexion,
|
||||
│ │ │ │ archiv, login, not-found
|
||||
│ │ │ │ leads, lead, archiv, login, not-found
|
||||
│ │ │ └── styles/globals.css
|
||||
│ │ ├── index.html
|
||||
│ │ └── vite.config.ts
|
||||
@@ -78,9 +82,11 @@ Internes Web-Tool von **ToolCTRL** für den täglichen Überblick über alle Pro
|
||||
│ ├── auth/ oidc, routes (login/callback/logout/dev-login),
|
||||
│ │ session, user, middleware
|
||||
│ ├── cron/routes.ts /internal/cron/* (Bearer-Token geschützt)
|
||||
│ ├── lib/ werktag (Mo-Fr Berlin), ampel, pflicht-minimum, logger
|
||||
│ ├── routers/ _app, user, area, project, deal, gtm,
|
||||
│ │ campaign, blocker, day-entry, time, dashboard
|
||||
│ ├── lib/ werktag (Mo-Fr Berlin + Feiertage), holidays,
|
||||
│ │ streak, csv, ampel, pflicht-minimum, logger
|
||||
│ ├── routers/ _app, user, area, project, deal, gtm, lead,
|
||||
│ │ risk, stakeholder, change, campaign, blocker,
|
||||
│ │ day-entry, time, dashboard
|
||||
│ ├── env.ts Zod-validierte Env-Vars
|
||||
│ ├── db.ts Singleton-Drizzle-Client
|
||||
│ ├── trpc.ts Context, protectedProcedure, withAudit
|
||||
@@ -88,11 +94,12 @@ Internes Web-Tool von **ToolCTRL** für den täglichen Überblick über alle Pro
|
||||
│ └── server.ts Fastify-Bootstrap + Healthcheck
|
||||
├── packages/
|
||||
│ ├── db/ Drizzle-Schema + Migrationen
|
||||
│ │ ├── src/{schema,client,seed,index}.ts
|
||||
│ │ ├── migrations/ 0000_init … 0007_project_description
|
||||
│ │ ├── src/{schema,client,seed,index,migrate,base-data}.ts
|
||||
│ │ ├── migrations/ 0000_init … 0011_lead_project_link
|
||||
│ │ └── drizzle.config.ts
|
||||
│ └── shared/ Zod-Schemas + Konstanten + Types
|
||||
│ └── src/schemas/ day-entry, project, deal, campaign, time-entry
|
||||
│ └── src/schemas/ day-entry, project, deal, campaign, time-entry,
|
||||
│ lead, risk, stakeholder, change
|
||||
├── _bmad-output/planning-artifacts/ PRD, Architektur, UX-Spec, Epics, Decision-Log
|
||||
├── docs/operations.md Ops-Guide (Authentik-Setup, Backup, Restore)
|
||||
├── scripts/backup.sh pg_dump-Skript (im Postgres-Container)
|
||||
@@ -147,7 +154,7 @@ Im Dev-Modus läuft ein **Auto-Login** als Admin-User `dejan@tool-ctrl.de`. Auth
|
||||
### Wichtige Ports
|
||||
|
||||
| Service | Port | Quelle |
|
||||
|---|---|---|
|
||||
| --------------- | --------- | ------------------------------------------------------------------------- |
|
||||
| Vite Dev-Server | **7173** | `apps/web/vite.config.ts` |
|
||||
| Fastify API | **7100** | `.env` (`PORT`) |
|
||||
| Postgres (Dev) | **55432** | `docker-compose.dev.yml` (5432 würde mit Mac-System-Postgres kollidieren) |
|
||||
@@ -169,21 +176,30 @@ pnpm --filter @cockpit/db migrate:generate --name=<name> # neue Migration
|
||||
|
||||
Postgres 16, Drizzle als ORM und Migrator. **Schema-Single-Source-of-Truth**: `packages/db/src/schema.ts`.
|
||||
|
||||
### Tabellen (aktueller Stand nach Migration 0007)
|
||||
### Tabellen (aktueller Stand nach Migration 0011)
|
||||
|
||||
| Tabelle | Zweck |
|
||||
|---|---|
|
||||
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `user` | Mitarbeiter (`authentik_sub` als Identitäts-Anker), `is_admin`-Flag |
|
||||
| `session` | Server-Side Sessions (Postgres-persistent), Browser kennt nur Cookie-`id` |
|
||||
| `audit_event` | Audit-Trail für jede mutierende Operation |
|
||||
| `audit_event` | Audit-Trail (Tabelle vorhanden; `withAudit`-Wrapper aktuell nicht verdrahtet) |
|
||||
| `area` | Bereich (entwicklung / vertrieb / marketing / allgemein) |
|
||||
| `project` | Projekt: Name, optionale `description`, Outline-/Plane-URLs, Arbeitsmodus (cycle/kanban), `pflicht_minimum_state` JSONB, Status-/Trend-Cache, Archiv-Felder |
|
||||
| `milestone` | Cockpit-Sicht-Meilenstein pro Projekt |
|
||||
| `project` | Projekt: Name, `description`, `maxime`, `ziel`/`nicht_ziele`/`liefergegenstaende`, `zieldreieck_flex`, `modus`, `phase`, Outline-/Plane-URLs, Arbeitsmodus, `pflicht_minimum_state` JSONB, Status-/Trend-Cache, `abschlussvermerk`, Archiv-Felder |
|
||||
| `milestone` | Cockpit-Sicht-Meilenstein pro Projekt (+ `ergebnis`, `kundennutzen`) |
|
||||
| `project_status` | Statusbericht-Historie pro Projekt (Ampel/Trend/Text, extern-Flag) |
|
||||
| `phase_gate` | Gate-Review am Phasenende (Ergebnis erreicht? + Notiz) |
|
||||
| `change_entry` | Änderungs-Log pro Projekt (Scope-Creep) |
|
||||
| `stakeholder` | Stakeholder-Analyse pro Projekt (Interesse × Einfluss, Haltung) |
|
||||
| `risk` | Risiko- & Chancen-Register pro Projekt (W×A, Showstopper, Owner, Strategie) |
|
||||
| `day_entry` | Tageseintrag (begun / full / absent), `published_at` für Vortrags-Veröffentlichung |
|
||||
| `todo` | Tagesplan-Item, optional an Bezug gebunden, `carried_over`-Flag |
|
||||
| `absence_day` | Urlaub/Krank/Sonstiges — zählt nicht gegen Streak |
|
||||
| `blocker` | Bereichsübergreifendes Hindernis |
|
||||
| `deal`, `gtm_step`, `campaign`, `lead_handover` | Im Schema vorhanden (Phase-2-Vorbereitung), **kein UI** mehr |
|
||||
| `lead` | Vertriebs-Lead-Dossier; optionale `project_id`-Verknüpfung zum (universellen) Projekt |
|
||||
| `lead_contact` | Kontaktperson(en) eines Leads |
|
||||
| `lead_touchpoint` | Austausch-Log eines Leads (Kanal, Outcome, Follow-up) |
|
||||
| `deal` | Pipeline-Deal; wird per Lead→Deal-Promotion erzeugt |
|
||||
| `gtm_step`, `campaign`, `lead_handover` | Im Schema vorhanden (Phase-2-Vorbereitung), kein UI |
|
||||
| `time_entry` | Zeiterfassungs-Block, optional an ToDo gebunden, Partial-Unique-Index erzwingt max. einen aktiven Timer pro User |
|
||||
|
||||
Migrationen liegen in `packages/db/migrations/*.sql` und werden über `drizzle-kit migrate` angewendet. Schema-Änderungen brauchen **immer eine neue Migration** — kein Schema-Drift.
|
||||
@@ -195,7 +211,7 @@ Migrationen liegen in `packages/db/migrations/*.sql` und werden über `drizzle-k
|
||||
### REST-Routen (Fastify)
|
||||
|
||||
| Methode | Pfad | Zweck |
|
||||
|---|---|---|
|
||||
| ----------- | ----------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| `GET` | `/api/health` | DB- und Authentik-Reachability-Check |
|
||||
| `GET` | `/api/me` | Eingeloggter User (oder 401) |
|
||||
| `GET` | `/api/auth/login` | Startet OIDC-Flow (Redirect zu Authentik) |
|
||||
@@ -211,14 +227,21 @@ Migrationen liegen in `packages/db/migrations/*.sql` und werden über `drizzle-k
|
||||
health publicProcedure
|
||||
user me, list, markAbsent
|
||||
area list
|
||||
project list, byAreaSlug, byId (mit area), create, archive,
|
||||
setMilestoneStatus, listArchived
|
||||
deal list, kpis, create, updateStage (kein UI, Phase 2)
|
||||
project list, byAreaSlug, byId, create, update, archive,
|
||||
setMilestoneStatus, addMilestone, updateMilestone, removeMilestone,
|
||||
setModus, setPhase, addPhaseGate, phaseGates,
|
||||
addStatus, statusHistory, listArchived
|
||||
lead list, byId, forProject, create, update, addContact, removeContact,
|
||||
addTouchpoint, removeTouchpoint, promoteToDeal, importCsv
|
||||
risk forProject, create, update, remove
|
||||
stakeholder forProject, create, update, remove
|
||||
change forProject, create, update, remove
|
||||
deal list, kpis, create, updateStage
|
||||
gtm list, create, setStatus (kein UI, Phase 2)
|
||||
campaign list, create, funnel, crosslink (kein UI, Phase 2)
|
||||
blocker listOpen, byProject, create, resolve
|
||||
dayEntry today, todayTeam, pendingCarryOver, checkIn,
|
||||
updateTodos, submitReflection, feed, todayPresence
|
||||
dayEntry today, todayTeam, pendingCarryOver, checkIn, updateTodos,
|
||||
editTodoTitle, addTodo, submitReflection, feed, todayPresence
|
||||
time now, start, stop, listToday, update, upsertManual,
|
||||
delete, teamToday
|
||||
dashboard overview
|
||||
@@ -282,7 +305,7 @@ Login-Route ist außerhalb der `AppShell` (`/login`). Alle übrigen Routen unter
|
||||
|
||||
### State
|
||||
|
||||
- **Server-State**: ausschließlich React Query via tRPC (`createTRPCReact<AppRouter>`). Konfig in `apps/web/src/lib/trpc-provider.tsx` (30 s staleTime, ein Retry, zentrales onError → Toast).
|
||||
- **Server-State**: ausschließlich React Query via tRPC (`createTRPCReact<AppRouter>`). Konfig in `apps/web/src/lib/trpc-provider.tsx` (**staleTime 0** → Daten werden bei Mount/Tab-Fokus neu geholt, kein Polling; ein Retry; zentrales onError → Toast). Mutationen invalidieren zusätzlich gezielt die gleichzeitig sichtbaren Sichten.
|
||||
- **Auth-State**: React Query `user.me` (Hook `useCurrentUser`).
|
||||
- **Lokaler UI-State**: `useState` in der Komponente. Kein globaler Store.
|
||||
|
||||
@@ -337,7 +360,7 @@ Konstanten (`MAX_TODO_TEXT_LENGTH`, `WERKTAGE`, `JOURFIXE_DAY`, `REFLEXION_REMIN
|
||||
`docker-compose.yml` definiert vier Services:
|
||||
|
||||
| Service | Image | Rolle |
|
||||
|---|---|---|
|
||||
| ---------- | ------------------------------- | ----------------------------------------------------------------------------- |
|
||||
| `postgres` | `postgres:16-alpine` | DB, persistentes Volume `cockpit_postgres_data`, Backups in `cockpit_backups` |
|
||||
| `api` | Build aus `apps/api/Dockerfile` | Fastify auf 3000, hängt an Postgres-Health |
|
||||
| `web` | Build aus `apps/web/Dockerfile` | Vite-Build wird in `cockpit_web_dist`-Volume gelegt |
|
||||
@@ -357,7 +380,7 @@ Env-Variablen werden über `.env.production` injiziert. Required: `POSTGRES_PASS
|
||||
|
||||
`scripts/backup.sh` läuft als System-Cron im Postgres-Container: tägliches `pg_dump` mit 14-Tage-Retention + Heartbeat an `/internal/cron/pg-dump-backup` für Audit.
|
||||
|
||||
### CI
|
||||
### CI & Auto-Deploy
|
||||
|
||||
`.gitea/workflows/ci.yml`:
|
||||
|
||||
@@ -366,6 +389,13 @@ quality → install, typecheck, lint, format:check, test
|
||||
build → install, web build, api build (needs quality)
|
||||
```
|
||||
|
||||
`.gitea/workflows/deploy.yml` (Runner `runs-on: host` auf dem Homeserver): **bei jedem Push auf `main`** → `git reset --hard origin/main`, `docker compose up -d --build`, dann Warten bis `cockpit-api` healthy. Es gibt **keinen manuellen Trigger** — ein (ggf. leerer) Push löst den Deploy aus.
|
||||
|
||||
**Startup-Verhalten der API** (`apps/api/src/server.ts`): vor dem Listen wird
|
||||
|
||||
1. `runMigrations()` ausgeführt (Drizzle-Migrationen idempotent; schlägt eine fehl, startet die API nicht), dann
|
||||
2. `ensureBaseAreas()` (legt die 4 Basis-Bereiche idempotent an, damit z. B. der „Neues Projekt"-Dropdown nie leer ist — auch auf einer nicht geseedeten Prod-DB).
|
||||
|
||||
---
|
||||
|
||||
## Konventionen — Pflicht-Lesen vor Code-Edits
|
||||
@@ -385,7 +415,7 @@ build → install, web build, api build (needs quality)
|
||||
## Was bewusst NICHT gebaut ist (Phase 2)
|
||||
|
||||
- **Plane-/Outline-API-Sync** — Cockpit verlinkt nur, hängt sich nichts ab
|
||||
- **Kanban-Pipeline / Lead-Funnel-UI** — Schemas existieren, aber UI raus
|
||||
- **Kanban-Pipeline / Deal-Funnel-UI** — `gtm`/`campaign` ohne UI (Lead-CRM ist gebaut)
|
||||
- **Reportings / Wochen-/Monatsauswertungen** — bewusst minimal
|
||||
- **Reaktionen / Kommentare** auf Tagesupdates
|
||||
- **Mobile schreibbar** — Desktop-first, mobil nur lesbar
|
||||
@@ -406,7 +436,7 @@ Vollständige PRD/Architektur/UX/Stories im `_bmad-output/planning-artifacts/`-O
|
||||
- Anti-Ziele und Roadmap-Hinweise
|
||||
|
||||
| Datei | Inhalt |
|
||||
|---|---|
|
||||
| ---------------------------------------------- | --------------------------------------- |
|
||||
| `prds/prd-projectmanagement-2026-05-25/prd.md` | PRD (49 FRs, 16 NFRs) |
|
||||
| `architecture.md` | Stack-Entscheidungen, Patterns |
|
||||
| `ux-design-specification.md` | Brand-Tokens, Komponenten, Voice & Tone |
|
||||
@@ -417,7 +447,7 @@ Vollständige PRD/Architektur/UX/Stories im `_bmad-output/planning-artifacts/`-O
|
||||
## Repo & Remote
|
||||
|
||||
- **Default-Branch**: `main`
|
||||
- **Remote**: `ssh://git@git.tool-ctrl.de:2222/toolctrl-labs/everythingbutwork.git` (Gitea, non-standard SSH-Port)
|
||||
- **Remote**: `ssh://git@git.hg-int.dev:2222/toolctrl-labs/everythingbutwork.git` (Gitea, non-standard SSH-Port)
|
||||
- **Gitignore**: `.env`, `node_modules`, `dist`, `_bmad/`-Tools (Bmad-Framework), `.claude/`, `ToolCTRL Brand Identity/` (215 MB Raw-Assets)
|
||||
|
||||
---
|
||||
|
||||
+8
-1
@@ -15,7 +15,14 @@ COPY apps/api ./apps/api
|
||||
COPY packages/db ./packages/db
|
||||
COPY packages/shared ./packages/shared
|
||||
|
||||
RUN pnpm --filter api build
|
||||
# Die Workspace-Libs werden zur Laufzeit (Node) als JS geladen. Ihre tsconfig hat
|
||||
# jedoch noEmit:true und main zeigt auf die TS-Quelle — Node kann das nicht laden.
|
||||
# Daher hier mit Emit kompilieren und main/exports im Image auf die dist-Artefakte
|
||||
# umbiegen (nur im Image; Repo-Quelle, Dev-Modus und Web-/Vite-Build bleiben unberührt).
|
||||
RUN pnpm exec tsc -p packages/shared/tsconfig.json --noEmit false \
|
||||
&& pnpm exec tsc -p packages/db/tsconfig.json --noEmit false \
|
||||
&& pnpm --filter api build \
|
||||
&& node -e "const fs=require('fs');for(const p of ['packages/db','packages/shared']){const f=p+'/package.json';const j=JSON.parse(fs.readFileSync(f,'utf8'));const fix=s=>s.replace('./src/','./dist/').replace(/[.]ts$/,'.js');if(j.main){j.main=fix(j.main);j.types=j.main.replace(/[.]js$/,'.d.ts');}if(j.exports)for(const k in j.exports){if(typeof j.exports[k]==='string')j.exports[k]=fix(j.exports[k]);}fs.writeFileSync(f,JSON.stringify(j,null,2));}"
|
||||
|
||||
# --- runtime ---
|
||||
FROM node:22-alpine AS runtime
|
||||
|
||||
@@ -111,13 +111,18 @@ export async function registerAuthRoutes(app: FastifyInstance): Promise<void> {
|
||||
// die App ohne Authentik durchnavigierbar ist. Authentik kommt in der späteren
|
||||
// Roadmap. Nur aktiv bei NODE_ENV=development.
|
||||
if (env.NODE_ENV === 'development') {
|
||||
const handler = async (req: import('fastify').FastifyRequest, reply: import('fastify').FastifyReply) => {
|
||||
const handler = async (
|
||||
req: import('fastify').FastifyRequest,
|
||||
reply: import('fastify').FastifyReply,
|
||||
) => {
|
||||
const { getDb } = await import('../db.js');
|
||||
const { user } = await import('@cockpit/db');
|
||||
const { eq } = await import('drizzle-orm');
|
||||
const { db } = getDb();
|
||||
|
||||
const found = (await db.select().from(user).where(eq(user.email, 'dejan@tool-ctrl.de')).limit(1))[0];
|
||||
const found = (
|
||||
await db.select().from(user).where(eq(user.email, 'dejan@tool-ctrl.de')).limit(1)
|
||||
)[0];
|
||||
const userRow = found
|
||||
? found
|
||||
: await upsertUserFromOidc({
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { FastifyInstance, FastifyRequest } from 'fastify';
|
||||
import { isNull } from 'drizzle-orm';
|
||||
import { dayEntry } from '@cockpit/db';
|
||||
import { loadEnv } from '../env.js';
|
||||
import { logger } from '../lib/logger.js';
|
||||
import { getDb } from '../db.js';
|
||||
import { publishYesterdaysEntries } from '../routers/day-entry.js';
|
||||
import { publishYesterdaysEntries, applyWorkdayBoundary } from '../routers/day-entry.js';
|
||||
import { previousWerktag, todayIso } from '../lib/werktag.js';
|
||||
|
||||
function authorize(req: FastifyRequest): void {
|
||||
@@ -15,6 +17,33 @@ function authorize(req: FastifyRequest): void {
|
||||
}
|
||||
|
||||
export async function registerCronRoutes(app: FastifyInstance): Promise<void> {
|
||||
// 6-Uhr-Schnitt teamweit: beendet offene Nacht-Einträge, deren Arbeitstag
|
||||
// abgelaufen ist, und startet den Folge-Tag. Lazy passiert das ohnehin beim
|
||||
// nächsten Request der Person — dieser Cron (≈06:05) hält das Team-Dashboard
|
||||
// konsistent, auch ohne dass die Person aktiv wird.
|
||||
app.post('/internal/cron/apply-workday-boundaries', async (req, reply) => {
|
||||
try {
|
||||
authorize(req);
|
||||
} catch (err) {
|
||||
reply.code(401);
|
||||
logger.warn({ err }, 'unauthorized cron call');
|
||||
return { error: 'unauthorized' };
|
||||
}
|
||||
const { db } = getDb();
|
||||
const now = new Date();
|
||||
const openRows = await db
|
||||
.selectDistinct({ userId: dayEntry.userId })
|
||||
.from(dayEntry)
|
||||
.where(isNull(dayEntry.checkedOutAt));
|
||||
let cut = 0;
|
||||
for (const { userId } of openRows) {
|
||||
await applyWorkdayBoundary(db, userId, now);
|
||||
cut++;
|
||||
}
|
||||
logger.info({ usersChecked: cut }, 'applied workday boundaries');
|
||||
return { ok: true, usersChecked: cut };
|
||||
});
|
||||
|
||||
app.post('/internal/cron/publish-day-entries', async (req, reply) => {
|
||||
try {
|
||||
authorize(req);
|
||||
|
||||
@@ -19,6 +19,13 @@ const envSchema = z.object({
|
||||
CRON_BEARER_TOKEN: z.string().min(8),
|
||||
|
||||
PUBLIC_BASE_URL: z.string().url().default('http://localhost:5173'),
|
||||
|
||||
// Kimai-Anbindung (optional). Erst wenn alle gesetzt sind, wird beim
|
||||
// Check-In/Out wirklich nach Kimai synchronisiert; sonst No-Op.
|
||||
KIMAI_BASE_URL: z.string().url().optional(),
|
||||
KIMAI_API_TOKEN: z.string().min(1).optional(),
|
||||
KIMAI_PROJECT_ID: z.coerce.number().int().optional(),
|
||||
KIMAI_ACTIVITY_ID: z.coerce.number().int().optional(),
|
||||
});
|
||||
|
||||
export type Env = z.infer<typeof envSchema>;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseCsv, normalizeHeader } from './csv.js';
|
||||
|
||||
describe('parseCsv', () => {
|
||||
it('parst einfache Zeilen', () => {
|
||||
expect(parseCsv('a,b,c\n1,2,3')).toEqual([
|
||||
['a', 'b', 'c'],
|
||||
['1', '2', '3'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('ignoriert einen abschließenden Zeilenumbruch', () => {
|
||||
expect(parseCsv('a,b\n1,2\n')).toEqual([
|
||||
['a', 'b'],
|
||||
['1', '2'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('behandelt \\r\\n', () => {
|
||||
expect(parseCsv('a,b\r\n1,2')).toEqual([
|
||||
['a', 'b'],
|
||||
['1', '2'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('respektiert Anführungszeichen mit Komma und Quote-Escape', () => {
|
||||
expect(parseCsv('a,b\n"x, y","sagt ""hi"""')).toEqual([
|
||||
['a', 'b'],
|
||||
['x, y', 'sagt "hi"'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('erlaubt Zeilenumbruch innerhalb von Quotes', () => {
|
||||
expect(parseCsv('a,b\n"erste\nzweite",2')).toEqual([
|
||||
['a', 'b'],
|
||||
['erste\nzweite', '2'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('behält leere Felder', () => {
|
||||
expect(parseCsv('a,b,c\n1,,3')).toEqual([
|
||||
['a', 'b', 'c'],
|
||||
['1', '', '3'],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeHeader', () => {
|
||||
it('normalisiert Umlaute und Sonderzeichen', () => {
|
||||
expect(normalizeHeader('E-Mail')).toBe('email');
|
||||
expect(normalizeHeader('Straße')).toBe('strasse');
|
||||
expect(normalizeHeader(' Quelle ')).toBe('quelle');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
// Minimaler, robuster CSV-Parser (RFC-4180-nah): unterstützt Anführungszeichen,
|
||||
// eingebettete Kommata/Zeilenumbrüche und doppelte Quotes ("") als Escape.
|
||||
|
||||
export function parseCsv(input: string): string[][] {
|
||||
const text = input.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = '';
|
||||
let inQuotes = false;
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text[i];
|
||||
if (inQuotes) {
|
||||
if (c === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
} else if (c === '"') {
|
||||
inQuotes = true;
|
||||
} else if (c === ',') {
|
||||
row.push(field);
|
||||
field = '';
|
||||
} else if (c === '\n') {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
row = [];
|
||||
field = '';
|
||||
} else {
|
||||
field += c;
|
||||
}
|
||||
}
|
||||
// Letztes Feld / letzte Zeile (falls Datei nicht mit \n endet).
|
||||
if (field !== '' || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Header-Zelle auf einen vergleichbaren Schlüssel normalisieren
|
||||
// ("E-Mail" → "email", "Straße" → "strasse").
|
||||
export function normalizeHeader(h: string): string {
|
||||
return h
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/ß/g, 'ss')
|
||||
.replace(/[^a-z0-9]/g, '');
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { germanNationwideHolidays, isGermanHoliday } from './holidays.js';
|
||||
import { isWerktag } from './werktag.js';
|
||||
|
||||
describe('germanNationwideHolidays', () => {
|
||||
it('feste Feiertage 2026', () => {
|
||||
const h = germanNationwideHolidays(2026);
|
||||
for (const d of ['2026-01-01', '2026-05-01', '2026-10-03', '2026-12-25', '2026-12-26']) {
|
||||
expect(h.has(d)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('oster-abhängige Feiertage 2026 (Ostern = 05.04.2026)', () => {
|
||||
const h = germanNationwideHolidays(2026);
|
||||
expect(h.has('2026-04-03')).toBe(true); // Karfreitag
|
||||
expect(h.has('2026-04-06')).toBe(true); // Ostermontag
|
||||
expect(h.has('2026-05-14')).toBe(true); // Christi Himmelfahrt
|
||||
expect(h.has('2026-05-25')).toBe(true); // Pfingstmontag
|
||||
});
|
||||
|
||||
it('oster-abhängige Feiertage 2025 (Ostern = 20.04.2025)', () => {
|
||||
const h = germanNationwideHolidays(2025);
|
||||
expect(h.has('2025-04-18')).toBe(true); // Karfreitag
|
||||
expect(h.has('2025-06-09')).toBe(true); // Pfingstmontag
|
||||
});
|
||||
|
||||
it('normale Tage sind keine Feiertage', () => {
|
||||
expect(isGermanHoliday('2026-06-08')).toBe(false);
|
||||
});
|
||||
|
||||
it('isWerktag behandelt Feiertage als Nicht-Werktag', () => {
|
||||
expect(isWerktag('2026-05-01')).toBe(false); // Tag der Arbeit (Freitag)
|
||||
expect(isWerktag('2026-05-25')).toBe(false); // Pfingstmontag
|
||||
expect(isWerktag('2026-06-08')).toBe(true); // normaler Montag
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
// Bundesweite gesetzliche Feiertage in Deutschland. Diese 9 gelten in ALLEN
|
||||
// Bundesländern — sie als Nicht-Werktag zu behandeln ist daher immer korrekt.
|
||||
// Landesspezifische Feiertage (z. B. Fronleichnam, Reformationstag) sind hier
|
||||
// bewusst NICHT enthalten; die können bei Bedarf pro Bundesland ergänzt werden.
|
||||
|
||||
const cache = new Map<number, Set<string>>();
|
||||
|
||||
function isoFromParts(year: number, month: number, day: number): string {
|
||||
return new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function addDays(year: number, month: number, day: number, offset: number): string {
|
||||
const d = new Date(Date.UTC(year, month - 1, day));
|
||||
d.setUTCDate(d.getUTCDate() + offset);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
// Ostersonntag (gregorianisch) nach Meeus/Jones/Butcher.
|
||||
function easterSunday(year: number): { month: number; day: number } {
|
||||
const a = year % 19;
|
||||
const b = Math.floor(year / 100);
|
||||
const c = year % 100;
|
||||
const d = Math.floor(b / 4);
|
||||
const e = b % 4;
|
||||
const f = Math.floor((b + 8) / 25);
|
||||
const g = Math.floor((b - f + 1) / 3);
|
||||
const h = (19 * a + b - d - g + 15) % 30;
|
||||
const i = Math.floor(c / 4);
|
||||
const k = c % 4;
|
||||
const l = (32 + 2 * e + 2 * i - h - k) % 7;
|
||||
const m = Math.floor((a + 11 * h + 22 * l) / 451);
|
||||
const month = Math.floor((h + l - 7 * m + 114) / 31); // 3 = März, 4 = April
|
||||
const day = ((h + l - 7 * m + 114) % 31) + 1;
|
||||
return { month, day };
|
||||
}
|
||||
|
||||
export function germanNationwideHolidays(year: number): Set<string> {
|
||||
const cached = cache.get(year);
|
||||
if (cached) return cached;
|
||||
const e = easterSunday(year);
|
||||
const set = new Set<string>([
|
||||
isoFromParts(year, 1, 1), // Neujahr
|
||||
addDays(year, e.month, e.day, -2), // Karfreitag
|
||||
addDays(year, e.month, e.day, 1), // Ostermontag
|
||||
isoFromParts(year, 5, 1), // Tag der Arbeit
|
||||
addDays(year, e.month, e.day, 39), // Christi Himmelfahrt
|
||||
addDays(year, e.month, e.day, 50), // Pfingstmontag
|
||||
isoFromParts(year, 10, 3), // Tag der Deutschen Einheit
|
||||
isoFromParts(year, 12, 25), // 1. Weihnachtstag
|
||||
isoFromParts(year, 12, 26), // 2. Weihnachtstag
|
||||
]);
|
||||
cache.set(year, set);
|
||||
return set;
|
||||
}
|
||||
|
||||
export function isGermanHoliday(iso: string): boolean {
|
||||
const year = Number(iso.slice(0, 4));
|
||||
if (!Number.isFinite(year)) return false;
|
||||
return germanNationwideHolidays(year).has(iso);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Kimai-Anbindung (optional). Nur wenn KIMAI_BASE_URL + KIMAI_API_TOKEN +
|
||||
// KIMAI_PROJECT_ID + KIMAI_ACTIVITY_ID gesetzt sind, wird wirklich synchronisiert;
|
||||
// sonst No-Op. Alle Calls sind best-effort — ein Kimai-Ausfall darf den
|
||||
// ebw-Check-In/Out NIE blockieren.
|
||||
|
||||
import { loadEnv } from '../env.js';
|
||||
import { logger } from './logger.js';
|
||||
|
||||
type KimaiConfig = {
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
projectId: number;
|
||||
activityId: number;
|
||||
};
|
||||
|
||||
function kimaiConfig(): KimaiConfig | null {
|
||||
const env = loadEnv();
|
||||
if (
|
||||
env.KIMAI_BASE_URL &&
|
||||
env.KIMAI_API_TOKEN &&
|
||||
env.KIMAI_PROJECT_ID !== undefined &&
|
||||
env.KIMAI_ACTIVITY_ID !== undefined
|
||||
) {
|
||||
return {
|
||||
baseUrl: env.KIMAI_BASE_URL.replace(/\/$/, ''),
|
||||
token: env.KIMAI_API_TOKEN,
|
||||
projectId: env.KIMAI_PROJECT_ID,
|
||||
activityId: env.KIMAI_ACTIVITY_ID,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function kimaiEnabled(): boolean {
|
||||
return kimaiConfig() !== null;
|
||||
}
|
||||
|
||||
async function safeText(res: Response): Promise<string> {
|
||||
try {
|
||||
return (await res.text()).slice(0, 300);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Startet ein laufendes Timesheet in Kimai (Clock-In). Liefert die Kimai-
|
||||
* Timesheet-ID zurück oder null (nicht konfiguriert / Fehler).
|
||||
*/
|
||||
export async function kimaiClockIn(opts: {
|
||||
begin: Date;
|
||||
description?: string;
|
||||
}): Promise<number | null> {
|
||||
const cfg = kimaiConfig();
|
||||
if (!cfg) {
|
||||
logger.debug('kimai not configured — clock-in skipped');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${cfg.baseUrl}/api/timesheets`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${cfg.token}` },
|
||||
body: JSON.stringify({
|
||||
begin: opts.begin.toISOString(),
|
||||
project: cfg.projectId,
|
||||
activity: cfg.activityId,
|
||||
description: opts.description ?? 'ebw Check-In',
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
logger.warn({ status: res.status, body: await safeText(res) }, 'kimai clock-in failed');
|
||||
return null;
|
||||
}
|
||||
const data = (await res.json()) as { id?: number };
|
||||
return typeof data.id === 'number' ? data.id : null;
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'kimai clock-in error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stoppt das laufende Timesheet in Kimai (Clock-Out). Best-effort.
|
||||
*/
|
||||
export async function kimaiClockOut(opts: { timesheetId: number }): Promise<boolean> {
|
||||
const cfg = kimaiConfig();
|
||||
if (!cfg) {
|
||||
logger.debug('kimai not configured — clock-out skipped');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${cfg.baseUrl}/api/timesheets/${opts.timesheetId}/stop`, {
|
||||
method: 'PATCH',
|
||||
headers: { Authorization: `Bearer ${cfg.token}` },
|
||||
});
|
||||
if (!res.ok) {
|
||||
logger.warn({ status: res.status, body: await safeText(res) }, 'kimai clock-out failed');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
logger.warn({ err }, 'kimai clock-out error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +1,32 @@
|
||||
// Pflicht-Minimum-Berechnung (Leitfaden §9).
|
||||
// Punkte 1–4 + 6 werden manuell in der App gepflegt; Punkt 5 (Status-Ampel aktuell)
|
||||
// wird hier zeitabhängig berechnet und im Cron auf alle Projekte aktualisiert.
|
||||
// wird hier zeitabhängig berechnet und im Cron aktualisiert.
|
||||
|
||||
import { eq, isNotNull, isNull, and, desc } from 'drizzle-orm';
|
||||
import { project, dayEntry } from '@cockpit/db';
|
||||
import { werktageBetween, todayIso } from './werktag.js';
|
||||
import { eq, desc } from 'drizzle-orm';
|
||||
import { project, projectStatus } from '@cockpit/db';
|
||||
import type { Db } from '@cockpit/db';
|
||||
import { werktageBetween, todayIso, formatIsoDate } from './werktag.js';
|
||||
|
||||
const MAX_AGE_WERKTAGE = 7;
|
||||
|
||||
export async function recomputePflichtMinimumStatusActual(
|
||||
db: import('@cockpit/db').Db,
|
||||
): Promise<{ updated: number }> {
|
||||
export async function recomputePflichtMinimumStatusActual(db: Db): Promise<{ updated: number }> {
|
||||
const projects = await db.select().from(project).where(eq(project.archiviert, false));
|
||||
const today = todayIso();
|
||||
let updated = 0;
|
||||
for (const p of projects) {
|
||||
// Letzte Reflexion mit Projektbezug? (Vereinfachung: letzter day_entry mit Ampel,
|
||||
// dessen Update das Projekt-Status-Cache gesetzt hat = `status_cache` selbst.)
|
||||
const lastEntry = (
|
||||
// Jüngsten Statusbericht DIESES Projekts heranziehen (statt global).
|
||||
const last = (
|
||||
await db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(isNotNull(dayEntry.reflectedAt)))
|
||||
.orderBy(desc(dayEntry.reflectedAt))
|
||||
.select({ createdAt: projectStatus.createdAt })
|
||||
.from(projectStatus)
|
||||
.where(eq(projectStatus.projectId, p.id))
|
||||
.orderBy(desc(projectStatus.createdAt))
|
||||
.limit(1)
|
||||
)[0];
|
||||
|
||||
const actual = lastEntry ? werktageBetween(lastEntry.date, today) <= MAX_AGE_WERKTAGE : false;
|
||||
const actual = last
|
||||
? werktageBetween(formatIsoDate(last.createdAt), today) <= MAX_AGE_WERKTAGE
|
||||
: false;
|
||||
|
||||
const newState = { ...p.pflichtMinimumState, status_aktuell: actual };
|
||||
if (JSON.stringify(newState) !== JSON.stringify(p.pflichtMinimumState)) {
|
||||
@@ -36,6 +36,3 @@ export async function recomputePflichtMinimumStatusActual(
|
||||
}
|
||||
return { updated };
|
||||
}
|
||||
|
||||
// linter
|
||||
void isNull;
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { countStreakDays } from './streak.js';
|
||||
|
||||
const S = (...d: string[]) => new Set(d);
|
||||
const NONE = new Set<string>();
|
||||
|
||||
describe('countStreakDays', () => {
|
||||
it('zählt aufeinanderfolgende volle Werktage', () => {
|
||||
// Mi/Di/Mo voll, heute Mi
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-10',
|
||||
fullDates: S('2026-06-10', '2026-06-09', '2026-06-08'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it('heute noch nicht reflektiert → Schonfrist (zählt ab gestern)', () => {
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-10',
|
||||
fullDates: S('2026-06-09', '2026-06-08'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it('bricht bei einem ausgelassenen Werktag', () => {
|
||||
// 06-09 fehlt
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-10',
|
||||
fullDates: S('2026-06-10', '2026-06-08'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('Wochenende ist neutral (Fr + Mo zählt durch)', () => {
|
||||
// heute Mo 06-08, Fr 06-05 voll; 06-04 (Do) fehlt → 2
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-08',
|
||||
fullDates: S('2026-06-08', '2026-06-05'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it('Abwesenheit ist neutral (überspringen, nicht brechen)', () => {
|
||||
// heute Mi 06-10 voll, Di 06-09 Urlaub, Mo 06-08 voll
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-10',
|
||||
fullDates: S('2026-06-10', '2026-06-08'),
|
||||
absenceDates: S('2026-06-09'),
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it('Feiertag bricht die Streak NICHT (Pfingstmontag 25.05.2026)', () => {
|
||||
// heute Mi 05-27, Di 05-26 voll, Mo 05-25 Pfingstmontag, Fr 05-22 voll
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-05-27',
|
||||
fullDates: S('2026-05-27', '2026-05-26', '2026-05-22'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it('Reflexion am Wochenende zählt nicht zu 0 (zählt Freitag)', () => {
|
||||
// heute Sa 06-06, voll am Sa + Fr 06-05; früher nichts
|
||||
expect(
|
||||
countStreakDays({
|
||||
today: '2026-06-06',
|
||||
fullDates: S('2026-06-06', '2026-06-05'),
|
||||
absenceDates: NONE,
|
||||
}),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('leere Historie → 0', () => {
|
||||
expect(countStreakDays({ today: '2026-06-10', fullDates: NONE, absenceDates: NONE })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { isWerktag, previousWerktag } from './werktag.js';
|
||||
|
||||
/**
|
||||
* Zählt aufeinanderfolgende Werktage (Mo-Fr, ohne Feiertage) mit voller
|
||||
* Reflexion, rückwärts ab `today`.
|
||||
*
|
||||
* Regeln:
|
||||
* - Nur Tage in `fullDates` (status = 'full') zählen.
|
||||
* - Tage in `absenceDates` (Urlaub/Krank/…) sind neutral: überspringen, nicht
|
||||
* zählen, nicht brechen.
|
||||
* - Wochenenden und Feiertage sind keine Werktage → übersprungen.
|
||||
* - Heute ist Schonfrist: ist heute noch nicht voll, wird ab dem vorherigen
|
||||
* Werktag gezählt (die laufende Streak bleibt über den Tag erhalten).
|
||||
* - Bricht beim ersten Werktag, der weder voll noch Abwesenheit ist.
|
||||
*/
|
||||
export function countStreakDays(opts: {
|
||||
today: string;
|
||||
fullDates: Set<string>;
|
||||
absenceDates: Set<string>;
|
||||
}): number {
|
||||
const { today, fullDates, absenceDates } = opts;
|
||||
let cursor = today;
|
||||
let streak = 0;
|
||||
|
||||
// Heute noch nicht reflektiert → ab vorherigem Werktag zählen.
|
||||
if (!fullDates.has(cursor)) cursor = previousWerktag(today);
|
||||
|
||||
while (true) {
|
||||
// Nicht-Werktag (z. B. an einem Wochenende/Feiertag reflektiert) überspringen,
|
||||
// statt die Streak fälschlich abzubrechen.
|
||||
if (!isWerktag(cursor)) {
|
||||
cursor = previousWerktag(cursor);
|
||||
continue;
|
||||
}
|
||||
if (absenceDates.has(cursor)) {
|
||||
cursor = previousWerktag(cursor);
|
||||
continue;
|
||||
}
|
||||
if (fullDates.has(cursor)) {
|
||||
streak++;
|
||||
cursor = previousWerktag(cursor);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return streak;
|
||||
}
|
||||
@@ -1,5 +1,16 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { formatIsoDate, isWerktag, nextWerktag, previousWerktag, werktageBetween } from './werktag';
|
||||
import {
|
||||
formatIsoDate,
|
||||
isWerktag,
|
||||
nextWerktag,
|
||||
previousWerktag,
|
||||
werktageBetween,
|
||||
berlinDayStartMs,
|
||||
addCalendarDays,
|
||||
workdayCutoffMs,
|
||||
isWorkdaySealed,
|
||||
isEditableWithinGrace,
|
||||
} from './werktag';
|
||||
|
||||
describe('werktag', () => {
|
||||
it('formatIsoDate liefert YYYY-MM-DD in Berlin TZ', () => {
|
||||
@@ -7,24 +18,77 @@ describe('werktag', () => {
|
||||
expect(formatIsoDate(d)).toBe('2026-05-25');
|
||||
});
|
||||
|
||||
it('isWerktag erkennt Mo-Fr', () => {
|
||||
expect(isWerktag('2026-05-25')).toBe(true); // Mo
|
||||
expect(isWerktag('2026-05-29')).toBe(true); // Fr
|
||||
expect(isWerktag('2026-05-30')).toBe(false); // Sa
|
||||
expect(isWerktag('2026-05-31')).toBe(false); // So
|
||||
it('isWerktag erkennt Mo-Fr (ohne Feiertage)', () => {
|
||||
expect(isWerktag('2026-06-08')).toBe(true); // Mo
|
||||
expect(isWerktag('2026-06-12')).toBe(true); // Fr
|
||||
expect(isWerktag('2026-06-13')).toBe(false); // Sa
|
||||
expect(isWerktag('2026-06-14')).toBe(false); // So
|
||||
});
|
||||
|
||||
it('nextWerktag springt über Wochenende', () => {
|
||||
expect(nextWerktag('2026-05-29')).toBe('2026-06-01'); // Fr → Mo
|
||||
expect(nextWerktag('2026-05-25')).toBe('2026-05-26'); // Mo → Di
|
||||
expect(nextWerktag('2026-06-12')).toBe('2026-06-15'); // Fr → Mo
|
||||
expect(nextWerktag('2026-06-08')).toBe('2026-06-09'); // Mo → Di
|
||||
});
|
||||
|
||||
it('previousWerktag springt über Wochenende', () => {
|
||||
expect(previousWerktag('2026-06-01')).toBe('2026-05-29'); // Mo → Fr
|
||||
expect(previousWerktag('2026-06-15')).toBe('2026-06-12'); // Mo → Fr
|
||||
});
|
||||
|
||||
it('werktageBetween zählt korrekt', () => {
|
||||
// Mo 2026-05-25 bis Mo 2026-06-01 (exkl.): 5 Werktage
|
||||
expect(werktageBetween('2026-05-25', '2026-06-01')).toBe(5);
|
||||
// Mo 2026-06-08 bis Mo 2026-06-15 (exkl.): 5 Werktage
|
||||
expect(werktageBetween('2026-06-08', '2026-06-15')).toBe(5);
|
||||
});
|
||||
|
||||
it('berlinDayStartMs ist DST-korrekt', () => {
|
||||
// Sommer (CEST, +2): 00:00 Berlin = 22:00 UTC am Vortag
|
||||
expect(berlinDayStartMs('2026-06-06')).toBe(Date.parse('2026-06-05T22:00:00Z'));
|
||||
// Winter (CET, +1): 00:00 Berlin = 23:00 UTC am Vortag
|
||||
expect(berlinDayStartMs('2026-01-15')).toBe(Date.parse('2026-01-14T23:00:00Z'));
|
||||
});
|
||||
|
||||
it('addCalendarDays verschiebt Kalendertage (auch über Monatsgrenze)', () => {
|
||||
expect(addCalendarDays('2026-06-07', 1)).toBe('2026-06-08');
|
||||
expect(addCalendarDays('2026-06-30', 1)).toBe('2026-07-01');
|
||||
expect(addCalendarDays('2026-06-07', -1)).toBe('2026-06-06');
|
||||
});
|
||||
|
||||
it('workdayCutoffMs ist 06:00 Berlin am Folgetag (DST-korrekt)', () => {
|
||||
// Sommer (CEST, +2): 06:00 Berlin = 04:00 UTC
|
||||
expect(workdayCutoffMs('2026-06-06')).toBe(Date.parse('2026-06-07T04:00:00Z'));
|
||||
// Winter (CET, +1): 06:00 Berlin = 05:00 UTC
|
||||
expect(workdayCutoffMs('2026-01-15')).toBe(Date.parse('2026-01-16T05:00:00Z'));
|
||||
});
|
||||
|
||||
describe('isWorkdaySealed — der Arbeitstag = Check-in-Kalendertag', () => {
|
||||
// Eintrag mit Datum Sa 2026-06-06 (Check-in irgendwann an dem Tag).
|
||||
const entry = '2026-06-06';
|
||||
it('vor Mitternacht: nicht versiegelt', () => {
|
||||
expect(isWorkdaySealed(entry, new Date('2026-06-06T22:00:00+02:00'))).toBe(false);
|
||||
});
|
||||
it('nach Mitternacht, aber vor 06:00: noch der Arbeitstag (nicht versiegelt)', () => {
|
||||
// 03:00 in der Nacht → gehört noch zum 06.
|
||||
expect(isWorkdaySealed(entry, new Date('2026-06-07T03:00:00+02:00'))).toBe(false);
|
||||
});
|
||||
it('um/nach 06:00 des Folgetags: versiegelt', () => {
|
||||
expect(isWorkdaySealed(entry, new Date('2026-06-07T06:00:00+02:00'))).toBe(true);
|
||||
expect(isWorkdaySealed(entry, new Date('2026-06-07T09:00:00+02:00'))).toBe(true);
|
||||
});
|
||||
it('ein nach Mitternacht begonnener Tag (Datum = 07.) gilt um 06:00 noch nicht als versiegelt', () => {
|
||||
const sameDayStart = '2026-06-07';
|
||||
expect(isWorkdaySealed(sameDayStart, new Date('2026-06-07T06:00:00+02:00'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isEditableWithinGrace — 3-Tage-Nachfrist', () => {
|
||||
const entry = '2026-06-05'; // Fr
|
||||
it('am Eintragstag selbst editierbar', () => {
|
||||
expect(isEditableWithinGrace(entry, new Date('2026-06-05T20:00:00+02:00'))).toBe(true);
|
||||
});
|
||||
it('bis Ende des 3. Tages danach (08.) editierbar', () => {
|
||||
expect(isEditableWithinGrace(entry, new Date('2026-06-08T23:00:00+02:00'))).toBe(true);
|
||||
});
|
||||
it('ab dem 4. Tag (09.) gesperrt', () => {
|
||||
expect(isEditableWithinGrace(entry, new Date('2026-06-09T00:30:00+02:00'))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,18 @@
|
||||
// Werktag-Logik in Europe/Berlin. Single source of truth fürs Backend
|
||||
// (Frontend bekommt fertige Felder).
|
||||
|
||||
import { isGermanHoliday } from './holidays.js';
|
||||
|
||||
const TIMEZONE = 'Europe/Berlin';
|
||||
|
||||
/**
|
||||
* Uhrzeit (Berlin), zu der ein Arbeitstag „kippt": Wer um 06:00 noch eingestempelt
|
||||
* ist, dessen Tag wird automatisch beendet (siehe `applyWorkdayBoundary`). Bis dahin
|
||||
* gehört eine über Mitternacht laufende Session noch zum Tag, an dem eingestempelt
|
||||
* wurde — der Arbeitstag eines Eintrags = der Kalendertag des Check-ins.
|
||||
*/
|
||||
export const WORKDAY_RESET_HOUR = 6;
|
||||
|
||||
/**
|
||||
* Gibt das aktuelle Datum (oder `now`) als `YYYY-MM-DD` in Europe/Berlin zurück.
|
||||
*/
|
||||
@@ -10,6 +20,45 @@ export function todayIso(now: Date = new Date()): string {
|
||||
return formatIsoDate(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschiebt ein ISO-Datum um `n` Kalendertage (nicht Werktage). DST-robust, weil
|
||||
* `parseIsoDate` von 12:00 UTC ausgeht und in Berlin formatiert wird.
|
||||
*/
|
||||
export function addCalendarDays(iso: string, n: number): string {
|
||||
const d = parseIsoDate(iso);
|
||||
return formatIsoDate(new Date(d.getTime() + n * 24 * 60 * 60 * 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* Epoch-ms des Zeitpunkts, ab dem der Arbeitstag mit Eintrags-Datum `entryDate`
|
||||
* abgelaufen ist: 06:00 Europe/Berlin am Folgetag (DST-korrekt).
|
||||
*/
|
||||
export function workdayCutoffMs(entryDate: string): number {
|
||||
return berlinDayStartMs(addCalendarDays(entryDate, 1)) + WORKDAY_RESET_HOUR * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* True, wenn der Arbeitstag eines Eintrags (Datum = Check-in-Kalendertag) bereits
|
||||
* „versiegelt" ist, d. h. `now` liegt am/nach 06:00 des Folgetags. Versiegelte Tage
|
||||
* sind read-only und werden nicht mehr als aktiver Tag angezeigt.
|
||||
*/
|
||||
export function isWorkdaySealed(entryDate: string, now: Date = new Date()): boolean {
|
||||
return now.getTime() >= workdayCutoffMs(entryDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* True, solange ein Eintrag mit Datum `entryDate` noch nachträglich bearbeitet
|
||||
* werden darf: bis zum Ende des `graceDays`-ten Kalendertages danach (Default 3).
|
||||
* Genutzt für die Reflexion in der Historie (Tag selbst + 3 Tage Nachfrist).
|
||||
*/
|
||||
export function isEditableWithinGrace(
|
||||
entryDate: string,
|
||||
now: Date = new Date(),
|
||||
graceDays = 3,
|
||||
): boolean {
|
||||
return now.getTime() < berlinDayStartMs(addCalendarDays(entryDate, graceDays + 1));
|
||||
}
|
||||
|
||||
export function formatIsoDate(d: Date): string {
|
||||
const fmt = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: TIMEZONE,
|
||||
@@ -20,6 +69,36 @@ export function formatIsoDate(d: Date): string {
|
||||
return fmt.format(d); // en-CA liefert ISO YYYY-MM-DD
|
||||
}
|
||||
|
||||
/**
|
||||
* Epoch-ms von 00:00 Europe/Berlin am gegebenen Tag (DST-korrekt). Genutzt, um
|
||||
* Tagesgrenzen für Zeit-Auswertungen zu bilden (z. B. Tagesanteil eines über
|
||||
* Mitternacht laufenden Timers).
|
||||
*/
|
||||
export function berlinDayStartMs(iso: string): number {
|
||||
const utcMidnight = Date.parse(`${iso}T00:00:00Z`);
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: TIMEZONE,
|
||||
hourCycle: 'h23',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).formatToParts(new Date(utcMidnight));
|
||||
const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? '0');
|
||||
const asIfUtc = Date.UTC(
|
||||
get('year'),
|
||||
get('month') - 1,
|
||||
get('day'),
|
||||
get('hour'),
|
||||
get('minute'),
|
||||
get('second'),
|
||||
);
|
||||
const offset = asIfUtc - utcMidnight; // ms, die Berlin der UTC voraus ist
|
||||
return utcMidnight - offset;
|
||||
}
|
||||
|
||||
export function parseIsoDate(s: string): Date {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) {
|
||||
throw new Error(`Ungültiges ISO-Datum: ${s}`);
|
||||
@@ -29,12 +108,13 @@ export function parseIsoDate(s: string): Date {
|
||||
}
|
||||
|
||||
/**
|
||||
* Mo-Fr = Werktag. Feiertage Phase 2.
|
||||
* Werktag = Mo-Fr und kein bundesweiter gesetzlicher Feiertag.
|
||||
*/
|
||||
export function isWerktag(s: string): boolean {
|
||||
const d = parseIsoDate(s);
|
||||
const wd = new Intl.DateTimeFormat('en-US', { timeZone: TIMEZONE, weekday: 'short' }).format(d);
|
||||
return wd !== 'Sat' && wd !== 'Sun';
|
||||
if (wd === 'Sat' || wd === 'Sun') return false;
|
||||
return !isGermanHoliday(s);
|
||||
}
|
||||
|
||||
export function nextWerktag(s: string): string {
|
||||
|
||||
@@ -6,10 +6,15 @@ import { userRouter } from './user.js';
|
||||
import { dashboardRouter } from './dashboard.js';
|
||||
import { projectRouter } from './project.js';
|
||||
import { dealRouter, gtmRouter } from './deal.js';
|
||||
import { leadRouter } from './lead.js';
|
||||
import { riskRouter } from './risk.js';
|
||||
import { stakeholderRouter } from './stakeholder.js';
|
||||
import { changeRouter } from './change.js';
|
||||
import { campaignRouter } from './campaign.js';
|
||||
import { areaRouter } from './area.js';
|
||||
import { blockerRouter } from './blocker.js';
|
||||
import { timeRouter } from './time.js';
|
||||
import { searchRouter } from './search.js';
|
||||
|
||||
export const appRouter = router({
|
||||
health: publicProcedure.query(() => ({
|
||||
@@ -21,11 +26,16 @@ export const appRouter = router({
|
||||
project: projectRouter,
|
||||
deal: dealRouter,
|
||||
gtm: gtmRouter,
|
||||
lead: leadRouter,
|
||||
risk: riskRouter,
|
||||
stakeholder: stakeholderRouter,
|
||||
change: changeRouter,
|
||||
campaign: campaignRouter,
|
||||
blocker: blockerRouter,
|
||||
dayEntry: dayEntryRouter,
|
||||
time: timeRouter,
|
||||
dashboard: dashboardRouter,
|
||||
search: searchRouter,
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -2,7 +2,7 @@ import { z } from 'zod';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { eq, isNull, desc } from 'drizzle-orm';
|
||||
import { blocker, project, user } from '@cockpit/db';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { router, protectedProcedure, auditedProcedure } from '../trpc.js';
|
||||
|
||||
export const blockerRouter = router({
|
||||
listOpen: protectedProcedure.query(async ({ ctx }) => {
|
||||
@@ -52,7 +52,7 @@ export const blockerRouter = router({
|
||||
return created;
|
||||
}),
|
||||
|
||||
resolve: protectedProcedure
|
||||
resolve: auditedProcedure('blocker.resolve')
|
||||
.input(
|
||||
z.object({
|
||||
blockerId: z.string().uuid(),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { desc, eq } from 'drizzle-orm';
|
||||
import { changeEntry, user } from '@cockpit/db';
|
||||
import { ChangeSchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
|
||||
export const changeRouter = router({
|
||||
forProject: protectedProcedure
|
||||
.input(ChangeSchemas.changeForProjectInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const rows = await ctx.db
|
||||
.select({ change: changeEntry, authorName: user.name })
|
||||
.from(changeEntry)
|
||||
.leftJoin(user, eq(user.id, changeEntry.createdBy))
|
||||
.where(eq(changeEntry.projectId, input.projectId))
|
||||
.orderBy(desc(changeEntry.createdAt));
|
||||
return rows.map((r) => ({ ...r.change, authorName: r.authorName }));
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(ChangeSchemas.createChangeInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [created] = await ctx.db
|
||||
.insert(changeEntry)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
titel: input.titel,
|
||||
auswirkung: input.auswirkung ?? null,
|
||||
entscheidung: input.entscheidung,
|
||||
createdBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
.input(ChangeSchemas.updateChangeInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (
|
||||
await ctx.db.select().from(changeEntry).where(eq(changeEntry.id, id)).limit(1)
|
||||
)[0];
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(changeEntry)
|
||||
.set(patch)
|
||||
.where(eq(changeEntry.id, id))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
remove: protectedProcedure
|
||||
.input(ChangeSchemas.removeChangeInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(changeEntry).where(eq(changeEntry.id, input.id));
|
||||
return { ok: true as const };
|
||||
}),
|
||||
});
|
||||
@@ -1,5 +1,15 @@
|
||||
import { and, eq, isNotNull, isNull, count } from 'drizzle-orm';
|
||||
import { area, project, blocker, dayEntry, user, type Area, type Project } from '@cockpit/db';
|
||||
import { and, eq, ne, isNull, isNotNull, lt, count, asc, desc } from 'drizzle-orm';
|
||||
import {
|
||||
area,
|
||||
project,
|
||||
blocker,
|
||||
dayEntry,
|
||||
user,
|
||||
risk,
|
||||
milestone,
|
||||
type Area,
|
||||
type Project,
|
||||
} from '@cockpit/db';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { todayIso, previousWerktag } from '../lib/werktag.js';
|
||||
import { aggregateAreaAmpel } from '../lib/ampel.js';
|
||||
@@ -7,8 +17,16 @@ import { aggregateAreaAmpel } from '../lib/ampel.js';
|
||||
export const dashboardRouter = router({
|
||||
overview: protectedProcedure.query(async ({ ctx }) => {
|
||||
const todayDate = todayIso();
|
||||
const [areas, allProjects, openBlockers, todayPresence, totalActiveUsers, feedRows] =
|
||||
await Promise.all([
|
||||
const [
|
||||
areas,
|
||||
allProjects,
|
||||
openBlockers,
|
||||
todayPresence,
|
||||
totalActiveUsers,
|
||||
feedRows,
|
||||
showstopperRows,
|
||||
milestoneRows,
|
||||
] = await Promise.all([
|
||||
ctx.db.select().from(area).orderBy(area.order),
|
||||
ctx.db.select().from(project).where(eq(project.archiviert, false)),
|
||||
ctx.db.select().from(blocker).where(isNull(blocker.resolvedAt)),
|
||||
@@ -30,9 +48,51 @@ export const dashboardRouter = router({
|
||||
})
|
||||
.from(dayEntry)
|
||||
.innerJoin(user, eq(user.id, dayEntry.userId))
|
||||
.where(and(isNotNull(dayEntry.publishedAt), eq(dayEntry.status, 'full')))
|
||||
.orderBy(dayEntry.publishedAt)
|
||||
// „Gestern im Team": volle Reflexionen vor heute (heutige bleiben privat
|
||||
// bis morgen). Unabhängig vom publish-Cron.
|
||||
.where(and(lt(dayEntry.date, todayDate), eq(dayEntry.status, 'full')))
|
||||
.orderBy(desc(dayEntry.date), desc(dayEntry.reflectedAt))
|
||||
.limit(50),
|
||||
ctx.db
|
||||
.select({
|
||||
id: risk.id,
|
||||
title: risk.title,
|
||||
projectId: risk.projectId,
|
||||
projectName: project.name,
|
||||
})
|
||||
.from(risk)
|
||||
.innerJoin(project, eq(project.id, risk.projectId))
|
||||
.where(
|
||||
and(
|
||||
eq(risk.showstopper, true),
|
||||
eq(risk.kind, 'risiko'),
|
||||
ne(risk.status, 'geschlossen'),
|
||||
eq(project.archiviert, false),
|
||||
),
|
||||
),
|
||||
// Anstehende Meilensteine (offen/überfällig, mit Datum) projektübergreifend.
|
||||
ctx.db
|
||||
.select({
|
||||
id: milestone.id,
|
||||
title: milestone.title,
|
||||
due: milestone.due,
|
||||
status: milestone.status,
|
||||
projectId: milestone.projectId,
|
||||
projectName: project.name,
|
||||
projectLogoUrl: project.logoUrl,
|
||||
areaId: project.areaId,
|
||||
})
|
||||
.from(milestone)
|
||||
.innerJoin(project, eq(project.id, milestone.projectId))
|
||||
.where(
|
||||
and(
|
||||
ne(milestone.status, 'done'),
|
||||
isNotNull(milestone.due),
|
||||
eq(project.archiviert, false),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(milestone.due))
|
||||
.limit(15),
|
||||
]);
|
||||
|
||||
const projectsByArea = new Map<string, Project[]>();
|
||||
@@ -55,6 +115,15 @@ export const dashboardRouter = router({
|
||||
};
|
||||
});
|
||||
|
||||
// „Gestern im Team": pro User nur die neueste Reflexion (feedRows ist nach
|
||||
// date desc, reflectedAt desc sortiert → erster Treffer je User = aktuellste).
|
||||
const seenUsers = new Set<string>();
|
||||
const feedLatestPerUser = feedRows.filter((r) => {
|
||||
if (seenUsers.has(r.userId)) return false;
|
||||
seenUsers.add(r.userId);
|
||||
return true;
|
||||
});
|
||||
|
||||
const presentToday = new Set(todayPresence.map((p) => p.userId));
|
||||
const usersAll = await ctx.db
|
||||
.select({ id: user.id, name: user.name })
|
||||
@@ -78,10 +147,18 @@ export const dashboardRouter = router({
|
||||
fehlende,
|
||||
},
|
||||
jourfixe: { nextDate: nextJourfixe(todayDate), label: 'Di 11:00' },
|
||||
showstoppers: showstopperRows,
|
||||
meilensteine: milestoneRows.map((m) => ({
|
||||
...m,
|
||||
ueberfaellig: m.due != null && m.due < todayDate,
|
||||
})),
|
||||
kritischeModi: allProjects
|
||||
.filter((p) => p.modus === 'eskalation' || p.modus === 'taskforce')
|
||||
.map((p) => ({ id: p.id, name: p.name, areaId: p.areaId, modus: p.modus })),
|
||||
pflichtMinimumOffen: allProjects
|
||||
.filter((p) => Object.values(p.pflichtMinimumState).some((v) => v === false))
|
||||
.map((p) => ({ id: p.id, name: p.name, areaId: p.areaId })),
|
||||
feed: feedRows,
|
||||
.map((p) => ({ id: p.id, name: p.name, areaId: p.areaId, logoUrl: p.logoUrl })),
|
||||
feed: feedLatestPerUser,
|
||||
gestern: previousWerktag(todayDate),
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -1,9 +1,130 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { and, eq, isNull, isNotNull, lt, asc, inArray } from 'drizzle-orm';
|
||||
import { dayEntry, todo, blocker, type Todo } from '@cockpit/db';
|
||||
import { z } from 'zod';
|
||||
import { and, eq, gt, gte, isNull, lt, lte, asc, desc, inArray } from 'drizzle-orm';
|
||||
import { dayEntry, todo, blocker, user, type Db, type DayEntry, type Todo } from '@cockpit/db';
|
||||
import { DayEntrySchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { todayIso } from '../lib/werktag.js';
|
||||
import {
|
||||
todayIso,
|
||||
previousWerktag,
|
||||
addCalendarDays,
|
||||
workdayCutoffMs,
|
||||
isWorkdaySealed,
|
||||
isEditableWithinGrace,
|
||||
} from '../lib/werktag.js';
|
||||
import { kimaiClockIn, kimaiClockOut, kimaiEnabled } from '../lib/kimai.js';
|
||||
|
||||
/**
|
||||
* Der 6-Uhr-Schnitt: Ist um 06:00 (Berlin) noch ein Eintrag offen, dessen
|
||||
* Arbeitstag (= Check-in-Kalendertag) abgelaufen ist, wird er automatisch beendet
|
||||
* (checkedOutAt = 06:00 des Folgetags) und ein nahtloser Folge-Tag gestartet —
|
||||
* offene ToDos wandern mit. So entstehen aus Nacht-Durcharbeiten saubere
|
||||
* Tagesgrenzen, ohne dass der Nutzer manuell aus- und wieder einstempeln muss.
|
||||
*
|
||||
* Idempotent: ohne offenen, abgelaufenen Eintrag passiert nichts. Die Schleife
|
||||
* deckt (selten) mehrtägiges Durchlaufen ab; das Limit ist ein Sicherheitsnetz.
|
||||
*/
|
||||
export async function applyWorkdayBoundary(db: Db, userId: string, now: Date): Promise<void> {
|
||||
for (let i = 0; i < 14; i++) {
|
||||
const open = (
|
||||
await db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, userId), isNull(dayEntry.checkedOutAt)))
|
||||
.orderBy(desc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0];
|
||||
if (!open || !isWorkdaySealed(open.date, now)) return;
|
||||
|
||||
const cutoff = new Date(workdayCutoffMs(open.date));
|
||||
const nextDate = addCalendarDays(open.date, 1);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
// 1) Alten Tag um 06:00 beenden.
|
||||
await tx
|
||||
.update(dayEntry)
|
||||
.set({ checkedOutAt: cutoff, updatedAt: now })
|
||||
.where(eq(dayEntry.id, open.id));
|
||||
|
||||
if (open.kimaiTimesheetId !== null && kimaiEnabled()) {
|
||||
await kimaiClockOut({ timesheetId: open.kimaiTimesheetId });
|
||||
}
|
||||
|
||||
// 2) Folge-Tag nur anlegen, wenn es ihn noch nicht gibt (unique userId+date).
|
||||
const existsNext = (
|
||||
await tx
|
||||
.select({ id: dayEntry.id })
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, userId), eq(dayEntry.date, nextDate)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
if (existsNext) return;
|
||||
|
||||
const [created] = await tx
|
||||
.insert(dayEntry)
|
||||
.values({
|
||||
userId,
|
||||
date: nextDate,
|
||||
status: 'begun',
|
||||
checkedInAt: cutoff,
|
||||
// Kein echter Lock-in — Anwesenheits-Anzeigen ignorieren diesen Check-in.
|
||||
autoCheckedIn: true,
|
||||
})
|
||||
.returning();
|
||||
if (!created) throw new Error('Folge-Tag konnte nicht angelegt werden.');
|
||||
|
||||
// 3) Offene ToDos in den neuen Tag übernehmen (im alten als übertragen markiert).
|
||||
const openTodos = await tx
|
||||
.select()
|
||||
.from(todo)
|
||||
.where(and(eq(todo.dayEntryId, open.id), eq(todo.status, 'open')))
|
||||
.orderBy(asc(todo.order));
|
||||
if (openTodos.length > 0) {
|
||||
await tx.insert(todo).values(
|
||||
openTodos.map((t, idx) => ({
|
||||
dayEntryId: created.id,
|
||||
userId,
|
||||
date: nextDate,
|
||||
title: t.title,
|
||||
order: idx,
|
||||
bezugKind: t.bezugKind,
|
||||
bezugId: t.bezugId,
|
||||
carriedOver: true,
|
||||
})),
|
||||
);
|
||||
await tx
|
||||
.update(todo)
|
||||
.set({ carriedOver: true })
|
||||
.where(
|
||||
inArray(
|
||||
todo.id,
|
||||
openTodos.map((t) => t.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Der aktive Arbeitstag des Nutzers nach Anwendung des 6-Uhr-Schnitts: der jüngste
|
||||
* Eintrag, der noch nicht versiegelt ist (offen ODER bereits ausgecheckt, aber vor
|
||||
* 06:00 des Folgetags — also noch fortsetzbar). `null`, wenn kein laufender/heutiger
|
||||
* Tag existiert (→ Frontend zeigt das Einstempel-Formular).
|
||||
*/
|
||||
export async function getActiveEntry(db: Db, userId: string, now: Date): Promise<DayEntry | null> {
|
||||
await applyWorkdayBoundary(db, userId, now);
|
||||
const entry = (
|
||||
await db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(eq(dayEntry.userId, userId))
|
||||
.orderBy(desc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0];
|
||||
if (!entry || isWorkdaySealed(entry.date, now)) return null;
|
||||
return entry;
|
||||
}
|
||||
|
||||
export const dayEntryRouter = router({
|
||||
/**
|
||||
@@ -13,11 +134,9 @@ export const dayEntryRouter = router({
|
||||
*/
|
||||
todayTeam: protectedProcedure.query(async ({ ctx }) => {
|
||||
const date = todayIso();
|
||||
const entries = await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(eq(dayEntry.date, date));
|
||||
if (entries.length === 0) return [] as Array<{ userId: string; entryStatus: string; todos: Todo[] }>;
|
||||
const entries = await ctx.db.select().from(dayEntry).where(eq(dayEntry.date, date));
|
||||
if (entries.length === 0)
|
||||
return [] as Array<{ userId: string; entryStatus: string; todos: Todo[] }>;
|
||||
const ids = entries.map((e) => e.id);
|
||||
const todos = await ctx.db
|
||||
.select()
|
||||
@@ -64,25 +183,22 @@ export const dayEntryRouter = router({
|
||||
}),
|
||||
|
||||
/**
|
||||
* Heute-Status der eigenen Person.
|
||||
* Heute-Status der eigenen Person. „Heute" = der aktive Arbeitstag: ein laufender
|
||||
* (offener) Eintrag bleibt aktiv, auch über Mitternacht hinaus, bis 06:00 des
|
||||
* Folgetags. Ein bereits ausgecheckter Tag bleibt bis dahin sichtbar (fortsetzbar).
|
||||
*/
|
||||
today: protectedProcedure.query(async ({ ctx }) => {
|
||||
const date = todayIso();
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), eq(dayEntry.date, date)))
|
||||
.limit(1);
|
||||
const entry = rows[0] ?? null;
|
||||
const now = new Date();
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, now);
|
||||
if (!entry) {
|
||||
return { date, entry: null, todos: [] as Todo[] };
|
||||
return { date: todayIso(now), entry: null, todos: [] as Todo[] };
|
||||
}
|
||||
const todos = await ctx.db
|
||||
.select()
|
||||
.from(todo)
|
||||
.where(eq(todo.dayEntryId, entry.id))
|
||||
.orderBy(todo.order);
|
||||
return { date, entry, todos };
|
||||
return { date: entry.date, entry, todos };
|
||||
}),
|
||||
|
||||
/**
|
||||
@@ -91,6 +207,8 @@ export const dayEntryRouter = router({
|
||||
checkIn: protectedProcedure
|
||||
.input(DayEntrySchemas.checkInInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
// Erst einen ggf. abgelaufenen Nacht-Eintrag sauber abschließen (6-Uhr-Schnitt).
|
||||
await applyWorkdayBoundary(ctx.db, ctx.user.id, new Date());
|
||||
const date = input.date ?? todayIso();
|
||||
|
||||
// Verhindert Doppel-Einstempeln. Wenn bereits Einträge existieren, Fehler.
|
||||
@@ -162,9 +280,95 @@ export const dayEntryRouter = router({
|
||||
return { entry: created, todos: todoRows, carriedOver: stale.length };
|
||||
});
|
||||
|
||||
// Kimai-Sync (best-effort, nicht blockierend): Check-In = Clock-In.
|
||||
if (kimaiEnabled()) {
|
||||
const tsId = await kimaiClockIn({
|
||||
begin: result.entry.checkedInAt ?? new Date(),
|
||||
description: `ebw — ${ctx.user.name}`,
|
||||
});
|
||||
if (tsId !== null) {
|
||||
await ctx.db
|
||||
.update(dayEntry)
|
||||
.set({ kimaiTimesheetId: tsId, kimaiSynced: true })
|
||||
.where(eq(dayEntry.id, result.entry.id));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Check-Out / Arbeitsende: beendet den laufenden (offenen) Arbeitstag — egal, ob
|
||||
* er heute oder gestern (Nachtarbeit über Mitternacht) begonnen wurde. Best-effort
|
||||
* Kimai-Clock-Out, falls beim Check-In ein Timesheet gestartet wurde.
|
||||
*/
|
||||
checkOut: protectedProcedure.mutation(async ({ ctx }) => {
|
||||
const now = new Date();
|
||||
await applyWorkdayBoundary(ctx.db, ctx.user.id, now);
|
||||
const entry = (
|
||||
await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), isNull(dayEntry.checkedOutAt)))
|
||||
.orderBy(desc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0];
|
||||
if (!entry) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Du bist gerade nicht eingestempelt.' });
|
||||
}
|
||||
|
||||
const [updated] = await ctx.db
|
||||
.update(dayEntry)
|
||||
.set({ checkedOutAt: now, updatedAt: now })
|
||||
.where(eq(dayEntry.id, entry.id))
|
||||
.returning();
|
||||
|
||||
if (entry.kimaiTimesheetId !== null && kimaiEnabled()) {
|
||||
await kimaiClockOut({ timesheetId: entry.kimaiTimesheetId });
|
||||
}
|
||||
return updated;
|
||||
}),
|
||||
|
||||
/**
|
||||
* „Arbeit fortsetzen" — hebt einen Feierabend wieder auf (versehentlich geklickt
|
||||
* oder doch noch weitergearbeitet). Öffnet den aktiven, noch nicht versiegelten
|
||||
* Tag erneut (checkedOutAt → null). Möglich, solange der Arbeitstag läuft, d. h.
|
||||
* vor 06:00 des Folgetags. Danach ist der Tag final → neu einstempeln.
|
||||
*/
|
||||
reopen: protectedProcedure.mutation(async ({ ctx }) => {
|
||||
const now = new Date();
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, now);
|
||||
if (!entry) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message:
|
||||
'Kein fortsetzbarer Arbeitstag — der letzte Tag ist abgeschlossen. Stempel neu ein.',
|
||||
});
|
||||
}
|
||||
if (!entry.checkedOutAt) return entry; // läuft bereits
|
||||
|
||||
const [updated] = await ctx.db
|
||||
.update(dayEntry)
|
||||
.set({ checkedOutAt: null, updatedAt: now })
|
||||
.where(eq(dayEntry.id, entry.id))
|
||||
.returning();
|
||||
|
||||
// Best-effort: Kimai wieder anlaufen lassen, falls aktiv.
|
||||
if (kimaiEnabled()) {
|
||||
const tsId = await kimaiClockIn({
|
||||
begin: now,
|
||||
description: `ebw — ${ctx.user.name} (fortgesetzt)`,
|
||||
});
|
||||
if (tsId !== null) {
|
||||
await ctx.db
|
||||
.update(dayEntry)
|
||||
.set({ kimaiTimesheetId: tsId, kimaiSynced: true })
|
||||
.where(eq(dayEntry.id, entry.id));
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}),
|
||||
|
||||
/**
|
||||
* ToDos im Verlauf des Tages ändern (vor Reflexion).
|
||||
*/
|
||||
@@ -209,6 +413,107 @@ export const dayEntryRouter = router({
|
||||
return result;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Einzelnen ToDo-Titel korrigieren (z. B. Tippfehler) — auch noch in der
|
||||
* Reflexion. Erlaubt, solange der Arbeitstag des ToDos noch läuft (vor 06:00 des
|
||||
* Folgetags); gleiche Editierbarkeits-Regel wie die Reflexion.
|
||||
*/
|
||||
editTodoTitle: protectedProcedure
|
||||
.input(DayEntrySchemas.editTodoTitleInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(todo)
|
||||
.where(and(eq(todo.id, input.todoId), eq(todo.userId, ctx.user.id)))
|
||||
.limit(1);
|
||||
const existing = rows[0];
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'ToDo nicht gefunden.' });
|
||||
}
|
||||
if (!isEditableWithinGrace(existing.date, new Date())) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'ToDos können nur bis 3 Tage nach dem Tag bearbeitet werden.',
|
||||
});
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(todo)
|
||||
.set({ title: input.title })
|
||||
.where(eq(todo.id, input.todoId))
|
||||
.returning();
|
||||
return updated;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Einzelnes ToDo mitten am Tag hinzufügen (auch nach der Reflexion möglich,
|
||||
* solange der Tageseintrag vom heutigen Berlin-Tag ist).
|
||||
*/
|
||||
addTodo: protectedProcedure
|
||||
.input(DayEntrySchemas.addTodoInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, new Date());
|
||||
if (!entry) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Du bist gerade nicht eingestempelt.',
|
||||
});
|
||||
}
|
||||
const existing = await ctx.db
|
||||
.select({ id: todo.id })
|
||||
.from(todo)
|
||||
.where(eq(todo.dayEntryId, entry.id));
|
||||
const [created] = await ctx.db
|
||||
.insert(todo)
|
||||
.values({
|
||||
dayEntryId: entry.id,
|
||||
userId: ctx.user.id,
|
||||
date: entry.date,
|
||||
title: input.title,
|
||||
order: existing.length,
|
||||
bezugKind: input.bezugKind ?? null,
|
||||
bezugId: input.bezugId ?? null,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Ungeplant dazugekommenes & bereits erledigtes Item nachtragen
|
||||
* („btw, das habe ich heute auch noch gemacht"). Wird sofort als erledigt
|
||||
* und als ungeplant markiert.
|
||||
*/
|
||||
addUnplanned: protectedProcedure
|
||||
.input(DayEntrySchemas.addUnplannedInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, new Date());
|
||||
if (!entry) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Du bist gerade nicht eingestempelt.',
|
||||
});
|
||||
}
|
||||
const existing = await ctx.db
|
||||
.select({ id: todo.id })
|
||||
.from(todo)
|
||||
.where(eq(todo.dayEntryId, entry.id));
|
||||
const [created] = await ctx.db
|
||||
.insert(todo)
|
||||
.values({
|
||||
dayEntryId: entry.id,
|
||||
userId: ctx.user.id,
|
||||
date: entry.date,
|
||||
title: input.title,
|
||||
order: existing.length,
|
||||
bezugKind: input.bezugKind ?? null,
|
||||
bezugId: input.bezugId ?? null,
|
||||
status: 'done',
|
||||
unplanned: true,
|
||||
completedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Abend-Reflexion. Setzt Ampel + Trend, optional Blocker.
|
||||
*/
|
||||
@@ -224,13 +529,12 @@ export const dayEntryRouter = router({
|
||||
if (!entry) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Tageseintrag nicht gefunden.' });
|
||||
}
|
||||
// Editierbar, solange das Eintrags-Datum noch der heutige Berlin-Tag ist.
|
||||
// Damit kann mehrmals am Tag aktualisiert werden; nach 00:00 (Europe/Berlin)
|
||||
// ist der Vortag final und kann nicht mehr verändert werden.
|
||||
if (entry.date !== todayIso(new Date())) {
|
||||
// Reflexion ist bis 3 Kalendertage nach dem Eintragstag nachträglich
|
||||
// editierbar (Nachfrist für die Historie). Danach final.
|
||||
if (!isEditableWithinGrace(entry.date, new Date())) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Reflexion eines Vortags kann nicht mehr bearbeitet werden.',
|
||||
message: 'Reflexion kann nur bis 3 Tage nach dem Tag bearbeitet werden.',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -300,15 +604,116 @@ export const dayEntryRouter = router({
|
||||
* Nutzbar in Story 3.4 (Dashboard-Feed).
|
||||
*/
|
||||
feed: protectedProcedure.query(async ({ ctx }) => {
|
||||
// Volle Reflexionen vor heute (heutige bleiben privat bis morgen) —
|
||||
// unabhängig vom publish-Cron.
|
||||
const today = todayIso();
|
||||
const entries = await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(isNotNull(dayEntry.publishedAt))
|
||||
.orderBy(dayEntry.publishedAt)
|
||||
.where(and(lt(dayEntry.date, today), eq(dayEntry.status, 'full')))
|
||||
.orderBy(desc(dayEntry.date), desc(dayEntry.reflectedAt))
|
||||
.limit(50);
|
||||
return entries;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Team-weite Historie eines (vergangenen) Tages: was hat jede/r gemacht —
|
||||
* Reflexion (Ampel/Trend/Text) + ToDos. Default-Datum = vorheriger Werktag.
|
||||
* Datums-Navigation (prev/next Werktag) wird mitgeliefert.
|
||||
*/
|
||||
historyForDate: protectedProcedure
|
||||
.input(DayEntrySchemas.historyForDateInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const today = todayIso();
|
||||
// Default-Tag = der jüngste Tag VOR heute, an dem es überhaupt Einträge gibt
|
||||
// (nicht starr der vorige Werktag — sonst sieht man Wochenend-Arbeit nicht).
|
||||
const fallbackDate =
|
||||
(
|
||||
await ctx.db
|
||||
.select({ d: dayEntry.date })
|
||||
.from(dayEntry)
|
||||
.where(lt(dayEntry.date, today))
|
||||
.orderBy(desc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0]?.d ?? previousWerktag(today);
|
||||
const date = input.date ?? fallbackDate;
|
||||
const isToday = date === today;
|
||||
|
||||
const entries = await ctx.db.select().from(dayEntry).where(eq(dayEntry.date, date));
|
||||
const userRows = await ctx.db
|
||||
.select({ id: user.id, name: user.name })
|
||||
.from(user)
|
||||
.where(eq(user.active, true));
|
||||
const nameById = new Map(userRows.map((u) => [u.id, u.name]));
|
||||
|
||||
const ids = entries.map((e) => e.id);
|
||||
const todoRows = ids.length
|
||||
? await ctx.db
|
||||
.select()
|
||||
.from(todo)
|
||||
.where(inArray(todo.dayEntryId, ids))
|
||||
.orderBy(asc(todo.order))
|
||||
: [];
|
||||
const todosByEntry = new Map<string, Todo[]>();
|
||||
for (const t of todoRows) {
|
||||
const arr = todosByEntry.get(t.dayEntryId) ?? [];
|
||||
arr.push(t);
|
||||
todosByEntry.set(t.dayEntryId, arr);
|
||||
}
|
||||
|
||||
const list = entries
|
||||
.map((e) => ({
|
||||
userId: e.userId,
|
||||
name: nameById.get(e.userId) ?? '—',
|
||||
status: e.status,
|
||||
ampel: e.ampel,
|
||||
trend: e.trend,
|
||||
// Heutige Reflexion bleibt privat bis morgen; ToDos sind teamweit sichtbar.
|
||||
reflectionText: isToday ? null : e.reflectionText,
|
||||
url: e.url,
|
||||
todos: (todosByEntry.get(e.id) ?? []).map((t) => ({
|
||||
id: t.id,
|
||||
title: t.title,
|
||||
status: t.status,
|
||||
dropReason: t.dropReason,
|
||||
unplanned: t.unplanned,
|
||||
})),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
const withEntry = new Set(entries.map((e) => e.userId));
|
||||
const ohneEintrag = userRows
|
||||
.filter((u) => !withEntry.has(u.id))
|
||||
.map((u) => u.name)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
// Pfeil-Navigation springt zum nächsten/vorherigen Tag MIT Einträgen
|
||||
// (überspringt leere Tage, erreicht aber Wochenend-Arbeit).
|
||||
const prevRow = (
|
||||
await ctx.db
|
||||
.select({ d: dayEntry.date })
|
||||
.from(dayEntry)
|
||||
.where(lt(dayEntry.date, date))
|
||||
.orderBy(desc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0];
|
||||
const nextRow = (
|
||||
await ctx.db
|
||||
.select({ d: dayEntry.date })
|
||||
.from(dayEntry)
|
||||
.where(and(gt(dayEntry.date, date), lte(dayEntry.date, today)))
|
||||
.orderBy(asc(dayEntry.date))
|
||||
.limit(1)
|
||||
)[0];
|
||||
return {
|
||||
date,
|
||||
prevDate: prevRow?.d ?? null,
|
||||
nextDate: nextRow?.d ?? null,
|
||||
entries: list,
|
||||
ohneEintrag,
|
||||
};
|
||||
}),
|
||||
|
||||
/**
|
||||
* „Heute fehlt"-Liste (Anwesenheits-Übersicht).
|
||||
*/
|
||||
@@ -323,11 +728,73 @@ export const dayEntryRouter = router({
|
||||
.where(eq(dayEntry.date, date));
|
||||
return rows;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Persönliche Wochenübersicht: die letzten 7 Kalendertage des eigenen Users —
|
||||
* pro Tag Status/Ampel/Trend, grobe Anwesenheit (Antritt→Feierabend) und ein
|
||||
* ToDo-Zähler (erledigt/offen/verworfen). Speist die Route „Meine Woche".
|
||||
*/
|
||||
myWeek: protectedProcedure.query(async ({ ctx }) => {
|
||||
const today = todayIso();
|
||||
const from = addCalendarDays(today, -6);
|
||||
const entries = await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(
|
||||
and(eq(dayEntry.userId, ctx.user.id), gte(dayEntry.date, from), lte(dayEntry.date, today)),
|
||||
)
|
||||
.orderBy(asc(dayEntry.date));
|
||||
|
||||
const ids = entries.map((e) => e.id);
|
||||
const todos = ids.length
|
||||
? await ctx.db.select().from(todo).where(inArray(todo.dayEntryId, ids))
|
||||
: [];
|
||||
const counts = new Map<string, { done: number; open: number; dropped: number }>();
|
||||
for (const t of todos) {
|
||||
const c = counts.get(t.dayEntryId) ?? { done: 0, open: 0, dropped: 0 };
|
||||
c[t.status] += 1;
|
||||
counts.set(t.dayEntryId, c);
|
||||
}
|
||||
|
||||
return entries.map((e) => ({
|
||||
date: e.date,
|
||||
status: e.status,
|
||||
ampel: e.ampel,
|
||||
trend: e.trend,
|
||||
checkedInAt: e.checkedInAt,
|
||||
checkedOutAt: e.checkedOutAt,
|
||||
todos: counts.get(e.id) ?? { done: 0, open: 0, dropped: 0 },
|
||||
}));
|
||||
}),
|
||||
|
||||
/**
|
||||
* Eigener Tageseintrag eines bestimmten Datums — zum nachträglichen Reflektieren
|
||||
* aus der Historie. `editable` zeigt, ob die 3-Tage-Nachfrist noch läuft.
|
||||
*/
|
||||
ownForDate: protectedProcedure
|
||||
.input(z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const entry =
|
||||
(
|
||||
await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), eq(dayEntry.date, input.date)))
|
||||
.limit(1)
|
||||
)[0] ?? null;
|
||||
if (!entry) return { entry: null, todos: [] as Todo[], editable: false };
|
||||
const todos = await ctx.db
|
||||
.select()
|
||||
.from(todo)
|
||||
.where(eq(todo.dayEntryId, entry.id))
|
||||
.orderBy(todo.order);
|
||||
return { entry, todos, editable: isEditableWithinGrace(entry.date, new Date()) };
|
||||
}),
|
||||
});
|
||||
|
||||
// Helper für Cron-Endpoint
|
||||
export async function publishYesterdaysEntries(
|
||||
ctx: { db: import('@cockpit/db').Db },
|
||||
ctx: { db: Db },
|
||||
yesterdayIso: string,
|
||||
): Promise<number> {
|
||||
const now = new Date();
|
||||
|
||||
@@ -64,10 +64,8 @@ export const dealRouter = router({
|
||||
stage: input.stage,
|
||||
enteredStageAt: new Date(),
|
||||
wonAt: input.stage === 'abschluss' ? new Date() : null,
|
||||
wonValueEur:
|
||||
input.stage === 'abschluss'
|
||||
? sql`COALESCE(${deal.valueEur} * ${deal.probability} / 100, 0)`
|
||||
: null,
|
||||
// Gewonnener Deal = voller Auftragswert (nicht mit Wahrscheinlichkeit gewichtet).
|
||||
wonValueEur: input.stage === 'abschluss' ? sql`COALESCE(${deal.valueEur}, 0)` : null,
|
||||
})
|
||||
.where(eq(deal.id, input.dealId))
|
||||
.returning();
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { and, asc, desc, eq, inArray, isNotNull, lte, sql } from 'drizzle-orm';
|
||||
import { lead, leadContact, leadTouchpoint, deal, area, user, project } from '@cockpit/db';
|
||||
import type { Db } from '@cockpit/db';
|
||||
import { LeadSchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { parseCsv, normalizeHeader } from '../lib/csv.js';
|
||||
import { todayIso } from '../lib/werktag.js';
|
||||
|
||||
const SALES_AREA_SLUG = 'vertrieb';
|
||||
|
||||
async function getSalesAreaId(db: Db): Promise<string> {
|
||||
const a = (await db.select().from(area).where(eq(area.slug, SALES_AREA_SLUG)).limit(1))[0];
|
||||
if (!a) throw new Error('Vertriebs-Bereich fehlt — bitte seed laufen lassen.');
|
||||
return a.id;
|
||||
}
|
||||
|
||||
export const leadRouter = router({
|
||||
// Liste aller Leads, mit Owner-Namen. Sortiert: zuletzt aktualisiert zuerst.
|
||||
list: protectedProcedure.query(async ({ ctx }) => {
|
||||
const rows = await ctx.db
|
||||
.select({
|
||||
lead: lead,
|
||||
ownerName: user.name,
|
||||
projectName: project.name,
|
||||
})
|
||||
.from(lead)
|
||||
.leftJoin(user, eq(user.id, lead.ownerUserId))
|
||||
.leftJoin(project, eq(project.id, lead.projectId))
|
||||
.orderBy(desc(lead.updatedAt));
|
||||
return rows.map((r) => ({ ...r.lead, ownerName: r.ownerName, projectName: r.projectName }));
|
||||
}),
|
||||
|
||||
/**
|
||||
* Fällige Wiedervorlagen: aktive Leads (cold/warm/hot), deren geplanter nächster
|
||||
* Schritt heute oder überfällig ist. naechsterSchrittDatum wurde erfasst, aber
|
||||
* nie als Liste gebündelt — so geht keine warme Spur mehr unter.
|
||||
*/
|
||||
dueFollowUps: protectedProcedure.query(async ({ ctx }) => {
|
||||
const today = todayIso();
|
||||
const rows = await ctx.db
|
||||
.select({
|
||||
id: lead.id,
|
||||
firma: lead.firma,
|
||||
status: lead.status,
|
||||
ownerName: user.name,
|
||||
naechsterSchritt: lead.naechsterSchritt,
|
||||
faelligAm: lead.naechsterSchrittDatum,
|
||||
})
|
||||
.from(lead)
|
||||
.leftJoin(user, eq(user.id, lead.ownerUserId))
|
||||
.where(
|
||||
and(
|
||||
inArray(lead.status, ['cold', 'warm', 'hot']),
|
||||
isNotNull(lead.naechsterSchrittDatum),
|
||||
lte(lead.naechsterSchrittDatum, today),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(lead.naechsterSchrittDatum));
|
||||
return rows;
|
||||
}),
|
||||
|
||||
// Leads, die einem Projekt zugeordnet sind (Vertriebs-Sicht im Projekt).
|
||||
forProject: protectedProcedure
|
||||
.input(LeadSchemas.leadsForProjectInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const rows = await ctx.db
|
||||
.select({ lead: lead, ownerName: user.name })
|
||||
.from(lead)
|
||||
.leftJoin(user, eq(user.id, lead.ownerUserId))
|
||||
.where(eq(lead.projectId, input.projectId))
|
||||
.orderBy(desc(lead.score), desc(lead.updatedAt));
|
||||
return rows.map((r) => ({ ...r.lead, ownerName: r.ownerName }));
|
||||
}),
|
||||
|
||||
byId: protectedProcedure.input(LeadSchemas.leadIdInput).query(async ({ ctx, input }) => {
|
||||
const l = (await ctx.db.select().from(lead).where(eq(lead.id, input.id)).limit(1))[0];
|
||||
if (!l) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lead nicht gefunden.' });
|
||||
const contacts = await ctx.db
|
||||
.select()
|
||||
.from(leadContact)
|
||||
.where(eq(leadContact.leadId, l.id))
|
||||
.orderBy(desc(leadContact.isPrimary), asc(leadContact.order));
|
||||
const touchpoints = await ctx.db
|
||||
.select({
|
||||
touchpoint: leadTouchpoint,
|
||||
bearbeiterName: user.name,
|
||||
})
|
||||
.from(leadTouchpoint)
|
||||
.leftJoin(user, eq(user.id, leadTouchpoint.bearbeiterUserId))
|
||||
.where(eq(leadTouchpoint.leadId, l.id))
|
||||
.orderBy(desc(leadTouchpoint.datum), desc(leadTouchpoint.createdAt));
|
||||
const linkedProject = l.projectId
|
||||
? ((
|
||||
await ctx.db
|
||||
.select({ id: project.id, name: project.name })
|
||||
.from(project)
|
||||
.where(eq(project.id, l.projectId))
|
||||
.limit(1)
|
||||
)[0] ?? null)
|
||||
: null;
|
||||
return {
|
||||
lead: l,
|
||||
contacts,
|
||||
project: linkedProject,
|
||||
touchpoints: touchpoints.map((t) => ({ ...t.touchpoint, bearbeiterName: t.bearbeiterName })),
|
||||
};
|
||||
}),
|
||||
|
||||
create: protectedProcedure.input(LeadSchemas.createLeadInput).mutation(async ({ ctx, input }) => {
|
||||
const areaId = await getSalesAreaId(ctx.db);
|
||||
const [created] = await ctx.db
|
||||
.insert(lead)
|
||||
.values({
|
||||
areaId,
|
||||
firma: input.firma,
|
||||
status: input.status,
|
||||
score: input.score,
|
||||
ownerUserId: input.ownerUserId ?? null,
|
||||
projectId: input.projectId ?? null,
|
||||
branche: input.branche ?? null,
|
||||
subSegment: input.subSegment ?? null,
|
||||
website: input.website ?? null,
|
||||
quelle: input.quelle ?? null,
|
||||
createdBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
if (!created) throw new Error('Lead konnte nicht angelegt werden.');
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: protectedProcedure.input(LeadSchemas.updateLeadInput).mutation(async ({ ctx, input }) => {
|
||||
const { id, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (await ctx.db.select().from(lead).where(eq(lead.id, id)).limit(1))[0];
|
||||
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lead nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(lead)
|
||||
.set({ ...patch, updatedAt: new Date() })
|
||||
.where(eq(lead.id, id))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lead nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// Kontaktpersonen -----------------------------------------------------------
|
||||
addContact: protectedProcedure
|
||||
.input(LeadSchemas.addContactInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const count =
|
||||
(
|
||||
await ctx.db
|
||||
.select({ c: sql<number>`count(*)::int` })
|
||||
.from(leadContact)
|
||||
.where(eq(leadContact.leadId, input.leadId))
|
||||
)[0]?.c ?? 0;
|
||||
const [created] = await ctx.db
|
||||
.insert(leadContact)
|
||||
.values({
|
||||
leadId: input.leadId,
|
||||
name: input.name,
|
||||
rolle: input.rolle ?? null,
|
||||
funktion: input.funktion ?? null,
|
||||
email: input.email ?? null,
|
||||
telefon: input.telefon ?? null,
|
||||
linkedin: input.linkedin ?? null,
|
||||
imBuyingCenterSeit: input.imBuyingCenterSeit ?? null,
|
||||
sprache: input.sprache ?? null,
|
||||
isPrimary: input.isPrimary,
|
||||
order: count,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
removeContact: protectedProcedure
|
||||
.input(LeadSchemas.removeContactInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(leadContact).where(eq(leadContact.id, input.contactId));
|
||||
return { ok: true as const };
|
||||
}),
|
||||
|
||||
// Austausch-Log -------------------------------------------------------------
|
||||
addTouchpoint: protectedProcedure
|
||||
.input(LeadSchemas.addTouchpointInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [created] = await ctx.db
|
||||
.insert(leadTouchpoint)
|
||||
.values({
|
||||
leadId: input.leadId,
|
||||
datum: input.datum,
|
||||
kanal: input.kanal,
|
||||
bearbeiterUserId: ctx.user.id,
|
||||
inhalt: input.inhalt,
|
||||
outcome: input.outcome ?? null,
|
||||
followUpBis: input.followUpBis ?? null,
|
||||
})
|
||||
.returning();
|
||||
// Touchpoint zählt als Aktivität → Lead als aktualisiert markieren.
|
||||
await ctx.db.update(lead).set({ updatedAt: new Date() }).where(eq(lead.id, input.leadId));
|
||||
return created;
|
||||
}),
|
||||
|
||||
removeTouchpoint: protectedProcedure
|
||||
.input(LeadSchemas.removeTouchpointInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(leadTouchpoint).where(eq(leadTouchpoint.id, input.touchpointId));
|
||||
return { ok: true as const };
|
||||
}),
|
||||
|
||||
// Lead → Pipeline-Deal promoten --------------------------------------------
|
||||
promoteToDeal: protectedProcedure
|
||||
.input(LeadSchemas.promoteToDealInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const l = (await ctx.db.select().from(lead).where(eq(lead.id, input.leadId)).limit(1))[0];
|
||||
if (!l) throw new TRPCError({ code: 'NOT_FOUND', message: 'Lead nicht gefunden.' });
|
||||
if (l.promotedDealId) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Dieser Lead wurde bereits zu einem Deal gemacht.',
|
||||
});
|
||||
}
|
||||
const result = await ctx.db.transaction(async (tx) => {
|
||||
const [createdDeal] = await tx
|
||||
.insert(deal)
|
||||
.values({
|
||||
areaId: l.areaId,
|
||||
name: l.firma,
|
||||
ownerUserId: l.ownerUserId,
|
||||
valueEur: input.valueEur,
|
||||
probability: input.probability,
|
||||
stage: 'lead',
|
||||
})
|
||||
.returning();
|
||||
if (!createdDeal) throw new Error('Deal konnte nicht angelegt werden.');
|
||||
await tx
|
||||
.update(lead)
|
||||
.set({ promotedDealId: createdDeal.id, updatedAt: new Date() })
|
||||
.where(eq(lead.id, l.id));
|
||||
return createdDeal;
|
||||
});
|
||||
return result;
|
||||
}),
|
||||
|
||||
// CSV-Import: erzeugt je Zeile einen Lead + primären Kontakt; Adresse →
|
||||
// standorte, Notizen → erster Austausch-Log-Eintrag. Dedup über Firmenname.
|
||||
importCsv: protectedProcedure
|
||||
.input(LeadSchemas.importLeadsCsvInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const areaId = await getSalesAreaId(ctx.db);
|
||||
const rows = parseCsv(input.csv);
|
||||
const summary = {
|
||||
created: 0,
|
||||
skippedEmpty: 0,
|
||||
skippedDuplicate: 0,
|
||||
contacts: 0,
|
||||
touchpoints: 0,
|
||||
};
|
||||
if (rows.length < 2 || !rows[0]) return summary;
|
||||
|
||||
const header = rows[0].map(normalizeHeader);
|
||||
const col = (key: string) => header.indexOf(key);
|
||||
const cells = {
|
||||
quelle: col('quelle'),
|
||||
vorname: col('vorname'),
|
||||
nachname: col('nachname'),
|
||||
position: col('position'),
|
||||
firma: col('firma'),
|
||||
strasse: col('strasse'),
|
||||
plz: col('plz'),
|
||||
ort: col('ort'),
|
||||
telefon: col('telefon'),
|
||||
mobil: col('mobil'),
|
||||
email: col('email'),
|
||||
website: col('website'),
|
||||
branche: col('branche'),
|
||||
notizen: col('notizen'),
|
||||
};
|
||||
const get = (row: string[], i: number) =>
|
||||
i >= 0 && i < row.length ? (row[i] ?? '').trim() : '';
|
||||
|
||||
const existing = await ctx.db.select({ firma: lead.firma }).from(lead);
|
||||
const seen = new Set(existing.map((e) => e.firma.trim().toLowerCase()));
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
|
||||
for (let r = 1; r < rows.length; r++) {
|
||||
const row = rows[r];
|
||||
if (!row || row.every((c) => c.trim() === '')) continue; // Leerzeile
|
||||
|
||||
const vorname = get(row, cells.vorname);
|
||||
const nachname = get(row, cells.nachname);
|
||||
const personName = `${vorname} ${nachname}`.trim();
|
||||
const firma = get(row, cells.firma) || personName;
|
||||
if (!firma) {
|
||||
summary.skippedEmpty++;
|
||||
continue;
|
||||
}
|
||||
const key = firma.toLowerCase();
|
||||
if (seen.has(key)) {
|
||||
summary.skippedDuplicate++;
|
||||
continue;
|
||||
}
|
||||
seen.add(key);
|
||||
|
||||
const standorte = [
|
||||
get(row, cells.strasse),
|
||||
[get(row, cells.plz), get(row, cells.ort)].filter(Boolean).join(' '),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
|
||||
await ctx.db.transaction(async (tx) => {
|
||||
const [createdLead] = await tx
|
||||
.insert(lead)
|
||||
.values({
|
||||
areaId,
|
||||
firma,
|
||||
status: 'cold',
|
||||
score: 0,
|
||||
projectId: input.projectId ?? null,
|
||||
branche: get(row, cells.branche) || null,
|
||||
website: get(row, cells.website) || null,
|
||||
quelle: get(row, cells.quelle) || null,
|
||||
standorte: standorte || null,
|
||||
createdBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
if (!createdLead) throw new Error('Lead konnte nicht angelegt werden.');
|
||||
summary.created++;
|
||||
|
||||
const email = get(row, cells.email);
|
||||
const telefon = get(row, cells.telefon);
|
||||
const mobil = get(row, cells.mobil);
|
||||
const position = get(row, cells.position);
|
||||
if (personName || email || telefon || mobil) {
|
||||
const tel = [telefon, mobil ? `Mobil: ${mobil}` : ''].filter(Boolean).join(' · ');
|
||||
await tx.insert(leadContact).values({
|
||||
leadId: createdLead.id,
|
||||
name: personName || firma,
|
||||
rolle: position || null,
|
||||
email: email || null,
|
||||
telefon: tel || null,
|
||||
isPrimary: true,
|
||||
order: 0,
|
||||
});
|
||||
summary.contacts++;
|
||||
}
|
||||
|
||||
const notizen = get(row, cells.notizen);
|
||||
if (notizen) {
|
||||
await tx.insert(leadTouchpoint).values({
|
||||
leadId: createdLead.id,
|
||||
datum: today,
|
||||
kanal: 'sonstiges',
|
||||
bearbeiterUserId: ctx.user.id,
|
||||
inhalt: notizen.slice(0, 2000),
|
||||
});
|
||||
summary.touchpoints++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return summary;
|
||||
}),
|
||||
});
|
||||
@@ -1,9 +1,23 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import { and, eq, desc } from 'drizzle-orm';
|
||||
import { project, milestone, area, user, type Project } from '@cockpit/db';
|
||||
import {
|
||||
project,
|
||||
milestone,
|
||||
area,
|
||||
user,
|
||||
projectStatus,
|
||||
phaseGate,
|
||||
type Project,
|
||||
} from '@cockpit/db';
|
||||
import { ProjectSchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { router, protectedProcedure, auditedProcedure } from '../trpc.js';
|
||||
|
||||
const PHASE_ORDER = ['definition', 'planung', 'umsetzung', 'abschluss'] as const;
|
||||
function nextPhase(p: (typeof PHASE_ORDER)[number]): (typeof PHASE_ORDER)[number] {
|
||||
const i = PHASE_ORDER.indexOf(p);
|
||||
return PHASE_ORDER[Math.min(i + 1, PHASE_ORDER.length - 1)]!;
|
||||
}
|
||||
|
||||
const byAreaInput = z.object({
|
||||
slug: z.string().min(1),
|
||||
@@ -65,9 +79,9 @@ export const projectRouter = router({
|
||||
areaId: input.areaId,
|
||||
name: input.name,
|
||||
description: input.description ?? null,
|
||||
logoUrl: input.logoUrl ?? null,
|
||||
kind: input.kind,
|
||||
verantwortlicheUserId: input.verantwortlicheUserId ?? null,
|
||||
arbeitsmodus: input.arbeitsmodus ?? null,
|
||||
outlineSteckbriefUrl: input.outlineSteckbriefUrl,
|
||||
planeProjectUrl: input.planeProjectUrl,
|
||||
risikolisteUrl: input.risikolisteUrl ?? null,
|
||||
@@ -102,7 +116,7 @@ export const projectRouter = router({
|
||||
return result;
|
||||
}),
|
||||
|
||||
archive: protectedProcedure
|
||||
archive: auditedProcedure('project.archive')
|
||||
.input(ProjectSchemas.archiveProjectInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const p = (
|
||||
@@ -120,7 +134,10 @@ export const projectRouter = router({
|
||||
.set({
|
||||
archiviert: true,
|
||||
archiviertAm: new Date(),
|
||||
phase: 'abschluss',
|
||||
lessonsLearnedUrl: input.lessonsLearnedUrl,
|
||||
abschlussvermerk: input.abschlussvermerk ?? p.abschlussvermerk,
|
||||
lessonsLearned: input.lessonsLearned ?? p.lessonsLearned,
|
||||
pflichtMinimumState: { ...p.pflichtMinimumState, retrospektive: true },
|
||||
})
|
||||
.where(eq(project.id, input.projectId))
|
||||
@@ -128,6 +145,95 @@ export const projectRouter = router({
|
||||
return updated as Project;
|
||||
}),
|
||||
|
||||
// Phase direkt setzen (Leitfaden Kap. 2).
|
||||
setPhase: auditedProcedure('project.setPhase')
|
||||
.input(ProjectSchemas.setPhaseInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [updated] = await ctx.db
|
||||
.update(project)
|
||||
.set({ phase: input.phase, updatedAt: new Date() })
|
||||
.where(eq(project.id, input.projectId))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// Gate-Review am Phasenende (Leitfaden Kap. 5), optional Folgephase freigeben.
|
||||
addPhaseGate: auditedProcedure('project.addPhaseGate')
|
||||
.input(ProjectSchemas.addPhaseGateInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [gate] = await ctx.db
|
||||
.insert(phaseGate)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
phase: input.phase,
|
||||
ergebnisErreicht: input.ergebnisErreicht,
|
||||
notiz: input.notiz ?? null,
|
||||
reviewedBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
if (input.advance) {
|
||||
await ctx.db
|
||||
.update(project)
|
||||
.set({ phase: nextPhase(input.phase), updatedAt: new Date() })
|
||||
.where(eq(project.id, input.projectId));
|
||||
}
|
||||
return gate;
|
||||
}),
|
||||
|
||||
phaseGates: protectedProcedure
|
||||
.input(ProjectSchemas.phaseGatesInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return ctx.db
|
||||
.select()
|
||||
.from(phaseGate)
|
||||
.where(eq(phaseGate.projectId, input.projectId))
|
||||
.orderBy(desc(phaseGate.reviewedAt));
|
||||
}),
|
||||
|
||||
// Statusbericht erfassen (Leitfaden Kap. 5) — speist statusCache + Pflicht-Minimum.
|
||||
addStatus: protectedProcedure
|
||||
.input(ProjectSchemas.addProjectStatusInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const p = (
|
||||
await ctx.db.select().from(project).where(eq(project.id, input.projectId)).limit(1)
|
||||
)[0];
|
||||
if (!p) throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
const [created] = await ctx.db
|
||||
.insert(projectStatus)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
ampel: input.ampel,
|
||||
trend: input.trend ?? null,
|
||||
text: input.text ?? null,
|
||||
externSichtbar: input.externSichtbar,
|
||||
createdBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
await ctx.db
|
||||
.update(project)
|
||||
.set({
|
||||
statusCache: input.ampel,
|
||||
trendCache: input.trend ?? null,
|
||||
pflichtMinimumState: { ...p.pflichtMinimumState, status_aktuell: true },
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(project.id, input.projectId));
|
||||
return created;
|
||||
}),
|
||||
|
||||
statusHistory: protectedProcedure
|
||||
.input(ProjectSchemas.projectStatusHistoryInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const rows = await ctx.db
|
||||
.select({ status: projectStatus, authorName: user.name })
|
||||
.from(projectStatus)
|
||||
.leftJoin(user, eq(user.id, projectStatus.createdBy))
|
||||
.where(eq(projectStatus.projectId, input.projectId))
|
||||
.orderBy(desc(projectStatus.createdAt));
|
||||
return rows.map((r) => ({ ...r.status, authorName: r.authorName }));
|
||||
}),
|
||||
|
||||
setMilestoneStatus: protectedProcedure
|
||||
.input(ProjectSchemas.setMilestoneStatusInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
@@ -139,6 +245,124 @@ export const projectRouter = router({
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// Projekt-Modus setzen (Leitfaden): muss jederzeit ans Team kommuniziert sein.
|
||||
setModus: protectedProcedure
|
||||
.input(ProjectSchemas.setModusInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [updated] = await ctx.db
|
||||
.update(project)
|
||||
.set({ modus: input.modus, updatedAt: new Date() })
|
||||
.where(eq(project.id, input.projectId))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// Maxime / Beschreibung / DoD bearbeiten (Ziel-Disziplin).
|
||||
update: protectedProcedure
|
||||
.input(ProjectSchemas.updateProjectInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { projectId, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (
|
||||
await ctx.db.select().from(project).where(eq(project.id, projectId)).limit(1)
|
||||
)[0];
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(project)
|
||||
.set({ ...patch, updatedAt: new Date() })
|
||||
.where(eq(project.id, projectId))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
addMilestone: protectedProcedure
|
||||
.input(ProjectSchemas.addMilestoneInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const existing = await ctx.db
|
||||
.select({ id: milestone.id })
|
||||
.from(milestone)
|
||||
.where(eq(milestone.projectId, input.projectId));
|
||||
const [created] = await ctx.db
|
||||
.insert(milestone)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
due: input.due ?? null,
|
||||
order: existing.length,
|
||||
})
|
||||
.returning();
|
||||
// Pflicht-Minimum-Punkt „Meilensteine" nachziehen (Leitfaden: mind. 2).
|
||||
const p = (
|
||||
await ctx.db.select().from(project).where(eq(project.id, input.projectId)).limit(1)
|
||||
)[0];
|
||||
if (p) {
|
||||
await ctx.db
|
||||
.update(project)
|
||||
.set({
|
||||
pflichtMinimumState: {
|
||||
...p.pflichtMinimumState,
|
||||
meilensteine: existing.length + 1 >= 2,
|
||||
},
|
||||
})
|
||||
.where(eq(project.id, input.projectId));
|
||||
}
|
||||
return created;
|
||||
}),
|
||||
|
||||
updateMilestone: protectedProcedure
|
||||
.input(ProjectSchemas.updateMilestoneInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { milestoneId, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (
|
||||
await ctx.db.select().from(milestone).where(eq(milestone.id, milestoneId)).limit(1)
|
||||
)[0];
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Meilenstein nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(milestone)
|
||||
.set(patch)
|
||||
.where(eq(milestone.id, milestoneId))
|
||||
.returning();
|
||||
if (!updated)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Meilenstein nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
removeMilestone: protectedProcedure
|
||||
.input(ProjectSchemas.removeMilestoneInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [removed] = await ctx.db
|
||||
.delete(milestone)
|
||||
.where(eq(milestone.id, input.milestoneId))
|
||||
.returning({ projectId: milestone.projectId });
|
||||
if (removed) {
|
||||
const rest = await ctx.db
|
||||
.select({ id: milestone.id })
|
||||
.from(milestone)
|
||||
.where(eq(milestone.projectId, removed.projectId));
|
||||
const p = (
|
||||
await ctx.db.select().from(project).where(eq(project.id, removed.projectId)).limit(1)
|
||||
)[0];
|
||||
if (p) {
|
||||
await ctx.db
|
||||
.update(project)
|
||||
.set({
|
||||
pflichtMinimumState: { ...p.pflichtMinimumState, meilensteine: rest.length >= 2 },
|
||||
})
|
||||
.where(eq(project.id, removed.projectId));
|
||||
}
|
||||
}
|
||||
return { ok: true as const };
|
||||
}),
|
||||
|
||||
listArchived: protectedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.db
|
||||
.select()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { desc, eq } from 'drizzle-orm';
|
||||
import { risk } from '@cockpit/db';
|
||||
import { RiskSchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
|
||||
export const riskRouter = router({
|
||||
forProject: protectedProcedure
|
||||
.input(RiskSchemas.riskForProjectInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return ctx.db
|
||||
.select()
|
||||
.from(risk)
|
||||
.where(eq(risk.projectId, input.projectId))
|
||||
.orderBy(desc(risk.showstopper), desc(risk.createdAt));
|
||||
}),
|
||||
|
||||
create: protectedProcedure.input(RiskSchemas.createRiskInput).mutation(async ({ ctx, input }) => {
|
||||
const [created] = await ctx.db
|
||||
.insert(risk)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
kind: input.kind,
|
||||
title: input.title,
|
||||
wahrscheinlichkeit: input.wahrscheinlichkeit,
|
||||
auswirkung: input.auswirkung,
|
||||
herkunft: input.herkunft ?? null,
|
||||
showstopper: input.showstopper,
|
||||
massnahme: input.massnahme ?? null,
|
||||
strategie: input.strategie ?? null,
|
||||
ownerUserId: input.ownerUserId ?? null,
|
||||
status: input.status,
|
||||
createdBy: ctx.user.id,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: protectedProcedure.input(RiskSchemas.updateRiskInput).mutation(async ({ ctx, input }) => {
|
||||
const { id, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (await ctx.db.select().from(risk).where(eq(risk.id, id)).limit(1))[0];
|
||||
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(risk)
|
||||
.set({ ...patch, updatedAt: new Date() })
|
||||
.where(eq(risk.id, id))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
remove: protectedProcedure.input(RiskSchemas.removeRiskInput).mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(risk).where(eq(risk.id, input.id));
|
||||
return { ok: true as const };
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from 'zod';
|
||||
import { and, ilike, isNull } from 'drizzle-orm';
|
||||
import { project, lead, blocker } from '@cockpit/db';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
|
||||
/**
|
||||
* Globale Schnellsuche über die wichtigsten Entitäten (Projekte, Leads, offene
|
||||
* Blocker). Postgres ILIKE — für die Teamgröße völlig ausreichend, kein FTS nötig.
|
||||
*/
|
||||
export const searchRouter = router({
|
||||
all: protectedProcedure
|
||||
.input(z.object({ q: z.string().min(1).max(100) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const term = `%${input.q.replace(/[%_]/g, '\\$&')}%`;
|
||||
const [projects, leads, blockers] = await Promise.all([
|
||||
ctx.db
|
||||
.select({ id: project.id, name: project.name, archiviert: project.archiviert })
|
||||
.from(project)
|
||||
.where(ilike(project.name, term))
|
||||
.limit(8),
|
||||
ctx.db
|
||||
.select({ id: lead.id, firma: lead.firma })
|
||||
.from(lead)
|
||||
.where(ilike(lead.firma, term))
|
||||
.limit(8),
|
||||
ctx.db
|
||||
.select({ id: blocker.id, title: blocker.title })
|
||||
.from(blocker)
|
||||
.where(and(ilike(blocker.title, term), isNull(blocker.resolvedAt)))
|
||||
.limit(8),
|
||||
]);
|
||||
return {
|
||||
projects: projects.map((p) => ({ id: p.id, label: p.name, archived: p.archiviert })),
|
||||
leads: leads.map((l) => ({ id: l.id, label: l.firma })),
|
||||
blockers: blockers.map((b) => ({ id: b.id, label: b.title })),
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { asc, eq, sql } from 'drizzle-orm';
|
||||
import { stakeholder } from '@cockpit/db';
|
||||
import { StakeholderSchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
|
||||
export const stakeholderRouter = router({
|
||||
forProject: protectedProcedure
|
||||
.input(StakeholderSchemas.stakeholderForProjectInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return ctx.db
|
||||
.select()
|
||||
.from(stakeholder)
|
||||
.where(eq(stakeholder.projectId, input.projectId))
|
||||
.orderBy(asc(stakeholder.order), asc(stakeholder.createdAt));
|
||||
}),
|
||||
|
||||
create: protectedProcedure
|
||||
.input(StakeholderSchemas.createStakeholderInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const count =
|
||||
(
|
||||
await ctx.db
|
||||
.select({ c: sql<number>`count(*)::int` })
|
||||
.from(stakeholder)
|
||||
.where(eq(stakeholder.projectId, input.projectId))
|
||||
)[0]?.c ?? 0;
|
||||
const [created] = await ctx.db
|
||||
.insert(stakeholder)
|
||||
.values({
|
||||
projectId: input.projectId,
|
||||
name: input.name,
|
||||
rolle: input.rolle ?? null,
|
||||
interesse: input.interesse,
|
||||
einfluss: input.einfluss,
|
||||
haltung: input.haltung,
|
||||
beduerfnis: input.beduerfnis ?? null,
|
||||
notiz: input.notiz ?? null,
|
||||
order: count,
|
||||
})
|
||||
.returning();
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: protectedProcedure
|
||||
.input(StakeholderSchemas.updateStakeholderInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...patch } = input;
|
||||
if (Object.keys(patch).length === 0) {
|
||||
const existing = (
|
||||
await ctx.db.select().from(stakeholder).where(eq(stakeholder.id, id)).limit(1)
|
||||
)[0];
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Stakeholder nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
.update(stakeholder)
|
||||
.set(patch)
|
||||
.where(eq(stakeholder.id, id))
|
||||
.returning();
|
||||
if (!updated)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Stakeholder nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
remove: protectedProcedure
|
||||
.input(StakeholderSchemas.removeStakeholderInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await ctx.db.delete(stakeholder).where(eq(stakeholder.id, input.id));
|
||||
return { ok: true as const };
|
||||
}),
|
||||
});
|
||||
+298
-75
@@ -1,39 +1,72 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import { and, eq, gte, isNull, lte, desc } from 'drizzle-orm';
|
||||
import { timeEntry, dayEntry, type TimeEntry } from '@cockpit/db';
|
||||
import { and, eq, isNull, asc, desc, sql, inArray } from 'drizzle-orm';
|
||||
import { timeEntry, dayEntry, todo, user, type TimeEntry, type Db } from '@cockpit/db';
|
||||
import { TimeEntrySchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import { todayIso } from '../lib/werktag.js';
|
||||
import { todayIso, berlinDayStartMs } from '../lib/werktag.js';
|
||||
|
||||
// Einträge, die „heute" betreffen: heute gestartet ODER heute beendet (über
|
||||
// Mitternacht gelaufen) ODER aktuell laufend. Gemeinsam für listToday/teamToday.
|
||||
function overlapsToday(today: string) {
|
||||
return sql`(
|
||||
(${timeEntry.startedAt} AT TIME ZONE 'Europe/Berlin')::date = ${today}
|
||||
OR (${timeEntry.endedAt} AT TIME ZONE 'Europe/Berlin')::date = ${today}
|
||||
OR ${timeEntry.endedAt} IS NULL
|
||||
)`;
|
||||
}
|
||||
|
||||
const idInput = z.object({ id: z.string().uuid() });
|
||||
|
||||
async function stopCurrent(
|
||||
tx: import('@cockpit/db').Db,
|
||||
userId: string,
|
||||
now: Date,
|
||||
): Promise<TimeEntry | null> {
|
||||
const active = (
|
||||
await tx
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(and(eq(timeEntry.userId, userId), isNull(timeEntry.endedAt)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
if (!active) return null;
|
||||
const durationSeconds = Math.max(0, Math.round((now.getTime() - active.startedAt.getTime()) / 1000));
|
||||
const [stopped] = await tx
|
||||
/**
|
||||
* Wall-Clock-Sekunden: Vereinigung überlappender Zeitintervalle. Parallel
|
||||
* laufende Einträge (mehrere Tasks gleichzeitig) zählen nur einmal — damit
|
||||
* „Gesamt heute" die tatsächlich anwesende Zeit zeigt, nicht die Summe.
|
||||
*/
|
||||
function unionSeconds(intervals: Array<readonly [number, number]>): number {
|
||||
const valid = intervals.filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0]);
|
||||
if (valid.length === 0) return 0;
|
||||
let total = 0;
|
||||
let curStart = valid[0]![0];
|
||||
let curEnd = valid[0]![1];
|
||||
for (let i = 1; i < valid.length; i++) {
|
||||
const [s, e] = valid[i]!;
|
||||
if (s <= curEnd) {
|
||||
if (e > curEnd) curEnd = e;
|
||||
} else {
|
||||
total += curEnd - curStart;
|
||||
curStart = s;
|
||||
curEnd = e;
|
||||
}
|
||||
}
|
||||
total += curEnd - curStart;
|
||||
return Math.round(total / 1000);
|
||||
}
|
||||
|
||||
async function stopOneEntry(db: Db, entry: TimeEntry, now: Date): Promise<TimeEntry | null> {
|
||||
const durationSeconds = Math.max(
|
||||
0,
|
||||
Math.round((now.getTime() - entry.startedAt.getTime()) / 1000),
|
||||
);
|
||||
const [stopped] = await db
|
||||
.update(timeEntry)
|
||||
.set({ endedAt: now, durationSeconds, updatedAt: now })
|
||||
.where(eq(timeEntry.id, active.id))
|
||||
.where(eq(timeEntry.id, entry.id))
|
||||
.returning();
|
||||
return stopped ?? null;
|
||||
}
|
||||
|
||||
async function findCurrentDayEntryId(
|
||||
db: import('@cockpit/db').Db,
|
||||
userId: string,
|
||||
): Promise<string | null> {
|
||||
// Stoppt ALLE laufenden Timer eines Users (mehrere parallele möglich).
|
||||
async function stopAllActive(db: Db, userId: string, now: Date): Promise<number> {
|
||||
const actives = await db
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(and(eq(timeEntry.userId, userId), isNull(timeEntry.endedAt)));
|
||||
for (const a of actives) await stopOneEntry(db, a, now);
|
||||
return actives.length;
|
||||
}
|
||||
|
||||
async function findCurrentDayEntryId(db: Db, userId: string): Promise<string | null> {
|
||||
const date = todayIso();
|
||||
const row = (
|
||||
await db
|
||||
@@ -47,30 +80,35 @@ async function findCurrentDayEntryId(
|
||||
|
||||
export const timeRouter = router({
|
||||
/**
|
||||
* Aktiver Eintrag (oder null) für den eingeloggten User.
|
||||
* Alle laufenden Timer des eingeloggten Users (mehrere parallel möglich).
|
||||
*/
|
||||
now: protectedProcedure.query(async ({ ctx }) => {
|
||||
const row = (
|
||||
await ctx.db
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(and(eq(timeEntry.userId, ctx.user.id), isNull(timeEntry.endedAt)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
return row ?? null;
|
||||
.orderBy(desc(timeEntry.startedAt));
|
||||
const todoIds = Array.from(new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)));
|
||||
const titles = new Map<string, string>();
|
||||
if (todoIds.length > 0) {
|
||||
const tr = await ctx.db
|
||||
.select({ id: todo.id, title: todo.title })
|
||||
.from(todo)
|
||||
.where(inArray(todo.id, todoIds));
|
||||
for (const t of tr) titles.set(t.id, t.title);
|
||||
}
|
||||
return rows.map((r) => ({ ...r, todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null }));
|
||||
}),
|
||||
|
||||
/**
|
||||
* Startet einen neuen Eintrag; stoppt automatisch einen evtl. laufenden.
|
||||
* Startet einen neuen Timer — parallel zu evtl. bereits laufenden (ENTWICKLUN-6).
|
||||
*/
|
||||
start: protectedProcedure
|
||||
.input(TimeEntrySchemas.startTimeEntryInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const now = new Date();
|
||||
const dayEntryId = await findCurrentDayEntryId(ctx.db, ctx.user.id);
|
||||
const result = await ctx.db.transaction(async (tx) => {
|
||||
await stopCurrent(tx, ctx.user.id, now);
|
||||
const [created] = await tx
|
||||
const [created] = await ctx.db
|
||||
.insert(timeEntry)
|
||||
.values({
|
||||
userId: ctx.user.id,
|
||||
@@ -83,20 +121,29 @@ export const timeRouter = router({
|
||||
.returning();
|
||||
if (!created) throw new Error('Time-Entry konnte nicht angelegt werden.');
|
||||
return created;
|
||||
});
|
||||
return result;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Stoppt den aktiven Eintrag.
|
||||
* Stoppt einen bestimmten laufenden Timer.
|
||||
*/
|
||||
stop: protectedProcedure.mutation(async ({ ctx }) => {
|
||||
const now = new Date();
|
||||
const stopped = await stopCurrent(ctx.db, ctx.user.id, now);
|
||||
if (!stopped) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Aktuell läuft kein Timer.' });
|
||||
stop: protectedProcedure.input(idInput).mutation(async ({ ctx, input }) => {
|
||||
const existing = (
|
||||
await ctx.db.select().from(timeEntry).where(eq(timeEntry.id, input.id)).limit(1)
|
||||
)[0];
|
||||
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
|
||||
if (existing.userId !== ctx.user.id) {
|
||||
throw new TRPCError({ code: 'FORBIDDEN', message: 'Nicht dein Eintrag.' });
|
||||
}
|
||||
return stopped;
|
||||
if (existing.endedAt) return existing;
|
||||
return stopOneEntry(ctx.db, existing, new Date());
|
||||
}),
|
||||
|
||||
/**
|
||||
* Stoppt alle laufenden Timer des Users.
|
||||
*/
|
||||
stopAll: protectedProcedure.mutation(async ({ ctx }) => {
|
||||
const stopped = await stopAllActive(ctx.db, ctx.user.id, new Date());
|
||||
return { stopped };
|
||||
}),
|
||||
|
||||
/**
|
||||
@@ -104,25 +151,65 @@ export const timeRouter = router({
|
||||
*/
|
||||
listToday: protectedProcedure.query(async ({ ctx }) => {
|
||||
const today = todayIso();
|
||||
const startOfDay = new Date(`${today}T00:00:00+02:00`);
|
||||
const startOfTomorrow = new Date(startOfDay.getTime() + 24 * 60 * 60 * 1000);
|
||||
const dayStart = berlinDayStartMs(today);
|
||||
const now = Date.now();
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(
|
||||
and(
|
||||
eq(timeEntry.userId, ctx.user.id),
|
||||
gte(timeEntry.startedAt, startOfDay),
|
||||
lte(timeEntry.startedAt, startOfTomorrow),
|
||||
),
|
||||
)
|
||||
.where(and(eq(timeEntry.userId, ctx.user.id), overlapsToday(today)))
|
||||
.orderBy(desc(timeEntry.startedAt));
|
||||
const totalSeconds = rows.reduce((acc, r) => {
|
||||
if (r.endedAt && r.durationSeconds) return acc + r.durationSeconds;
|
||||
if (!r.endedAt) return acc + Math.round((Date.now() - r.startedAt.getTime()) / 1000);
|
||||
return acc;
|
||||
}, 0);
|
||||
return { entries: rows, totalSeconds };
|
||||
|
||||
// ToDo-Titel tagesübergreifend auflösen (ToDo kann von gestern sein).
|
||||
const todoIds = Array.from(new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)));
|
||||
const titles = new Map<string, string>();
|
||||
if (todoIds.length > 0) {
|
||||
const tr = await ctx.db
|
||||
.select({ id: todo.id, title: todo.title })
|
||||
.from(todo)
|
||||
.where(inArray(todo.id, todoIds));
|
||||
for (const t of tr) titles.set(t.id, t.title);
|
||||
}
|
||||
|
||||
// Für die Tages-Summen nur den HEUTIGEN Anteil zählen (über Mitternacht
|
||||
// gelaufene Blöcke nicht doppelt/falsch zuschlagen).
|
||||
const clampStart = (r: TimeEntry) => Math.max(r.startedAt.getTime(), dayStart);
|
||||
const endMs = (r: TimeEntry) => (r.endedAt ? r.endedAt.getTime() : now);
|
||||
const totalSeconds = unionSeconds(rows.map((r) => [clampStart(r), endMs(r)] as const));
|
||||
const trackedSeconds = rows.reduce(
|
||||
(acc, r) => acc + Math.max(0, Math.round((endMs(r) - clampStart(r)) / 1000)),
|
||||
0,
|
||||
);
|
||||
|
||||
// Anwesenheits-Anker wie in teamToday: echter Lock-in, sonst (Auto-Tag vom
|
||||
// 6-Uhr-Schnitt oder kein Eintrag) der erste Zeiteintrag des Tages.
|
||||
const ownDay = (
|
||||
await ctx.db
|
||||
.select({
|
||||
checkedInAt: dayEntry.checkedInAt,
|
||||
checkedOutAt: dayEntry.checkedOutAt,
|
||||
autoCheckedIn: dayEntry.autoCheckedIn,
|
||||
})
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), eq(dayEntry.date, today)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
const firstStartMs = rows.length ? Math.min(...rows.map((r) => clampStart(r))) : null;
|
||||
const anchorMs =
|
||||
ownDay && !ownDay.autoCheckedIn && ownDay.checkedInAt
|
||||
? ownDay.checkedInAt.getTime()
|
||||
: firstStartMs;
|
||||
|
||||
const entries = rows.map((r) => ({
|
||||
...r,
|
||||
todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null,
|
||||
}));
|
||||
return {
|
||||
entries,
|
||||
totalSeconds,
|
||||
trackedSeconds,
|
||||
presenceStartedAt: anchorMs !== null ? new Date(anchorMs).toISOString() : null,
|
||||
presenceEndedAt: ownDay?.checkedOutAt ? ownDay.checkedOutAt.toISOString() : null,
|
||||
};
|
||||
}),
|
||||
|
||||
/**
|
||||
@@ -140,7 +227,11 @@ export const timeRouter = router({
|
||||
}
|
||||
const startedAt = input.startedAt ? new Date(input.startedAt) : existing.startedAt;
|
||||
const endedAt =
|
||||
input.endedAt === undefined ? existing.endedAt : input.endedAt === null ? null : new Date(input.endedAt);
|
||||
input.endedAt === undefined
|
||||
? existing.endedAt
|
||||
: input.endedAt === null
|
||||
? null
|
||||
: new Date(input.endedAt);
|
||||
const durationSeconds = endedAt
|
||||
? Math.max(0, Math.round((endedAt.getTime() - startedAt.getTime()) / 1000))
|
||||
: null;
|
||||
@@ -152,8 +243,7 @@ export const timeRouter = router({
|
||||
durationSeconds,
|
||||
todoId: input.todoId === undefined ? existing.todoId : input.todoId,
|
||||
category: input.category ?? existing.category,
|
||||
description:
|
||||
input.description === undefined ? existing.description : input.description,
|
||||
description: input.description === undefined ? existing.description : input.description,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(timeEntry.id, input.id))
|
||||
@@ -211,17 +301,13 @@ export const timeRouter = router({
|
||||
*/
|
||||
teamToday: protectedProcedure.query(async ({ ctx }) => {
|
||||
const today = todayIso();
|
||||
const startOfDay = new Date(`${today}T00:00:00+02:00`);
|
||||
const startOfTomorrow = new Date(startOfDay.getTime() + 24 * 60 * 60 * 1000);
|
||||
const { todo } = await import('@cockpit/db');
|
||||
const { inArray } = await import('drizzle-orm');
|
||||
const dayStart = berlinDayStartMs(today);
|
||||
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(
|
||||
and(gte(timeEntry.startedAt, startOfDay), lte(timeEntry.startedAt, startOfTomorrow)),
|
||||
);
|
||||
// Heute betroffen: heute gestartet/beendet oder laufend (auch über Mitternacht).
|
||||
.where(overlapsToday(today));
|
||||
|
||||
const todoIds = Array.from(
|
||||
new Set(rows.map((r) => r.todoId).filter((x): x is string => Boolean(x))),
|
||||
@@ -244,9 +330,10 @@ export const timeRouter = router({
|
||||
};
|
||||
type Bucket = {
|
||||
userId: string;
|
||||
totalSeconds: number;
|
||||
trackedSeconds: number; // Summe aller Task-Zeiten (Parallel-Tracking)
|
||||
byCategory: Record<string, number>;
|
||||
active: Active | null;
|
||||
intervals: Array<readonly [number, number]>;
|
||||
};
|
||||
|
||||
const now = Date.now();
|
||||
@@ -255,16 +342,18 @@ export const timeRouter = router({
|
||||
for (const r of rows) {
|
||||
const bucket: Bucket = perUser.get(r.userId) ?? {
|
||||
userId: r.userId,
|
||||
totalSeconds: 0,
|
||||
trackedSeconds: 0,
|
||||
byCategory: {},
|
||||
active: null,
|
||||
intervals: [],
|
||||
};
|
||||
const duration = r.endedAt
|
||||
? (r.durationSeconds ??
|
||||
Math.round((r.endedAt.getTime() - r.startedAt.getTime()) / 1000))
|
||||
: Math.round((now - r.startedAt.getTime()) / 1000);
|
||||
bucket.totalSeconds += duration;
|
||||
// Nur den heutigen Anteil zählen (über Mitternacht gelaufene Blöcke clampen).
|
||||
const startMs = Math.max(r.startedAt.getTime(), dayStart);
|
||||
const endMs = r.endedAt ? r.endedAt.getTime() : now;
|
||||
const duration = Math.max(0, Math.round((endMs - startMs) / 1000));
|
||||
bucket.trackedSeconds += duration;
|
||||
bucket.byCategory[r.category] = (bucket.byCategory[r.category] ?? 0) + duration;
|
||||
bucket.intervals.push([startMs, endMs]);
|
||||
if (!r.endedAt) {
|
||||
bucket.active = {
|
||||
startedAt: r.startedAt.toISOString(),
|
||||
@@ -277,6 +366,140 @@ export const timeRouter = router({
|
||||
perUser.set(r.userId, bucket);
|
||||
}
|
||||
|
||||
return Array.from(perUser.values());
|
||||
// Anwesenheit (Lock-in → Feierabend) pro Person — reine Anzeige neben dem
|
||||
// Tracking. Anker = echter Lock-in; bei vom 6-Uhr-Schnitt auto-angelegten
|
||||
// Tagen (Check-in 06:00 ist kein echter Lock-in) stattdessen der erste
|
||||
// Zeiteintrag des Tages.
|
||||
const dayRows = await ctx.db
|
||||
.select({
|
||||
userId: dayEntry.userId,
|
||||
checkedInAt: dayEntry.checkedInAt,
|
||||
checkedOutAt: dayEntry.checkedOutAt,
|
||||
autoCheckedIn: dayEntry.autoCheckedIn,
|
||||
})
|
||||
.from(dayEntry)
|
||||
.where(eq(dayEntry.date, today));
|
||||
const presenceByUser = new Map(dayRows.map((d) => [d.userId, d]));
|
||||
|
||||
// „Gesamt" pro Person = Wall-Clock (Vereinigung der Intervalle).
|
||||
return Array.from(perUser.values()).map((b) => {
|
||||
const p = presenceByUser.get(b.userId);
|
||||
const firstStartMs = b.intervals.length ? Math.min(...b.intervals.map((i) => i[0])) : null;
|
||||
const anchorMs =
|
||||
p && !p.autoCheckedIn && p.checkedInAt ? p.checkedInAt.getTime() : firstStartMs;
|
||||
return {
|
||||
userId: b.userId,
|
||||
totalSeconds: unionSeconds(b.intervals),
|
||||
trackedSeconds: b.trackedSeconds,
|
||||
byCategory: b.byCategory,
|
||||
active: b.active,
|
||||
presenceStartedAt: anchorMs !== null ? new Date(anchorMs).toISOString() : null,
|
||||
presenceEndedAt: p?.checkedOutAt ? p.checkedOutAt.toISOString() : null,
|
||||
};
|
||||
});
|
||||
}),
|
||||
|
||||
/**
|
||||
* Team-Timeline: alle Zeit-Einträge eines Tages, pro Person eine Spur.
|
||||
* Liefert Rohdaten (Start/Ende/Kategorie/Label); Achse & parallele Stränge
|
||||
* (überlappende Blöcke) rendert das Frontend.
|
||||
*/
|
||||
teamTimeline: protectedProcedure
|
||||
.input(TimeEntrySchemas.teamTimelineInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const today = todayIso();
|
||||
const date = input.date ?? today;
|
||||
const isToday = date === today;
|
||||
const onDate = (col: typeof timeEntry.startedAt | typeof timeEntry.endedAt) =>
|
||||
sql`(${col} AT TIME ZONE 'Europe/Berlin')::date = ${date}`;
|
||||
const cond = isToday
|
||||
? sql`(${onDate(timeEntry.startedAt)} OR ${onDate(timeEntry.endedAt)} OR ${timeEntry.endedAt} IS NULL)`
|
||||
: sql`(${onDate(timeEntry.startedAt)} OR ${onDate(timeEntry.endedAt)})`;
|
||||
|
||||
const rows = await ctx.db
|
||||
.select()
|
||||
.from(timeEntry)
|
||||
.where(cond)
|
||||
.orderBy(asc(timeEntry.startedAt));
|
||||
|
||||
const todoIds = Array.from(
|
||||
new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)),
|
||||
);
|
||||
const titles = new Map<string, string>();
|
||||
if (todoIds.length > 0) {
|
||||
const tr = await ctx.db
|
||||
.select({ id: todo.id, title: todo.title })
|
||||
.from(todo)
|
||||
.where(inArray(todo.id, todoIds));
|
||||
for (const t of tr) titles.set(t.id, t.title);
|
||||
}
|
||||
|
||||
const userRows = await ctx.db
|
||||
.select({ id: user.id, name: user.name })
|
||||
.from(user)
|
||||
.where(eq(user.active, true));
|
||||
const nameById = new Map(userRows.map((u) => [u.id, u.name]));
|
||||
|
||||
type Entry = {
|
||||
id: string;
|
||||
start: string;
|
||||
end: string | null;
|
||||
category: string;
|
||||
description: string | null;
|
||||
todoTitle: string | null;
|
||||
};
|
||||
const byUser = new Map<string, Entry[]>();
|
||||
for (const r of rows) {
|
||||
const arr = byUser.get(r.userId) ?? [];
|
||||
arr.push({
|
||||
id: r.id,
|
||||
start: r.startedAt.toISOString(),
|
||||
end: r.endedAt ? r.endedAt.toISOString() : null,
|
||||
category: r.category,
|
||||
description: r.description,
|
||||
todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null,
|
||||
});
|
||||
byUser.set(r.userId, arr);
|
||||
}
|
||||
|
||||
const lanes = Array.from(byUser.entries())
|
||||
.map(([userId, entries]) => ({ userId, name: nameById.get(userId) ?? '—', entries }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return { date, lanes };
|
||||
}),
|
||||
|
||||
/**
|
||||
* Getrackte Zeit auf ein Projekt (time_entry mit bezugKind='project'):
|
||||
* Gesamtsumme + Aufschlüsselung pro Person. bezugId wurde bislang erfasst,
|
||||
* aber nirgends ausgewertet — das speist die „Getrackte Zeit"-Sektion im
|
||||
* Projekt-Detail.
|
||||
*/
|
||||
byProject: protectedProcedure
|
||||
.input(z.object({ projectId: z.string().uuid() }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
const rows = await ctx.db
|
||||
.select({
|
||||
userId: timeEntry.userId,
|
||||
seconds: sql<number>`COALESCE(SUM(${timeEntry.durationSeconds}), 0)`,
|
||||
})
|
||||
.from(timeEntry)
|
||||
.where(and(eq(timeEntry.bezugKind, 'project'), eq(timeEntry.bezugId, input.projectId)))
|
||||
.groupBy(timeEntry.userId);
|
||||
|
||||
const userRows = await ctx.db.select({ id: user.id, name: user.name }).from(user);
|
||||
const nameById = new Map(userRows.map((u) => [u.id, u.name]));
|
||||
|
||||
const perUser = rows
|
||||
.map((r) => ({
|
||||
userId: r.userId,
|
||||
name: nameById.get(r.userId) ?? '—',
|
||||
seconds: Number(r.seconds),
|
||||
}))
|
||||
.filter((r) => r.seconds > 0)
|
||||
.sort((a, b) => b.seconds - a.seconds);
|
||||
const totalSeconds = perUser.reduce((sum, r) => sum + r.seconds, 0);
|
||||
|
||||
return { totalSeconds, perUser };
|
||||
}),
|
||||
});
|
||||
@@ -1,23 +1,20 @@
|
||||
import { and, eq, gte, lte } from 'drizzle-orm';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { user, dayEntry, absenceDay } from '@cockpit/db';
|
||||
import type { Db } from '@cockpit/db';
|
||||
import { DayEntrySchemas } from '@cockpit/shared';
|
||||
import { router, protectedProcedure } from '../trpc.js';
|
||||
import {
|
||||
todayIso,
|
||||
isWerktag,
|
||||
previousWerktag,
|
||||
parseIsoDate,
|
||||
formatIsoDate,
|
||||
} from '../lib/werktag.js';
|
||||
import { todayIso, isWerktag, parseIsoDate, formatIsoDate } from '../lib/werktag.js';
|
||||
import { countStreakDays } from '../lib/streak.js';
|
||||
|
||||
async function computeStreak(db: import('@cockpit/db').Db, userId: string): Promise<number> {
|
||||
async function computeStreak(db: Db, userId: string): Promise<number> {
|
||||
const today = todayIso();
|
||||
|
||||
// Hole alle relevanten DayEntries und Abwesenheiten der letzten 90 Tage.
|
||||
// DayEntries + Abwesenheiten der letzten 400 Tage (deckt > 1 Jahr Werktage ab,
|
||||
// damit lange Streaks nicht am Lookback-Fenster abgeschnitten werden).
|
||||
const endIso = today;
|
||||
const start = parseIsoDate(today);
|
||||
start.setUTCDate(start.getUTCDate() - 120);
|
||||
start.setUTCDate(start.getUTCDate() - 400);
|
||||
const startIso = formatIsoDate(start);
|
||||
|
||||
const [entries, absences] = await Promise.all([
|
||||
@@ -39,31 +36,11 @@ async function computeStreak(db: import('@cockpit/db').Db, userId: string): Prom
|
||||
),
|
||||
]);
|
||||
|
||||
const fullByDate = new Map<string, boolean>();
|
||||
for (const e of entries) fullByDate.set(e.date, e.status === 'full');
|
||||
const absSet = new Set(absences.map((a) => a.date));
|
||||
const fullDates = new Set<string>();
|
||||
for (const e of entries) if (e.status === 'full') fullDates.add(e.date);
|
||||
const absenceDates = new Set(absences.map((a) => a.date));
|
||||
|
||||
// Zähle aufeinanderfolgende volle Werktage rückwärts ab heute.
|
||||
let cursor = today;
|
||||
let streak = 0;
|
||||
// Wenn heute noch nicht voll: starten beim vorherigen Werktag.
|
||||
if (!fullByDate.get(today)) {
|
||||
cursor = previousWerktag(today);
|
||||
}
|
||||
while (true) {
|
||||
if (!isWerktag(cursor)) break;
|
||||
if (absSet.has(cursor)) {
|
||||
cursor = previousWerktag(cursor);
|
||||
continue;
|
||||
}
|
||||
if (fullByDate.get(cursor)) {
|
||||
streak++;
|
||||
cursor = previousWerktag(cursor);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return streak;
|
||||
return countStreakDays({ today, fullDates, absenceDates });
|
||||
}
|
||||
|
||||
export const userRouter = router({
|
||||
@@ -95,7 +72,6 @@ export const userRouter = router({
|
||||
let cursor = input.from;
|
||||
const toInsert: { userId: string; date: string; reason: 'urlaub' | 'krank' | 'sonstiges' }[] =
|
||||
[];
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
while (cursor <= input.to) {
|
||||
if (isWerktag(cursor)) {
|
||||
toInsert.push({ userId: ctx.user.id, date: cursor, reason: input.reason });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Fastify from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import { fastifyTRPCPlugin, type FastifyTRPCPluginOptions } from '@trpc/server/adapters/fastify';
|
||||
import { runMigrations, ensureBaseAreas } from '@cockpit/db';
|
||||
import { loadEnv } from './env.js';
|
||||
import { logger } from './lib/logger.js';
|
||||
import { registerAuthMiddleware } from './auth/middleware.js';
|
||||
@@ -12,6 +13,26 @@ import { createContext } from './trpc.js';
|
||||
|
||||
async function main() {
|
||||
const env = loadEnv();
|
||||
|
||||
// Schema-Migrationen vor dem Start anwenden (idempotent). Schlägt eine
|
||||
// Migration fehl, startet der Server nicht — besser als mit veraltetem Schema.
|
||||
try {
|
||||
await runMigrations(env.DATABASE_URL);
|
||||
logger.info('db migrations applied');
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'db migration failed');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Basis-Bereiche sicherstellen (idempotent), damit der „Neues Projekt"-
|
||||
// Bereich-Dropdown auch auf einer nicht geseedeten Prod-DB nie leer ist.
|
||||
try {
|
||||
await ensureBaseAreas(env.DATABASE_URL);
|
||||
logger.info('base areas ensured');
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'ensure base areas failed');
|
||||
}
|
||||
|
||||
const app = Fastify({
|
||||
logger: {
|
||||
level: env.LOG_LEVEL,
|
||||
|
||||
+23
-18
@@ -3,8 +3,9 @@
|
||||
import './types.js';
|
||||
import { initTRPC, TRPCError } from '@trpc/server';
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { User } from '@cockpit/db';
|
||||
import { auditEvent, type User } from '@cockpit/db';
|
||||
import { getDb } from './db.js';
|
||||
import { logger } from './lib/logger.js';
|
||||
|
||||
export interface Context {
|
||||
user: User | null;
|
||||
@@ -45,25 +46,29 @@ export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
|
||||
return next({ ctx: { ...ctx, user: ctx.user } });
|
||||
});
|
||||
|
||||
// Audit-Wrapper: schreibt nach erfolgreicher Mutation einen audit_event.
|
||||
// Genutzt als zusätzliche Middleware auf Mutations.
|
||||
export function withAudit<TInput, TResult extends Record<string, unknown> | unknown>(
|
||||
action: string,
|
||||
) {
|
||||
return async function audit(opts: {
|
||||
ctx: Context;
|
||||
input: TInput;
|
||||
next: () => Promise<{ ok: true; data: TResult } | TResult>;
|
||||
}) {
|
||||
const result = await opts.next();
|
||||
if (!opts.ctx.user) return result;
|
||||
const { auditEvent } = await import('@cockpit/db');
|
||||
await opts.ctx.db.insert(auditEvent).values({
|
||||
actorUserId: opts.ctx.user.id,
|
||||
/**
|
||||
* Auditierte Procedure: wie `protectedProcedure`, schreibt aber nach erfolgreicher
|
||||
* Ausführung einen `audit_event`. Nutzung:
|
||||
* auditedProcedure('blocker.resolve').input(schema).mutation(...)
|
||||
* Das Audit ist best-effort — ein Fehler beim Schreiben darf die eigentliche
|
||||
* Mutation nicht scheitern lassen.
|
||||
*/
|
||||
export function auditedProcedure(action: string) {
|
||||
return protectedProcedure.use(async ({ ctx, next, getRawInput }) => {
|
||||
const result = await next();
|
||||
if (result.ok) {
|
||||
try {
|
||||
const rawInput = await getRawInput();
|
||||
await ctx.db.insert(auditEvent).values({
|
||||
actorUserId: ctx.user.id,
|
||||
action,
|
||||
entityKind: action.split('.')[0] ?? 'unknown',
|
||||
payload: { input: opts.input as unknown },
|
||||
payload: { input: (rawInput ?? null) as unknown },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn({ err, action }, 'audit_event konnte nicht geschrieben werden');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Caddy-Config für das statische Web-Image (cockpit-web).
|
||||
# Liefert die gebaute SPA aus /srv mit SPA-Fallback auf index.html.
|
||||
# /api und /trpc werden in Produktion bereits von Traefik (höhere Priorität)
|
||||
# an cockpit-api geroutet und erreichen diesen Container nicht.
|
||||
:80 {
|
||||
root * /srv
|
||||
encode zstd gzip
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
}
|
||||
+3
-1
@@ -19,6 +19,8 @@ COPY packages/shared ./packages/shared
|
||||
|
||||
RUN pnpm --filter web build
|
||||
|
||||
# --- runtime (static via Caddy in production compose) ---
|
||||
# --- runtime (static via Caddy) ---
|
||||
FROM caddy:2-alpine AS runtime
|
||||
# Eigene Caddy-Config statt der Default-Welcome-Seite: SPA aus /srv ausliefern.
|
||||
COPY apps/web/Caddyfile /etc/caddy/Caddyfile
|
||||
COPY --from=builder /repo/apps/web/dist /srv
|
||||
@@ -1,12 +1,15 @@
|
||||
import { Toaster } from 'sonner';
|
||||
import { TrpcProvider } from './lib/trpc-provider';
|
||||
import { Router } from './lib/router';
|
||||
import { ConfirmProvider } from './components/ui/ConfirmProvider';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<TrpcProvider>
|
||||
<ConfirmProvider>
|
||||
<Router />
|
||||
<Toaster position="bottom-right" richColors={false} />
|
||||
</ConfirmProvider>
|
||||
</TrpcProvider>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { toast } from 'sonner';
|
||||
import { trpc } from '../../lib/trpc';
|
||||
import { voice } from '../../lib/voice';
|
||||
import { Button } from '../ui/Button';
|
||||
import { Modal } from '../ui/Modal';
|
||||
|
||||
export function BlockerDialog({ onClose }: { onClose: () => void }) {
|
||||
const [title, setTitle] = useState('');
|
||||
@@ -23,15 +24,7 @@ export function BlockerDialog({ onClose }: { onClose: () => void }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/30"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-[var(--radius-xl)] bg-[var(--color-bg)] p-6 shadow-[var(--shadow-lg)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2 className="text-xl font-semibold">Neuer Blocker</h2>
|
||||
<Modal open onClose={onClose} title="Neuer Blocker">
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Was klemmt?</span>
|
||||
@@ -65,7 +58,6 @@ export function BlockerDialog({ onClose }: { onClose: () => void }) {
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -3,14 +3,18 @@ import { useEffect, useState } from 'react';
|
||||
import { TopNav } from './TopNav';
|
||||
import { useCurrentUser } from '../../hooks/useCurrentUser';
|
||||
import { BlockerDialog } from '../blocker/BlockerDialog';
|
||||
import { CommandPalette } from '../search/CommandPalette';
|
||||
|
||||
const SHORTCUT_MAP: Record<string, string> = {
|
||||
p: '/dashboard',
|
||||
h: '/heute',
|
||||
w: '/meine-woche',
|
||||
b: '/bereich',
|
||||
e: '/bereich/entwicklung',
|
||||
v: '/bereich/vertrieb',
|
||||
m: '/bereich/marketing',
|
||||
t: '/team',
|
||||
i: '/historie',
|
||||
a: '/archiv',
|
||||
};
|
||||
|
||||
@@ -18,6 +22,7 @@ export function AppShell() {
|
||||
const me = useCurrentUser();
|
||||
const navigate = useNavigate();
|
||||
const [blockerOpen, setBlockerOpen] = useState(false);
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
|
||||
// Dev-Mode: bei fehlender Session sofort in den Auto-Login. Auf prod hingegen
|
||||
// zeigen wir die Login-Aufforderung mit dem Authentik-Link.
|
||||
@@ -47,6 +52,12 @@ export function AppShell() {
|
||||
}
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
// Cmd/Ctrl+K öffnet die Suche — auch aus Eingabefeldern heraus.
|
||||
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
|
||||
e.preventDefault();
|
||||
setSearchOpen(true);
|
||||
return;
|
||||
}
|
||||
const target = e.target as HTMLElement | null;
|
||||
if (
|
||||
target &&
|
||||
@@ -54,6 +65,11 @@ export function AppShell() {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (e.key === '/') {
|
||||
e.preventDefault();
|
||||
setSearchOpen(true);
|
||||
return;
|
||||
}
|
||||
if (e.key === '?' && !waitingForSecond) {
|
||||
// eslint-disable-next-line no-alert
|
||||
alert(
|
||||
@@ -94,6 +110,7 @@ export function AppShell() {
|
||||
{me ? <Outlet /> : <NotLoggedInHint />}
|
||||
</main>
|
||||
{blockerOpen && <BlockerDialog onClose={() => setBlockerOpen(false)} />}
|
||||
<CommandPalette open={searchOpen} onClose={() => setSearchOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ const TABS = [
|
||||
{ to: '/dashboard', label: 'Dashboard', shortcut: 'g d', matchPrefix: '/dashboard' },
|
||||
{ to: '/bereich', label: 'Bereich', shortcut: 'g b', matchPrefix: '/bereich' },
|
||||
{ to: '/heute', label: 'Heute', shortcut: 'g h', matchPrefix: '/heute' },
|
||||
{ to: '/meine-woche', label: 'Woche', shortcut: 'g w', matchPrefix: '/meine-woche' },
|
||||
{ to: '/team', label: 'Team', shortcut: 'g t', matchPrefix: '/team' },
|
||||
{ to: '/historie', label: 'Historie', shortcut: 'g i', matchPrefix: '/historie' },
|
||||
{ to: '/archiv', label: 'Archiv', shortcut: 'g a', matchPrefix: '/archiv' },
|
||||
] as const;
|
||||
|
||||
@@ -35,7 +38,10 @@ export function TopNav() {
|
||||
className="mx-auto flex h-14 max-w-[1280px] items-center gap-2 px-6"
|
||||
aria-label="Hauptnavigation"
|
||||
>
|
||||
<NavLink to="/dashboard" className="flex items-center gap-1.5 font-bold text-[var(--color-ink)]">
|
||||
<NavLink
|
||||
to="/dashboard"
|
||||
className="flex items-center gap-1.5 font-bold text-[var(--color-ink)]"
|
||||
>
|
||||
<span>{voice.appName}</span>
|
||||
<ToolCtrlLogo size={18} />
|
||||
</NavLink>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { Upload, X } from 'lucide-react';
|
||||
|
||||
// Datei → zentriert quadratisch zugeschnittene, auf `size` verkleinerte WebP-Data-URL.
|
||||
async function fileToSquareDataUrl(file: File, size = 256): Promise<string> {
|
||||
const dataUrl = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(new Error('Datei konnte nicht gelesen werden.'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const i = new Image();
|
||||
i.onload = () => resolve(i);
|
||||
i.onerror = () => reject(new Error('Bild konnte nicht geladen werden.'));
|
||||
i.src = dataUrl;
|
||||
});
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = size;
|
||||
canvas.height = size;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('Canvas nicht verfügbar.');
|
||||
// Center-Crop (cover): kürzere Kante bestimmt das Quadrat.
|
||||
const s = Math.min(img.width, img.height);
|
||||
const sx = (img.width - s) / 2;
|
||||
const sy = (img.height - s) / 2;
|
||||
ctx.drawImage(img, sx, sy, s, s, 0, 0, size, size);
|
||||
return canvas.toDataURL('image/webp', 0.85);
|
||||
}
|
||||
|
||||
export function ProjectLogo({
|
||||
url,
|
||||
name,
|
||||
size = 40,
|
||||
className,
|
||||
}: {
|
||||
url: string | null | undefined;
|
||||
name: string;
|
||||
size?: number;
|
||||
className?: string;
|
||||
}) {
|
||||
if (url) {
|
||||
return (
|
||||
<img
|
||||
src={url}
|
||||
alt=""
|
||||
className={clsx('shrink-0 rounded-[var(--radius-md)] object-cover', className)}
|
||||
style={{ width: size, height: size }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const initials = name.trim().slice(0, 2).toUpperCase() || '–';
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'flex shrink-0 items-center justify-center rounded-[var(--radius-md)] bg-black/5 font-semibold text-[var(--color-ink-muted)]',
|
||||
className,
|
||||
)}
|
||||
style={{ width: size, height: size, fontSize: Math.round(size * 0.34) }}
|
||||
aria-hidden
|
||||
>
|
||||
{initials}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LogoUpload({
|
||||
value,
|
||||
name,
|
||||
onChange,
|
||||
className,
|
||||
}: {
|
||||
value: string | null;
|
||||
name: string;
|
||||
onChange: (v: string | null) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function handleFile(file: File | undefined) {
|
||||
if (!file) return;
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
onChange(await fileToSquareDataUrl(file));
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Upload fehlgeschlagen.');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
if (inputRef.current) inputRef.current.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={clsx('flex items-center gap-3', className)}>
|
||||
<ProjectLogo url={value} name={name} size={56} />
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={busy}
|
||||
className="inline-flex items-center gap-1 rounded-[var(--radius-md)] border border-[var(--color-border)] px-2.5 py-1 text-xs hover:border-[var(--color-ink)] disabled:opacity-50"
|
||||
>
|
||||
<Upload size={13} /> {busy ? 'Lädt…' : value ? 'Ändern' : 'Logo hochladen'}
|
||||
</button>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(null)}
|
||||
className="inline-flex items-center gap-1 text-xs text-[var(--color-ink-muted)] hover:text-[var(--color-ampel-red-fg)]"
|
||||
>
|
||||
<X size={13} /> Entfernen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{error ? (
|
||||
<span className="text-xs text-[var(--color-ampel-red-fg)]">{error}</span>
|
||||
) : (
|
||||
<span className="text-xs text-[var(--color-ink-faint)]">
|
||||
Quadratisch, wird auf 256px verkleinert.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={(e) => handleFile(e.target.files?.[0])}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { trpc } from '../../lib/trpc';
|
||||
import { Modal } from '../ui/Modal';
|
||||
|
||||
/**
|
||||
* Globale Schnellsuche (Cmd/Ctrl+K oder „/"). Tippen sucht debounced über
|
||||
* Projekte, Leads und offene Blocker; Klick springt zum Ziel.
|
||||
*/
|
||||
export function CommandPalette({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const navigate = useNavigate();
|
||||
const [q, setQ] = useState('');
|
||||
const [debounced, setDebounced] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(q.trim()), 200);
|
||||
return () => clearTimeout(t);
|
||||
}, [q]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setQ('');
|
||||
setDebounced('');
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const results = trpc.search.all.useQuery(
|
||||
{ q: debounced },
|
||||
{ enabled: open && debounced.length >= 1 },
|
||||
);
|
||||
const data = results.data;
|
||||
const empty =
|
||||
!!data && data.projects.length === 0 && data.leads.length === 0 && data.blockers.length === 0;
|
||||
|
||||
function go(path: string) {
|
||||
onClose();
|
||||
navigate(path);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Suche">
|
||||
<input
|
||||
type="text"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Projekt, Lead oder Blocker …"
|
||||
className="mt-2 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<div className="mt-3 max-h-80 space-y-3 overflow-y-auto text-sm">
|
||||
{debounced.length >= 1 && empty && results.isFetched && (
|
||||
<p className="text-[var(--color-ink-muted)]">Nichts gefunden.</p>
|
||||
)}
|
||||
{data && data.projects.length > 0 && (
|
||||
<Group title="Projekte">
|
||||
{data.projects.map((p) => (
|
||||
<ResultItem
|
||||
key={p.id}
|
||||
label={p.archived ? `${p.label} (archiviert)` : p.label}
|
||||
onClick={() => go(`/projekt/${p.id}`)}
|
||||
/>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
{data && data.leads.length > 0 && (
|
||||
<Group title="Leads">
|
||||
{data.leads.map((l) => (
|
||||
<ResultItem key={l.id} label={l.label} onClick={() => go(`/lead/${l.id}`)} />
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
{data && data.blockers.length > 0 && (
|
||||
<Group title="Offene Blocker">
|
||||
{data.blockers.map((b) => (
|
||||
<ResultItem key={b.id} label={b.label} onClick={() => go('/dashboard')} />
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function Group({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<p className="mb-1 text-xs font-medium uppercase tracking-wide text-[var(--color-ink-faint)]">
|
||||
{title}
|
||||
</p>
|
||||
<ul className="space-y-0.5">{children}</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResultItem({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="w-full truncate rounded-[var(--radius-sm)] px-2 py-1.5 text-left hover:bg-black/5"
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,16 @@ function initials(name: string) {
|
||||
.join('');
|
||||
}
|
||||
|
||||
/** Anwesenheit (Lock-in → Feierabend bzw. jetzt) — reine Anzeige, kein Tracking. */
|
||||
function presenceSecondsOf(it: {
|
||||
presenceStartedAt: string | null;
|
||||
presenceEndedAt: string | null;
|
||||
}): number | null {
|
||||
if (!it.presenceStartedAt) return null;
|
||||
const endMs = it.presenceEndedAt ? new Date(it.presenceEndedAt).getTime() : Date.now();
|
||||
return Math.max(0, Math.round((endMs - new Date(it.presenceStartedAt).getTime()) / 1000));
|
||||
}
|
||||
|
||||
export function TeamTimeSection() {
|
||||
const team = trpc.time.teamToday.useQuery(undefined, { refetchInterval: 30_000 });
|
||||
const users = trpc.user.list.useQuery();
|
||||
@@ -79,13 +89,32 @@ export function TeamTimeSection() {
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
Gesamt:{' '}
|
||||
<span className="font-mono">{formatDurationCompact(it.totalSeconds)}</span>
|
||||
{it.trackedSeconds > it.totalSeconds + 60 && (
|
||||
<span
|
||||
className="text-[var(--color-ink-faint)]"
|
||||
title="Über parallele Aufgaben getrackte Summe (zählt überlappende Zeit mehrfach)."
|
||||
>
|
||||
{' · getrackt '}
|
||||
<span className="font-mono">
|
||||
{formatDurationCompact(it.trackedSeconds)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{presenceSecondsOf(it) !== null && (
|
||||
<span title="Anwesenheit: ab Lock-in (bzw. erstem Zeiteintrag des Tages) bis Feierabend bzw. jetzt — unabhängig vom Tracking.">
|
||||
{' · Anwesend: '}
|
||||
<span className="font-mono">
|
||||
{formatDurationCompact(presenceSecondsOf(it)!)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{it.active ? <ActiveLine active={it.active} /> : <IdleLine />}
|
||||
|
||||
<Breakdown byCategory={it.byCategory} total={it.totalSeconds} />
|
||||
<Breakdown byCategory={it.byCategory} total={it.trackedSeconds} />
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
))}
|
||||
@@ -122,18 +151,10 @@ function ActiveLine({
|
||||
}
|
||||
|
||||
function IdleLine() {
|
||||
return (
|
||||
<p className="mt-3 text-xs text-[var(--color-ink-faint)]">Aktuell kein Timer.</p>
|
||||
);
|
||||
return <p className="mt-3 text-xs text-[var(--color-ink-faint)]">Aktuell kein Timer.</p>;
|
||||
}
|
||||
|
||||
function Breakdown({
|
||||
byCategory,
|
||||
total,
|
||||
}: {
|
||||
byCategory: Record<string, number>;
|
||||
total: number;
|
||||
}) {
|
||||
function Breakdown({ byCategory, total }: { byCategory: Record<string, number>; total: number }) {
|
||||
if (total === 0) return null;
|
||||
const ordered = TIME_CATEGORIES.map((c) => ({
|
||||
key: c.value,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useState } from 'react';
|
||||
import { Pencil, Trash2, Plus, X } from 'lucide-react';
|
||||
import { Pencil, Trash2, Plus } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { clsx } from 'clsx';
|
||||
import { trpc } from '../../lib/trpc';
|
||||
import { Card } from '../ui/Card';
|
||||
import { Button } from '../ui/Button';
|
||||
import { Modal } from '../ui/Modal';
|
||||
import { formatDuration, formatDurationCompact } from '../../lib/format-duration';
|
||||
import { usePresenceSeconds } from '../../lib/use-presence-seconds';
|
||||
import { TIME_CATEGORIES, type TimeCategory } from '../../lib/time-categories';
|
||||
|
||||
const CATEGORY_LABEL: Record<string, string> = Object.fromEntries(
|
||||
@@ -29,9 +31,23 @@ export function TimelineSection() {
|
||||
const todayQuery = trpc.dayEntry.today.useQuery();
|
||||
const [manualOpen, setManualOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<string | null>(null);
|
||||
// Anwesenheits-Anker: echter Lock-in; bei Auto-Tagen (6-Uhr-Schnitt) liefert
|
||||
// listToday den ersten Zeiteintrag des Tages als Fallback.
|
||||
const todayEntry = todayQuery.data?.entry;
|
||||
const presenceFrom =
|
||||
todayEntry && !todayEntry.autoCheckedIn && todayEntry.checkedInAt
|
||||
? todayEntry.checkedInAt
|
||||
: (listQuery.data?.presenceStartedAt ?? null);
|
||||
const presenceSeconds = usePresenceSeconds(
|
||||
presenceFrom,
|
||||
todayEntry?.checkedOutAt ?? listQuery.data?.presenceEndedAt ?? null,
|
||||
);
|
||||
|
||||
if (listQuery.isPending) return null;
|
||||
const entries = listQuery.data?.entries ?? [];
|
||||
// Aufsteigend sortieren: Vormittag oben, Abend unten.
|
||||
const entries = [...(listQuery.data?.entries ?? [])].sort(
|
||||
(a, b) => new Date(a.startedAt).getTime() - new Date(b.startedAt).getTime(),
|
||||
);
|
||||
const totalSeconds = listQuery.data?.totalSeconds ?? 0;
|
||||
const todoTitles = new Map((todayQuery.data?.todos ?? []).map((t) => [t.id, t.title]));
|
||||
|
||||
@@ -41,7 +57,13 @@ export function TimelineSection() {
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Zeit heute</h2>
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
Gesamt: <span className="font-mono">{formatDurationCompact(totalSeconds)}</span>
|
||||
Getrackt: <span className="font-mono">{formatDurationCompact(totalSeconds)}</span>
|
||||
{presenceSeconds !== null && (
|
||||
<>
|
||||
{' · '}Anwesend:{' '}
|
||||
<span className="font-mono">{formatDurationCompact(presenceSeconds)}</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" onClick={() => setManualOpen(true)}>
|
||||
@@ -64,7 +86,7 @@ export function TimelineSection() {
|
||||
<TimelineRow
|
||||
key={e.id}
|
||||
entry={e}
|
||||
todoTitle={e.todoId ? todoTitles.get(e.todoId) : undefined}
|
||||
todoTitle={e.todoTitle ?? (e.todoId ? todoTitles.get(e.todoId) : undefined)}
|
||||
todos={todayQuery.data?.todos ?? []}
|
||||
isEditing={editing === e.id}
|
||||
onEdit={() => setEditing(e.id)}
|
||||
@@ -77,10 +99,7 @@ export function TimelineSection() {
|
||||
)}
|
||||
|
||||
{manualOpen && (
|
||||
<ManualDialog
|
||||
onClose={() => setManualOpen(false)}
|
||||
todos={todayQuery.data?.todos ?? []}
|
||||
/>
|
||||
<ManualDialog onClose={() => setManualOpen(false)} todos={todayQuery.data?.todos ?? []} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
@@ -92,6 +111,7 @@ type TimeEntryRow = {
|
||||
endedAt: string | Date | null;
|
||||
durationSeconds: number | null;
|
||||
todoId: string | null;
|
||||
todoTitle?: string | null;
|
||||
category: string;
|
||||
description: string | null;
|
||||
};
|
||||
@@ -237,6 +257,11 @@ function TimelineRow({
|
||||
return (
|
||||
<div className="group flex items-center gap-3 rounded-[var(--radius-md)] border border-[var(--color-border)] p-2.5 text-sm">
|
||||
<div className="w-28 shrink-0 font-mono text-xs text-[var(--color-ink-muted)]">
|
||||
{start.toDateString() !== new Date().toDateString() && (
|
||||
<span className="mr-1 text-[var(--color-ink-faint)]">
|
||||
{pad(start.getDate())}.{pad(start.getMonth() + 1)}.
|
||||
</span>
|
||||
)}
|
||||
{pad(start.getHours())}:{pad(start.getMinutes())}
|
||||
{end && (
|
||||
<>
|
||||
@@ -249,7 +274,10 @@ function TimelineRow({
|
||||
<p className="truncate">{label}</p>
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
{CATEGORY_LABEL[entry.category]}
|
||||
{entry.description && !todoTitle && entry.description !== label && ` · ${entry.description}`}
|
||||
{entry.description &&
|
||||
!todoTitle &&
|
||||
entry.description !== label &&
|
||||
` · ${entry.description}`}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
@@ -261,7 +289,7 @@ function TimelineRow({
|
||||
{formatDuration(duration)}
|
||||
</div>
|
||||
{!isRunning && (
|
||||
<div className="flex shrink-0 gap-1 opacity-0 group-hover:opacity-100">
|
||||
<div className="flex shrink-0 gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onEdit}
|
||||
@@ -324,25 +352,7 @@ export function ManualDialog({
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/30"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-[var(--radius-xl)] bg-[var(--color-bg)] p-6 shadow-[var(--shadow-lg)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-semibold">Block nachtragen</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Schließen"
|
||||
className="rounded-[var(--radius-sm)] p-1 text-[var(--color-ink-muted)] hover:bg-black/5"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<Modal open onClose={onClose} title="Block nachtragen">
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block">
|
||||
@@ -414,7 +424,6 @@ export function ManualDialog({
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -9,37 +9,62 @@ import { TIME_CATEGORIES } from '../../lib/time-categories';
|
||||
const CATEGORY_LABEL: Record<string, string> = Object.fromEntries(
|
||||
TIME_CATEGORIES.map((c) => [c.value, c.label]),
|
||||
);
|
||||
const CATEGORY_DOT: Record<string, string> = {
|
||||
focus: 'bg-[var(--color-ink)]',
|
||||
meeting: 'bg-[var(--color-ampel-amber-fg)]',
|
||||
admin: 'bg-[var(--color-ink-muted)]',
|
||||
learning: 'bg-[var(--color-ampel-green-fg)]',
|
||||
break: 'bg-[var(--color-ampel-amber-fg)]',
|
||||
other: 'bg-[var(--color-border-strong)]',
|
||||
};
|
||||
|
||||
type Active = {
|
||||
id: string;
|
||||
startedAt: string | Date;
|
||||
category: string;
|
||||
description: string | null;
|
||||
todoId: string | null;
|
||||
todoTitle: string | null;
|
||||
};
|
||||
|
||||
function labelOf(a: Active): string {
|
||||
return a.description || a.todoTitle || CATEGORY_LABEL[a.category] || 'Timer';
|
||||
}
|
||||
function elapsedOf(a: Active): number {
|
||||
return Math.max(0, Math.round((Date.now() - new Date(a.startedAt).getTime()) / 1000));
|
||||
}
|
||||
|
||||
export function TimerPill() {
|
||||
const utils = trpc.useUtils();
|
||||
const nowQuery = trpc.time.now.useQuery(undefined, { refetchInterval: 30_000 });
|
||||
const todayQuery = trpc.dayEntry.today.useQuery();
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [elapsed, setElapsed] = useState(0);
|
||||
const [panelOpen, setPanelOpen] = useState(false);
|
||||
const [, setTick] = useState(0);
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Tick-Sekundenzähler nur wenn ein Timer läuft.
|
||||
const active: Active[] = nowQuery.data ?? [];
|
||||
|
||||
// Sekunden-Tick nur wenn etwas läuft.
|
||||
useEffect(() => {
|
||||
if (!nowQuery.data) {
|
||||
setElapsed(0);
|
||||
return;
|
||||
}
|
||||
const start = new Date(nowQuery.data.startedAt).getTime();
|
||||
const updateElapsed = () => setElapsed(Math.round((Date.now() - start) / 1000));
|
||||
updateElapsed();
|
||||
const id = window.setInterval(updateElapsed, 1000);
|
||||
if (active.length === 0) return undefined;
|
||||
const id = window.setInterval(() => setTick((t) => t + 1), 1000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [nowQuery.data]);
|
||||
}, [active.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pickerOpen) return undefined;
|
||||
if (!pickerOpen && !panelOpen) return undefined;
|
||||
function onClick(e: MouseEvent) {
|
||||
if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) {
|
||||
setPickerOpen(false);
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') setPickerOpen(false);
|
||||
if (e.key === 'Escape') {
|
||||
setPickerOpen(false);
|
||||
setPanelOpen(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', onClick);
|
||||
document.addEventListener('keydown', onKey);
|
||||
@@ -47,48 +72,40 @@ export function TimerPill() {
|
||||
document.removeEventListener('mousedown', onClick);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [pickerOpen]);
|
||||
}, [pickerOpen, panelOpen]);
|
||||
|
||||
const stopMutation = trpc.time.stop.useMutation({
|
||||
onSuccess: async () => {
|
||||
const invalidate = async () => {
|
||||
await utils.time.now.invalidate();
|
||||
await utils.time.listToday.invalidate();
|
||||
toast('Timer gestoppt.');
|
||||
},
|
||||
});
|
||||
};
|
||||
const startMutation = trpc.time.start.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.time.now.invalidate();
|
||||
await utils.time.listToday.invalidate();
|
||||
await invalidate();
|
||||
setPickerOpen(false);
|
||||
toast('Timer läuft.');
|
||||
},
|
||||
});
|
||||
|
||||
const active = nowQuery.data;
|
||||
const title = active
|
||||
? active.description ||
|
||||
(active.todoId
|
||||
? todayQuery.data?.todos.find((t) => t.id === active.todoId)?.title ?? 'ToDo'
|
||||
: CATEGORY_LABEL[active.category] ?? 'Timer')
|
||||
: null;
|
||||
const count = active.length;
|
||||
const longest = count > 0 ? Math.max(...active.map(elapsedOf)) : 0;
|
||||
|
||||
return (
|
||||
<div className="relative" ref={pickerRef}>
|
||||
{active ? (
|
||||
<div className="relative flex items-center gap-1.5" ref={pickerRef}>
|
||||
{count > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => stopMutation.mutate()}
|
||||
className="group inline-flex items-center gap-2 rounded-full bg-[var(--color-ampel-red-bg)] px-2.5 py-1 text-xs font-medium text-[var(--color-ampel-red-fg)] hover:bg-red-200"
|
||||
title="Stop"
|
||||
onClick={() => setPanelOpen((o) => !o)}
|
||||
aria-expanded={panelOpen}
|
||||
className="inline-flex items-center gap-2 rounded-full bg-[var(--color-ampel-red-bg)] px-2.5 py-1 text-xs font-medium text-[var(--color-ampel-red-fg)] hover:bg-red-200"
|
||||
title={count === 1 ? 'Timer' : `${count} Timer laufen`}
|
||||
>
|
||||
<span className="flex h-1.5 w-1.5 items-center justify-center">
|
||||
<span className="absolute h-1.5 w-1.5 animate-ping rounded-full bg-[var(--color-ampel-red-fg)] opacity-60" />
|
||||
<span className="relative h-1.5 w-1.5 rounded-full bg-[var(--color-ampel-red-fg)]" />
|
||||
</span>
|
||||
<span className="max-w-[180px] truncate">{title}</span>
|
||||
<span className="font-mono tabular-nums">{formatDuration(elapsed)}</span>
|
||||
<Square size={10} fill="currentColor" className="opacity-0 group-hover:opacity-100" />
|
||||
<span className="max-w-[160px] truncate">
|
||||
{count === 1 ? labelOf(active[0]!) : `${count} Timer`}
|
||||
</span>
|
||||
<span className="font-mono tabular-nums">{formatDuration(longest)}</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
@@ -104,7 +121,7 @@ export function TimerPill() {
|
||||
</button>
|
||||
)}
|
||||
|
||||
{pickerOpen && !active && (
|
||||
{pickerOpen && (
|
||||
<QuickPicker
|
||||
todos={(todayQuery.data?.todos ?? []).filter((t) => t.status === 'open')}
|
||||
onClose={() => setPickerOpen(false)}
|
||||
@@ -112,6 +129,65 @@ export function TimerPill() {
|
||||
pending={startMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
{panelOpen && count > 0 && (
|
||||
<TimersPanel
|
||||
active={active}
|
||||
onAdd={() => {
|
||||
setPanelOpen(false);
|
||||
setPickerOpen(true);
|
||||
}}
|
||||
onChanged={invalidate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TimersPanel({
|
||||
active,
|
||||
onAdd,
|
||||
onChanged,
|
||||
}: {
|
||||
active: Active[];
|
||||
onAdd: () => void;
|
||||
onChanged: () => Promise<void>;
|
||||
}) {
|
||||
const stopMutation = trpc.time.stop.useMutation({ onSuccess: onChanged });
|
||||
return (
|
||||
<div className="absolute right-0 top-full z-40 mt-2 w-[320px] rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-surface-elevated)] p-3 shadow-[var(--shadow-lg)]">
|
||||
<p className="px-1 text-xs font-medium text-[var(--color-ink-muted)]">
|
||||
Läuft gerade ({active.length})
|
||||
</p>
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{active.map((a) => (
|
||||
<div key={a.id} className="rounded-[var(--radius-md)] px-1 py-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={clsx('h-2 w-2 shrink-0 rounded-full', CATEGORY_DOT[a.category])} />
|
||||
<span className="flex-1 truncate text-sm">{labelOf(a)}</span>
|
||||
<span className="font-mono text-xs tabular-nums text-[var(--color-ink-muted)]">
|
||||
{formatDuration(elapsedOf(a))}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => stopMutation.mutate({ id: a.id })}
|
||||
aria-label="Stoppen"
|
||||
title="Stoppen"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded-[var(--radius-md)] text-[var(--color-ink-muted)] hover:bg-black/5 hover:text-[var(--color-ink)]"
|
||||
>
|
||||
<Square size={12} fill="currentColor" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
className="mt-2 flex w-full items-center gap-2 border-t border-[var(--color-border)] px-1 pt-2 text-sm text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]"
|
||||
>
|
||||
<Plus size={12} /> Weiteren Task starten
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -124,7 +200,11 @@ function QuickPicker({
|
||||
}: {
|
||||
todos: Array<{ id: string; title: string }>;
|
||||
onClose: () => void;
|
||||
onStart: (input: { todoId?: string; category: 'focus' | 'meeting' | 'admin' | 'learning' | 'break' | 'other'; description?: string }) => void;
|
||||
onStart: (input: {
|
||||
todoId?: string;
|
||||
category: 'focus' | 'meeting' | 'admin' | 'learning' | 'break' | 'other';
|
||||
description?: string;
|
||||
}) => void;
|
||||
pending: boolean;
|
||||
}) {
|
||||
const [description, setDescription] = useState('');
|
||||
@@ -163,7 +243,9 @@ function QuickPicker({
|
||||
<button
|
||||
key={c.value}
|
||||
type="button"
|
||||
onClick={() => onStart({ category: c.value, description: description.trim() || undefined })}
|
||||
onClick={() =>
|
||||
onStart({ category: c.value, description: description.trim() || undefined })
|
||||
}
|
||||
disabled={pending}
|
||||
className="flex w-full items-center gap-2 rounded-[var(--radius-md)] px-2 py-1.5 text-left text-sm hover:bg-black/5"
|
||||
>
|
||||
@@ -174,11 +256,15 @@ function QuickPicker({
|
||||
</div>
|
||||
|
||||
<div className="mt-3 border-t border-[var(--color-border)] pt-2">
|
||||
<label className="block px-1 text-[10px] uppercase tracking-wide text-[var(--color-ink-faint)]">
|
||||
<label
|
||||
htmlFor="timer-freetext"
|
||||
className="block px-1 text-[10px] uppercase tracking-wide text-[var(--color-ink-faint)]"
|
||||
>
|
||||
Mit freiem Text
|
||||
</label>
|
||||
<div className="mt-1 flex gap-1.5">
|
||||
<input
|
||||
id="timer-freetext"
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
|
||||
@@ -5,10 +5,7 @@ function Root({ className, ...rest }: HTMLAttributes<HTMLDivElement>) {
|
||||
// Scharfe Kanten, Haarlinien-Rahmen ohne Schatten — ToolCTRL-Website-Stil.
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'bg-[var(--color-surface)] border border-[var(--color-border)]',
|
||||
className,
|
||||
)}
|
||||
className={clsx('bg-[var(--color-surface)] border border-[var(--color-border)]', className)}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from 'react';
|
||||
import { Modal } from './Modal';
|
||||
import { Button } from './Button';
|
||||
|
||||
export type ConfirmOptions = {
|
||||
title: string;
|
||||
message?: ReactNode;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
destructive?: boolean;
|
||||
};
|
||||
|
||||
type ConfirmFn = (opts: ConfirmOptions) => Promise<boolean>;
|
||||
|
||||
const ConfirmContext = createContext<ConfirmFn | null>(null);
|
||||
|
||||
/**
|
||||
* Imperative Bestätigung: `const confirm = useConfirm(); if (await confirm({...})) …`.
|
||||
* Ersetzt window.confirm() durch einen gestylten, barrierearmen Dialog.
|
||||
*/
|
||||
export function useConfirm(): ConfirmFn {
|
||||
const ctx = useContext(ConfirmContext);
|
||||
if (!ctx) throw new Error('useConfirm muss innerhalb von <ConfirmProvider> stehen.');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||
const [opts, setOpts] = useState<ConfirmOptions | null>(null);
|
||||
const resolver = useRef<((v: boolean) => void) | null>(null);
|
||||
|
||||
const confirm = useCallback<ConfirmFn>((options) => {
|
||||
setOpts(options);
|
||||
return new Promise<boolean>((resolve) => {
|
||||
resolver.current = resolve;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const settle = useCallback((result: boolean) => {
|
||||
resolver.current?.(result);
|
||||
resolver.current = null;
|
||||
setOpts(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ConfirmContext.Provider value={confirm}>
|
||||
{children}
|
||||
<Modal open={opts !== null} onClose={() => settle(false)} title={opts?.title} size="sm">
|
||||
{opts && (
|
||||
<>
|
||||
{opts.message != null && (
|
||||
<div className="mt-2 text-sm text-[var(--color-ink-muted)]">{opts.message}</div>
|
||||
)}
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={() => settle(false)}>
|
||||
{opts.cancelLabel ?? 'Abbrechen'}
|
||||
</Button>
|
||||
<Button
|
||||
variant={opts.destructive ? 'destructive' : 'primary'}
|
||||
onClick={() => settle(true)}
|
||||
>
|
||||
{opts.confirmLabel ?? 'OK'}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</ConfirmContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Button } from './Button';
|
||||
|
||||
/**
|
||||
* Einheitlicher Fehlerzustand für fehlgeschlagene Queries — ersetzt stilles
|
||||
* `return null` (weiße Leerseite) durch einen Hinweis + optionalen Retry.
|
||||
*/
|
||||
export function ErrorState({
|
||||
message = 'Konnte nicht geladen werden.',
|
||||
onRetry,
|
||||
}: {
|
||||
message?: string;
|
||||
onRetry?: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-bg)] p-6 text-center">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{message}</p>
|
||||
{onRetry && (
|
||||
<Button variant="secondary" size="sm" className="mt-3" onClick={onRetry}>
|
||||
Neu laden
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useId, useRef, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
type Size = 'sm' | 'md' | 'lg';
|
||||
|
||||
const maxWidth: Record<Size, string> = {
|
||||
sm: 'max-w-sm',
|
||||
md: 'max-w-md',
|
||||
lg: 'max-w-2xl',
|
||||
};
|
||||
|
||||
/**
|
||||
* Barrierearmer Basis-Dialog: role=dialog/aria-modal, Fokus in den Dialog beim
|
||||
* Öffnen, Fokus-Trap (Tab zyklisch), Escape zum Schließen, Fokus-Rückgabe ans
|
||||
* vorher fokussierte Element, Body-Scroll-Lock. Klick aufs Overlay schließt.
|
||||
* Alle App-Dialoge sollen hierauf aufsetzen.
|
||||
*/
|
||||
export function Modal({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
size = 'md',
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
title?: ReactNode;
|
||||
children: ReactNode;
|
||||
size?: Size;
|
||||
}) {
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const restoreFocus = useRef<HTMLElement | null>(null);
|
||||
const titleId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
restoreFocus.current = document.activeElement as HTMLElement | null;
|
||||
|
||||
const panel = panelRef.current;
|
||||
const focusableSel =
|
||||
'input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';
|
||||
const first = panel?.querySelector<HTMLElement>(focusableSel);
|
||||
(first ?? panel)?.focus();
|
||||
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
if (e.key !== 'Tab' || !panel) return;
|
||||
const nodes = Array.from(panel.querySelectorAll<HTMLElement>(focusableSel));
|
||||
if (nodes.length === 0) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
const firstEl = nodes[0]!;
|
||||
const lastEl = nodes[nodes.length - 1]!;
|
||||
if (e.shiftKey && document.activeElement === firstEl) {
|
||||
e.preventDefault();
|
||||
lastEl.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === lastEl) {
|
||||
e.preventDefault();
|
||||
firstEl.focus();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', onKey);
|
||||
const prevOverflow = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKey);
|
||||
document.body.style.overflow = prevOverflow;
|
||||
restoreFocus.current?.focus?.();
|
||||
};
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return createPortal(
|
||||
// Overlay-Klick schließt (reiner Maus-Komfort); Tastatur/Screenreader nutzen
|
||||
// Escape und den Abbrechen-Button — daher ist die A11y-Regel hier ein false-positive.
|
||||
// Overlay-Klick (nur direkt aufs Overlay, nicht aufs Panel) schließt — reiner
|
||||
// Maus-Komfort; Tastatur/Screenreader nutzen Escape und den Abbrechen-Button.
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4"
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={panelRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={title != null ? titleId : undefined}
|
||||
tabIndex={-1}
|
||||
className={`relative max-h-[90vh] w-full ${maxWidth[size]} overflow-y-auto rounded-[var(--radius-xl)] bg-[var(--color-bg)] p-6 shadow-[var(--shadow-lg)] focus:outline-none`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Schließen"
|
||||
className="absolute right-4 top-4 rounded-[var(--radius-sm)] p-1 text-[var(--color-ink-muted)] hover:bg-black/5 hover:text-[var(--color-ink)]"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
{title != null && (
|
||||
<h2 id={titleId} className="pr-8 text-xl font-semibold">
|
||||
{title}
|
||||
</h2>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Anzeige-Metadaten für Leads — zentral, von /leads und /lead/:id genutzt.
|
||||
|
||||
export type LeadStatus = 'cold' | 'warm' | 'hot' | 'won' | 'lost';
|
||||
|
||||
export const LEAD_STATUS_META: Record<LeadStatus, { label: string; badge: string; dot: string }> = {
|
||||
cold: {
|
||||
label: 'Cold',
|
||||
badge: 'bg-black/5 text-[var(--color-ink-muted)]',
|
||||
dot: 'bg-[var(--color-border-strong)]',
|
||||
},
|
||||
warm: {
|
||||
label: 'Warm',
|
||||
badge: 'bg-[var(--color-ampel-amber-bg)] text-[var(--color-ampel-amber-fg)]',
|
||||
dot: 'bg-[var(--color-ampel-amber-fg)]',
|
||||
},
|
||||
hot: {
|
||||
label: 'Hot',
|
||||
badge: 'bg-[var(--color-ampel-red-bg)] text-[var(--color-ampel-red-fg)]',
|
||||
dot: 'bg-[var(--color-ampel-red-fg)]',
|
||||
},
|
||||
won: {
|
||||
label: 'Won',
|
||||
badge: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
dot: 'bg-[var(--color-ampel-green-fg)]',
|
||||
},
|
||||
lost: {
|
||||
label: 'Lost',
|
||||
badge: 'bg-black/5 text-[var(--color-ink-faint)]',
|
||||
dot: 'bg-[var(--color-ink-faint)]',
|
||||
},
|
||||
};
|
||||
|
||||
// Reihenfolge für Gruppierung/Sortierung in der Liste.
|
||||
export const LEAD_STATUS_ORDER: LeadStatus[] = ['hot', 'warm', 'cold', 'won', 'lost'];
|
||||
|
||||
export const CONTACT_FUNKTION_LABEL: Record<string, string> = {
|
||||
entscheider: 'Entscheider',
|
||||
influencer: 'Influencer',
|
||||
gatekeeper: 'Gatekeeper',
|
||||
end_user: 'End-User',
|
||||
champion: 'Champion',
|
||||
};
|
||||
|
||||
export const TOUCHPOINT_KANAL_LABEL: Record<string, string> = {
|
||||
call: 'Call',
|
||||
mail: 'Mail',
|
||||
linkedin: 'LinkedIn',
|
||||
termin: 'Termin',
|
||||
event: 'Event',
|
||||
sonstiges: 'Sonstiges',
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
// Anzeige-Metadaten für die PM-Insights-Features (Modus, Risiken, Stakeholder).
|
||||
|
||||
export type ProjectModus = 'relax' | 'standard' | 'eskalation' | 'taskforce';
|
||||
|
||||
export const MODUS_META: Record<ProjectModus, { label: string; badge: string; hint: string }> = {
|
||||
relax: {
|
||||
label: 'Relax',
|
||||
badge: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
hint: 'Ruhige Phase, kein Druck.',
|
||||
},
|
||||
standard: {
|
||||
label: 'Standard',
|
||||
badge: 'bg-black/5 text-[var(--color-ink-muted)]',
|
||||
hint: 'Normaler Projektbetrieb.',
|
||||
},
|
||||
eskalation: {
|
||||
label: 'Eskalation',
|
||||
badge: 'bg-[var(--color-ampel-amber-bg)] text-[var(--color-ampel-amber-fg)]',
|
||||
hint: 'Erhöhte Aufmerksamkeit nötig.',
|
||||
},
|
||||
taskforce: {
|
||||
label: 'Taskforce',
|
||||
badge: 'bg-[var(--color-ampel-red-bg)] text-[var(--color-ampel-red-fg)]',
|
||||
hint: 'Alle Kräfte gebündelt, höchste Priorität.',
|
||||
},
|
||||
};
|
||||
export const MODI: ProjectModus[] = ['relax', 'standard', 'eskalation', 'taskforce'];
|
||||
|
||||
export type Level = 'niedrig' | 'mittel' | 'hoch';
|
||||
|
||||
export const LEVEL_META: Record<Level, { label: string; badge: string }> = {
|
||||
niedrig: {
|
||||
label: 'Niedrig',
|
||||
badge: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
},
|
||||
mittel: {
|
||||
label: 'Mittel',
|
||||
badge: 'bg-[var(--color-ampel-amber-bg)] text-[var(--color-ampel-amber-fg)]',
|
||||
},
|
||||
hoch: { label: 'Hoch', badge: 'bg-[var(--color-ampel-red-bg)] text-[var(--color-ampel-red-fg)]' },
|
||||
};
|
||||
export const LEVELS: Level[] = ['niedrig', 'mittel', 'hoch'];
|
||||
|
||||
export type RiskStatus = 'offen' | 'beobachtet' | 'eingetreten' | 'geschlossen';
|
||||
export const RISK_STATUS_LABEL: Record<RiskStatus, string> = {
|
||||
offen: 'Offen',
|
||||
beobachtet: 'Beobachtet',
|
||||
eingetreten: 'Eingetreten',
|
||||
geschlossen: 'Geschlossen',
|
||||
};
|
||||
export const RISK_STATUSES: RiskStatus[] = ['offen', 'beobachtet', 'eingetreten', 'geschlossen'];
|
||||
|
||||
export type Haltung = 'pro' | 'neutral' | 'contra';
|
||||
export const HALTUNG_META: Record<Haltung, { label: string; dot: string }> = {
|
||||
pro: { label: 'Pro', dot: 'bg-[var(--color-ampel-green-fg)]' },
|
||||
neutral: { label: 'Neutral', dot: 'bg-[var(--color-ink-faint)]' },
|
||||
contra: { label: 'Contra', dot: 'bg-[var(--color-ampel-red-fg)]' },
|
||||
};
|
||||
export const HALTUNGEN: Haltung[] = ['pro', 'neutral', 'contra'];
|
||||
|
||||
// Empfehlung je Quadrant der Macht/Interesse-Matrix (Einfluss × Interesse).
|
||||
export function stakeholderStrategie(einfluss: Level, interesse: Level): string {
|
||||
const hochEinfluss = einfluss === 'hoch';
|
||||
const hochInteresse = interesse === 'hoch';
|
||||
if (hochEinfluss && hochInteresse) return 'Eng managen';
|
||||
if (hochEinfluss && !hochInteresse) return 'Zufrieden halten';
|
||||
if (!hochEinfluss && hochInteresse) return 'Informiert halten';
|
||||
return 'Beobachten';
|
||||
}
|
||||
|
||||
export type ProjectPhase = 'definition' | 'planung' | 'umsetzung' | 'abschluss';
|
||||
export const PHASES: ProjectPhase[] = ['definition', 'planung', 'umsetzung', 'abschluss'];
|
||||
export const PHASE_META: Record<ProjectPhase, { label: string; gateZiel: string }> = {
|
||||
definition: { label: 'Definition', gateZiel: 'Steckbrief abgestimmt und freigegeben' },
|
||||
planung: {
|
||||
label: 'Planung',
|
||||
gateZiel: 'Plan steht — Backlog zerlegt, Meilensteine & Risiken erfasst',
|
||||
},
|
||||
umsetzung: { label: 'Umsetzung', gateZiel: 'Liefergegenstände abgenommen' },
|
||||
abschluss: { label: 'Abschluss', gateZiel: 'Projekt beendet, Erkenntnisse gesichert' },
|
||||
};
|
||||
|
||||
export type ZieldreieckFlex = 'leistung' | 'zeit' | 'aufwand';
|
||||
export const ZIELDREIECK_LABEL: Record<ZieldreieckFlex, string> = {
|
||||
leistung: 'Leistung / Umfang',
|
||||
zeit: 'Zeit',
|
||||
aufwand: 'Aufwand',
|
||||
};
|
||||
export const ZIELDREIECK_FLEX: ZieldreieckFlex[] = ['leistung', 'zeit', 'aufwand'];
|
||||
|
||||
export type RiskStrategie = 'vermeiden' | 'verlagern' | 'mindern' | 'akzeptieren';
|
||||
export const RISK_STRATEGIE_LABEL: Record<RiskStrategie, string> = {
|
||||
vermeiden: 'Vermeiden',
|
||||
verlagern: 'Verlagern',
|
||||
mindern: 'Mindern',
|
||||
akzeptieren: 'Akzeptieren',
|
||||
};
|
||||
export const RISK_STRATEGIEN: RiskStrategie[] = [
|
||||
'vermeiden',
|
||||
'verlagern',
|
||||
'mindern',
|
||||
'akzeptieren',
|
||||
];
|
||||
|
||||
export type ChangeEntscheidung = 'offen' | 'genehmigt' | 'abgelehnt';
|
||||
export const CHANGE_ENTSCHEIDUNG_META: Record<
|
||||
ChangeEntscheidung,
|
||||
{ label: string; badge: string }
|
||||
> = {
|
||||
offen: {
|
||||
label: 'Offen',
|
||||
badge: 'bg-[var(--color-ampel-amber-bg)] text-[var(--color-ampel-amber-fg)]',
|
||||
},
|
||||
genehmigt: {
|
||||
label: 'Genehmigt',
|
||||
badge: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
},
|
||||
abgelehnt: { label: 'Abgelehnt', badge: 'bg-black/5 text-[var(--color-ink-faint)]' },
|
||||
};
|
||||
export const CHANGE_ENTSCHEIDUNGEN: ChangeEntscheidung[] = ['offen', 'genehmigt', 'abgelehnt'];
|
||||
|
||||
// Datums-Warnungen (keine Meilensteine Freitag / vor Feiertagen).
|
||||
export function dateWarnings(iso: string | null | undefined): string[] {
|
||||
if (!iso) return [];
|
||||
const d = new Date(`${iso}T00:00:00`);
|
||||
if (Number.isNaN(d.getTime())) return [];
|
||||
const out: string[] = [];
|
||||
const wd = d.getDay(); // 0=So .. 6=Sa
|
||||
if (wd === 5) out.push('Fällt auf einen Freitag — besser keine Meilensteine/Abgaben freitags.');
|
||||
if (wd === 0 || wd === 6) out.push('Fällt aufs Wochenende.');
|
||||
const month = d.getMonth();
|
||||
const day = d.getDate();
|
||||
if ((month === 11 && day >= 20) || (month === 0 && day <= 6)) {
|
||||
out.push('Liegt in der Weihnachts-/Neujahrszeit — besser einige Wochen davor oder danach.');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1,22 +1,85 @@
|
||||
import { createBrowserRouter, RouterProvider } from 'react-router';
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { lazy, Suspense, type ComponentType } from 'react';
|
||||
import { AppShell } from '../components/layout/AppShell';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { Button } from '../components/ui/Button';
|
||||
|
||||
const Dashboard = lazy(() => import('../routes/dashboard').then((m) => ({ default: m.DashboardRoute })));
|
||||
const Heute = lazy(() =>
|
||||
// Nach einem Deploy zeigen bereits offene Tabs auf alte, inzwischen gelöschte
|
||||
// Chunk-Dateien (gehashte Dateinamen). Der nächste Lazy-Import schlägt dann fehl
|
||||
// („Failed to fetch dynamically imported module"). Ein einmaliger Reload holt die
|
||||
// frische index.html mit den neuen Hashes. sessionStorage-Guard verhindert eine
|
||||
// Reload-Schleife, falls der Fehler eine andere Ursache hat (z. B. offline).
|
||||
const RELOAD_KEY = 'ebw:chunk-reload';
|
||||
|
||||
function reloadOnceForStaleChunk(): boolean {
|
||||
const last = Number(sessionStorage.getItem(RELOAD_KEY) ?? '0');
|
||||
if (Date.now() - last > 10_000) {
|
||||
sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function lazyWithReload<T extends ComponentType>(factory: () => Promise<{ default: T }>) {
|
||||
return lazy(() =>
|
||||
factory().catch((err: unknown) => {
|
||||
if (reloadOnceForStaleChunk()) {
|
||||
// Hängt bis der Reload greift — vermeidet ein kurzes Aufblitzen des Fehlers.
|
||||
return new Promise<{ default: T }>(() => {});
|
||||
}
|
||||
throw err;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Vite feuert dieses Event bei fehlgeschlagenem modulepreload (gleiche Ursache).
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('vite:preloadError', (e) => {
|
||||
if (reloadOnceForStaleChunk()) e.preventDefault();
|
||||
});
|
||||
}
|
||||
|
||||
const Dashboard = lazyWithReload(() =>
|
||||
import('../routes/dashboard').then((m) => ({ default: m.DashboardRoute })),
|
||||
);
|
||||
const Heute = lazyWithReload(() =>
|
||||
import('../routes/heute').then((m) => ({ default: m.HeuteRoute })),
|
||||
);
|
||||
const Reflexion = lazy(() =>
|
||||
const Reflexion = lazyWithReload(() =>
|
||||
import('../routes/reflexion').then((m) => ({ default: m.ReflexionRoute })),
|
||||
);
|
||||
const Bereich = lazy(() => import('../routes/bereich').then((m) => ({ default: m.BereichRoute })));
|
||||
const Projekt = lazy(() => import('../routes/projekt').then((m) => ({ default: m.ProjektRoute })));
|
||||
const Archiv = lazy(() => import('../routes/archiv').then((m) => ({ default: m.ArchivRoute })));
|
||||
const NotFound = lazy(() =>
|
||||
const Bereich = lazyWithReload(() =>
|
||||
import('../routes/bereich').then((m) => ({ default: m.BereichRoute })),
|
||||
);
|
||||
const Projekt = lazyWithReload(() =>
|
||||
import('../routes/projekt').then((m) => ({ default: m.ProjektRoute })),
|
||||
);
|
||||
const Leads = lazyWithReload(() =>
|
||||
import('../routes/leads').then((m) => ({ default: m.LeadsRoute })),
|
||||
);
|
||||
const Lead = lazyWithReload(() => import('../routes/lead').then((m) => ({ default: m.LeadRoute })));
|
||||
const TeamView = lazyWithReload(() =>
|
||||
import('../routes/team-view').then((m) => ({ default: m.TeamViewRoute })),
|
||||
);
|
||||
const Historie = lazyWithReload(() =>
|
||||
import('../routes/historie').then((m) => ({ default: m.HistorieRoute })),
|
||||
);
|
||||
const Archiv = lazyWithReload(() =>
|
||||
import('../routes/archiv').then((m) => ({ default: m.ArchivRoute })),
|
||||
);
|
||||
const Pipeline = lazyWithReload(() =>
|
||||
import('../routes/pipeline').then((m) => ({ default: m.PipelineRoute })),
|
||||
);
|
||||
const MeineWoche = lazyWithReload(() =>
|
||||
import('../routes/meine-woche').then((m) => ({ default: m.MeineWocheRoute })),
|
||||
);
|
||||
const NotFound = lazyWithReload(() =>
|
||||
import('../routes/not-found').then((m) => ({ default: m.NotFoundRoute })),
|
||||
);
|
||||
const Login = lazy(() => import('../routes/login').then((m) => ({ default: m.LoginRoute })));
|
||||
const Login = lazyWithReload(() =>
|
||||
import('../routes/login').then((m) => ({ default: m.LoginRoute })),
|
||||
);
|
||||
|
||||
function withSuspense(node: React.ReactNode) {
|
||||
return (
|
||||
@@ -24,22 +87,44 @@ function withSuspense(node: React.ReactNode) {
|
||||
);
|
||||
}
|
||||
|
||||
function RouteError() {
|
||||
return (
|
||||
<div className="mx-auto mt-16 max-w-md text-center">
|
||||
<h1 className="text-lg font-semibold">Etwas ist schiefgelaufen.</h1>
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Wahrscheinlich wurde gerade eine neue Version veröffentlicht. Lade die Seite neu.
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => window.location.reload()}>
|
||||
Neu laden
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: '/login',
|
||||
element: withSuspense(<Login />),
|
||||
errorElement: <RouteError />,
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
element: <AppShell />,
|
||||
errorElement: <RouteError />,
|
||||
children: [
|
||||
{ index: true, element: withSuspense(<Dashboard />) },
|
||||
{ path: 'dashboard', element: withSuspense(<Dashboard />) },
|
||||
{ path: 'heute', element: withSuspense(<Heute />) },
|
||||
{ path: 'meine-woche', element: withSuspense(<MeineWoche />) },
|
||||
{ path: 'reflexion', element: withSuspense(<Reflexion />) },
|
||||
{ path: 'bereich', element: withSuspense(<Bereich />) },
|
||||
{ path: 'bereich/:slug', element: withSuspense(<Bereich />) },
|
||||
{ path: 'projekt/:id', element: withSuspense(<Projekt />) },
|
||||
{ path: 'leads', element: withSuspense(<Leads />) },
|
||||
{ path: 'pipeline', element: withSuspense(<Pipeline />) },
|
||||
{ path: 'lead/:id', element: withSuspense(<Lead />) },
|
||||
{ path: 'team', element: withSuspense(<TeamView />) },
|
||||
{ path: 'historie', element: withSuspense(<Historie />) },
|
||||
{ path: 'archiv', element: withSuspense(<Archiv />) },
|
||||
{ path: '*', element: withSuspense(<NotFound />) },
|
||||
],
|
||||
|
||||
@@ -11,7 +11,11 @@ export function TrpcProvider({ children }: { children: React.ReactNode }) {
|
||||
new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
// staleTime 0: beim Aufrufen einer Seite / Tab-Fokus werden Daten
|
||||
// neu geholt, statt bis zu 30 s veraltete Cache-Stände zu zeigen
|
||||
// (sonst landeten Aktionen wie „Lock in" erst nach Refresh im
|
||||
// Dashboard). Kein Polling — nur Refetch bei Mount/Fokus.
|
||||
staleTime: 0,
|
||||
retry: 1,
|
||||
},
|
||||
mutations: {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Anwesenheits-Sekunden von Lock-in bis Feierabend — bzw. bis jetzt, solange
|
||||
* noch kein Check-Out vorliegt. Reine Anzeige, unabhängig vom Task-Tracking.
|
||||
* Tickt minütlich, solange der Tag noch läuft.
|
||||
*/
|
||||
export function usePresenceSeconds(
|
||||
checkedInAt: string | Date | null | undefined,
|
||||
checkedOutAt: string | Date | null | undefined,
|
||||
): number | null {
|
||||
const running = Boolean(checkedInAt) && !checkedOutAt;
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
const id = setInterval(() => setNowMs(Date.now()), 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, [running]);
|
||||
if (!checkedInAt) return null;
|
||||
const endMs = checkedOutAt ? new Date(checkedOutAt).getTime() : nowMs;
|
||||
return Math.max(0, Math.round((endMs - new Date(checkedInAt).getTime()) / 1000));
|
||||
}
|
||||
@@ -11,6 +11,8 @@ export const voice = {
|
||||
blockerResolved: 'Blocker erledigt.',
|
||||
projectCreated: 'Projekt angelegt.',
|
||||
projectArchived: 'Projekt archiviert.',
|
||||
leadCreated: 'Lead angelegt.',
|
||||
leadPromoted: 'Lead ist jetzt ein Deal.',
|
||||
saved: 'Gespeichert.',
|
||||
strong: 'Stark.',
|
||||
},
|
||||
@@ -19,6 +21,7 @@ export const voice = {
|
||||
reflect: 'Reflektieren',
|
||||
newBlocker: 'Neuer Blocker',
|
||||
newProject: 'Neues Projekt',
|
||||
newLead: 'Neuer Lead',
|
||||
},
|
||||
hint: {
|
||||
notCheckedInToday: 'Du hast heute noch nicht gepingt.',
|
||||
|
||||
+150
-29
@@ -1,12 +1,16 @@
|
||||
import { Link, NavLink, useParams } from 'react-router';
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { voice } from '../lib/voice';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { Modal } from '../components/ui/Modal';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { toast } from 'sonner';
|
||||
import { clsx } from 'clsx';
|
||||
import { LEAD_STATUS_META, type LeadStatus } from '../lib/lead-meta';
|
||||
import { MODUS_META, type ProjectModus } from '../lib/project-meta';
|
||||
import { ProjectLogo, LogoUpload } from '../components/project/ProjectLogo';
|
||||
|
||||
const BEREICHE: Array<{ slug: 'entwicklung' | 'vertrieb' | 'marketing'; label: string }> = [
|
||||
{ slug: 'entwicklung', label: 'Entwicklung' },
|
||||
@@ -83,8 +87,10 @@ function Section({
|
||||
projects: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
logoUrl: string | null;
|
||||
statusCache: 'green' | 'amber' | 'red' | null;
|
||||
deadline: string | null;
|
||||
modus: ProjectModus;
|
||||
pflichtMinimumState: Record<string, boolean>;
|
||||
}>;
|
||||
}) {
|
||||
@@ -102,13 +108,28 @@ function Section({
|
||||
{projects.map((p) => (
|
||||
<Link key={p.id} to={`/projekt/${p.id}`} className="contents">
|
||||
<Card.Root className="cursor-pointer hover:shadow-[var(--shadow-md)]">
|
||||
<Card.Body className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium">{p.name}</p>
|
||||
<Card.Body className="flex items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<ProjectLogo url={p.logoUrl} name={p.name} size={40} />
|
||||
<div className="min-w-0">
|
||||
<p className="flex items-center gap-2 font-medium">
|
||||
{p.name}
|
||||
{p.modus !== 'standard' && (
|
||||
<span
|
||||
className={clsx(
|
||||
'rounded-full px-2 py-0.5 text-[10px] font-medium',
|
||||
MODUS_META[p.modus].badge,
|
||||
)}
|
||||
>
|
||||
{MODUS_META[p.modus].label}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
{p.deadline ? `bis ${p.deadline}` : 'kein Deadline'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<PflichtMinimumIndicator state={p.pflichtMinimumState} />
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
@@ -160,9 +181,18 @@ function ProjectCreateDialog({
|
||||
const defaultArea = areas.find((a) => a.slug === defaultSlug);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [logoUrl, setLogoUrl] = useState<string | null>(null);
|
||||
const [areaId, setAreaId] = useState(defaultArea?.id ?? '');
|
||||
|
||||
// Areas werden asynchron geladen; sobald sie da sind und noch nichts gewählt
|
||||
// wurde, sinnvollen Default setzen (Dropdown war sonst leer).
|
||||
useEffect(() => {
|
||||
if (!areaId && areas.length > 0) {
|
||||
const fallback = areas.find((a) => a.slug === defaultSlug) ?? areas[0];
|
||||
if (fallback) setAreaId(fallback.id);
|
||||
}
|
||||
}, [areas, areaId, defaultSlug]);
|
||||
const [kind, setKind] = useState<'kundenprojekt' | 'internes_projekt'>('internes_projekt');
|
||||
const [arbeitsmodus, setArbeitsmodus] = useState<'cycle' | 'kanban'>('kanban');
|
||||
const [steckbrief, setSteckbrief] = useState('');
|
||||
const [plane, setPlane] = useState('');
|
||||
|
||||
@@ -183,23 +213,15 @@ function ProjectCreateDialog({
|
||||
areaId,
|
||||
name,
|
||||
description: description.trim() || undefined,
|
||||
logoUrl: logoUrl ?? undefined,
|
||||
kind,
|
||||
arbeitsmodus,
|
||||
outlineSteckbriefUrl: steckbrief,
|
||||
planeProjectUrl: plane,
|
||||
milestones: [],
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/30"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-[var(--radius-xl)] bg-[var(--color-bg)] p-6 shadow-[var(--shadow-lg)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2 className="text-xl font-semibold">Neues Projekt</h2>
|
||||
<Modal open onClose={onClose} title="Neues Projekt">
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<Field label="Name">
|
||||
<input
|
||||
@@ -219,6 +241,9 @@ function ProjectCreateDialog({
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Logo (optional)">
|
||||
<LogoUpload value={logoUrl} name={name} onChange={setLogoUrl} />
|
||||
</Field>
|
||||
<Field label="Bereich">
|
||||
<select
|
||||
required
|
||||
@@ -226,6 +251,9 @@ function ProjectCreateDialog({
|
||||
onChange={(e) => setAreaId(e.target.value)}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="" disabled>
|
||||
{areas.length ? '— Bereich wählen —' : 'Bereiche werden geladen…'}
|
||||
</option>
|
||||
{areas.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
@@ -243,16 +271,6 @@ function ProjectCreateDialog({
|
||||
<option value="internes_projekt">Internes Projekt</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Arbeitsmodus">
|
||||
<select
|
||||
value={arbeitsmodus}
|
||||
onChange={(e) => setArbeitsmodus(e.target.value as 'cycle' | 'kanban')}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="kanban">Kanban</option>
|
||||
<option value="cycle">Cycle</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Outline-Steckbrief-URL">
|
||||
<input
|
||||
required
|
||||
@@ -282,8 +300,7 @@ function ProjectCreateDialog({
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -297,7 +314,112 @@ function Field({ label, children }: { label: string; children: React.ReactNode }
|
||||
}
|
||||
|
||||
function VertriebDetail() {
|
||||
return <ProjektListeFuerBereich slug="vertrieb" />;
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<LeadsTeaser />
|
||||
<ProjekteMitLeads />
|
||||
<ProjektListeFuerBereich slug="vertrieb" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Bereichsübergreifend: Projekte (egal aus welchem Bereich), die verknüpfte
|
||||
// Leads haben — so taucht z. B. ein Entwicklungsprojekt hier auf, WEIL es
|
||||
// Vertriebsaktivität hat, ohne redundant angelegt werden zu müssen.
|
||||
function ProjekteMitLeads() {
|
||||
const q = trpc.lead.list.useQuery();
|
||||
const leads = q.data ?? [];
|
||||
const map = new Map<string, { id: string; name: string; total: number; open: number }>();
|
||||
for (const l of leads) {
|
||||
if (!l.projectId || !l.projectName) continue;
|
||||
const e = map.get(l.projectId) ?? { id: l.projectId, name: l.projectName, total: 0, open: 0 };
|
||||
e.total++;
|
||||
if (l.status !== 'won' && l.status !== 'lost') e.open++;
|
||||
map.set(l.projectId, e);
|
||||
}
|
||||
const projects = Array.from(map.values()).sort((a, b) => b.open - a.open);
|
||||
if (projects.length === 0) return null;
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-2 text-lg font-semibold">Projekte mit Vertriebsaktivität</h2>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||
{projects.map((p) => (
|
||||
<Link key={p.id} to={`/projekt/${p.id}`} className="contents">
|
||||
<Card.Root className="cursor-pointer hover:shadow-[var(--shadow-md)]">
|
||||
<Card.Body className="flex items-center justify-between gap-2">
|
||||
<p className="font-medium">{p.name}</p>
|
||||
<span className="shrink-0 text-xs text-[var(--color-ink-muted)]">
|
||||
{p.total} {p.total === 1 ? 'Lead' : 'Leads'}
|
||||
{p.open > 0 && ` · ${p.open} offen`}
|
||||
</span>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadsTeaser() {
|
||||
const q = trpc.lead.list.useQuery();
|
||||
const leads = q.data ?? [];
|
||||
const offen = leads.filter((l) => l.status !== 'won' && l.status !== 'lost');
|
||||
const top = [...offen].sort((a, b) => b.score - a.score).slice(0, 3);
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h2 className="text-lg font-semibold">Leads</h2>
|
||||
<Link
|
||||
to="/leads"
|
||||
className="text-sm text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
Alle Leads ({leads.length}) →
|
||||
</Link>
|
||||
</div>
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
{q.isPending ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">Lädt…</p>
|
||||
) : offen.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
Keine offenen Leads.{' '}
|
||||
<Link to="/leads" className="hover:underline">
|
||||
Lege einen an.
|
||||
</Link>
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-[var(--color-border)]">
|
||||
{top.map((l) => {
|
||||
const meta = LEAD_STATUS_META[l.status as LeadStatus];
|
||||
return (
|
||||
<li key={l.id}>
|
||||
<Link
|
||||
to={`/lead/${l.id}`}
|
||||
className="flex items-center justify-between gap-2 py-2 hover:opacity-80"
|
||||
>
|
||||
<span className="flex items-center gap-2 text-sm">
|
||||
<span className={clsx('h-2 w-2 rounded-full', meta.dot)} />
|
||||
<span className="font-medium">{l.firma}</span>
|
||||
{l.subSegment && (
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">
|
||||
{l.subSegment}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="font-mono text-xs tabular-nums text-[var(--color-ink-muted)]">
|
||||
{l.score}/10
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function MarketingDetail() {
|
||||
@@ -329,4 +451,3 @@ function ProjektListeFuerBereich({ slug }: { slug: 'vertrieb' | 'marketing' }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,10 +4,12 @@ import { voice } from '../lib/voice';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { TeamTimeSection } from '../components/time/TeamTimeSection';
|
||||
import { MODUS_META, type ProjectModus } from '../lib/project-meta';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import { clsx } from 'clsx';
|
||||
|
||||
type Ampel = 'green' | 'amber' | 'red' | 'grey';
|
||||
import { ProjectLogo } from '../components/project/ProjectLogo';
|
||||
|
||||
export function DashboardRoute() {
|
||||
const q = trpc.dashboard.overview.useQuery();
|
||||
@@ -22,7 +24,13 @@ export function DashboardRoute() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!q.data) return null;
|
||||
if (q.isError || !q.data)
|
||||
return (
|
||||
<ErrorState
|
||||
message="Dashboard konnte nicht geladen werden."
|
||||
onRetry={() => void q.refetch()}
|
||||
/>
|
||||
);
|
||||
|
||||
const isCheckedIn =
|
||||
today.data?.entry?.status !== undefined && today.data.entry.status !== 'absent';
|
||||
@@ -46,31 +54,102 @@ export function DashboardRoute() {
|
||||
)}
|
||||
</header>
|
||||
|
||||
<section aria-labelledby="bereiche-heading">
|
||||
<h2 id="bereiche-heading" className="sr-only">
|
||||
Bereiche
|
||||
{q.data.showstoppers.length > 0 && (
|
||||
<section>
|
||||
<Card.Root className="border-[var(--color-ampel-red-fg)]">
|
||||
<Card.Header>
|
||||
<h2 className="flex items-center gap-2 text-lg font-semibold text-[var(--color-ampel-red-fg)]">
|
||||
<AlertTriangle size={18} /> Showstopper
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
{q.data.areas.map((a) => (
|
||||
<Link key={a.id} to={`/bereich/${a.slug}`} className="contents">
|
||||
<Card.Root className="cursor-pointer hover:shadow-[var(--shadow-md)] transition-shadow">
|
||||
<Card.Body className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">{a.name}</h3>
|
||||
<AmpelDot ampel={a.ampel as Ampel} />
|
||||
</div>
|
||||
<div className="flex gap-3 text-xs text-[var(--color-ink-muted)]">
|
||||
<span>{a.counts.green} grün</span>
|
||||
<span>{a.counts.amber} gelb</span>
|
||||
<span>{a.counts.red} rot</span>
|
||||
{a.counts.grey > 0 && <span>{a.counts.grey} ohne Status</span>}
|
||||
</div>
|
||||
</Card.Header>
|
||||
<Card.Body>
|
||||
<ul className="space-y-2">
|
||||
{q.data.showstoppers.map((s) => (
|
||||
<li
|
||||
key={s.id}
|
||||
className="flex items-start justify-between gap-3 rounded-[var(--radius-md)] border border-[var(--color-border)] p-3"
|
||||
>
|
||||
<span className="text-sm">{s.title}</span>
|
||||
<Link
|
||||
to={`/projekt/${s.projectId}`}
|
||||
className="shrink-0 text-xs text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
{s.projectName} →
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{q.data.meilensteine.length > 0 && (
|
||||
<section>
|
||||
<h2 className="mb-2 text-lg font-semibold">Anstehende Meilensteine</h2>
|
||||
<Card.Root>
|
||||
<Card.Body className="p-0">
|
||||
<ul className="divide-y divide-[var(--color-border)]">
|
||||
{q.data.meilensteine.map((m) => (
|
||||
<li key={m.id} className="flex items-center justify-between gap-3 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{m.title}</p>
|
||||
<div className="mt-0.5 flex items-center gap-2 text-xs">
|
||||
<span
|
||||
className={clsx(
|
||||
m.ueberfaellig
|
||||
? 'font-medium text-[var(--color-ampel-red-fg)]'
|
||||
: 'text-[var(--color-ink-muted)]',
|
||||
)}
|
||||
>
|
||||
{formatDate(m.due!)}
|
||||
{m.ueberfaellig && ' · überfällig'}
|
||||
</span>
|
||||
<span className="text-[var(--color-ink-faint)]">·</span>
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
{relativeDays(m.due!, q.data.date)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Link
|
||||
to={`/projekt/${m.projectId}`}
|
||||
className="inline-flex shrink-0 items-center gap-2 text-xs text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
<ProjectLogo url={m.projectLogoUrl} name={m.projectName} size={20} />
|
||||
{m.projectName} →
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{q.data.kritischeModi.length > 0 && (
|
||||
<section>
|
||||
<h2 className="mb-2 text-lg font-semibold">Projekte in Eskalation / Taskforce</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{q.data.kritischeModi.map((p) => (
|
||||
<Link
|
||||
key={p.id}
|
||||
to={`/projekt/${p.id}`}
|
||||
className="inline-flex items-center gap-2 rounded-[var(--radius-md)] border border-[var(--color-border)] px-3 py-1.5 text-sm hover:border-[var(--color-ink)]"
|
||||
>
|
||||
<span
|
||||
className={clsx(
|
||||
'rounded-full px-2 py-0.5 text-[10px] font-medium',
|
||||
MODUS_META[p.modus as ProjectModus].badge,
|
||||
)}
|
||||
>
|
||||
{MODUS_META[p.modus as ProjectModus].label}
|
||||
</span>
|
||||
{p.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="grid grid-cols-1 gap-6 md:grid-cols-3">
|
||||
<Card.Root>
|
||||
@@ -132,7 +211,11 @@ export function DashboardRoute() {
|
||||
<ul className="space-y-1 text-sm">
|
||||
{q.data.pflichtMinimumOffen.map((p) => (
|
||||
<li key={p.id}>
|
||||
<Link to={`/projekt/${p.id}`} className="hover:underline">
|
||||
<Link
|
||||
to={`/projekt/${p.id}`}
|
||||
className="inline-flex items-center gap-2 hover:underline"
|
||||
>
|
||||
<ProjectLogo url={p.logoUrl} name={p.name} size={20} />
|
||||
{p.name}
|
||||
</Link>
|
||||
</li>
|
||||
@@ -147,9 +230,17 @@ export function DashboardRoute() {
|
||||
<TeamTimeSection />
|
||||
|
||||
<section aria-labelledby="feed-heading">
|
||||
<h2 id="feed-heading" className="mb-3 text-lg font-semibold">
|
||||
<div className="mb-3 flex items-baseline justify-between">
|
||||
<h2 id="feed-heading" className="text-lg font-semibold">
|
||||
Gestern im Team
|
||||
</h2>
|
||||
<Link
|
||||
to="/historie"
|
||||
className="text-xs text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
Ganze Historie →
|
||||
</Link>
|
||||
</div>
|
||||
{q.data.feed.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
@@ -179,16 +270,6 @@ export function DashboardRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
function AmpelDot({ ampel }: { ampel: Ampel }) {
|
||||
const colorClass = {
|
||||
green: 'bg-[var(--color-ampel-green-fg)]',
|
||||
amber: 'bg-[var(--color-ampel-amber-fg)]',
|
||||
red: 'bg-[var(--color-ampel-red-fg)]',
|
||||
grey: 'bg-[var(--color-ink-faint)]',
|
||||
}[ampel];
|
||||
return <span className={clsx('inline-block h-3 w-3 rounded-full', colorClass)} aria-hidden />;
|
||||
}
|
||||
|
||||
function AmpelBadge({ ampel }: { ampel: 'green' | 'amber' | 'red' }) {
|
||||
const cls = {
|
||||
green: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
@@ -255,7 +336,9 @@ function TeamHeuteSection() {
|
||||
</span>
|
||||
</div>
|
||||
{u.todos.length === 0 ? (
|
||||
<p className="mt-2 text-xs text-[var(--color-ink-faint)]">Keine ToDos eingetragen.</p>
|
||||
<p className="mt-2 text-xs text-[var(--color-ink-faint)]">
|
||||
Keine ToDos eingetragen.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-2 space-y-1.5 text-sm">
|
||||
{u.todos.map((t) => (
|
||||
@@ -299,5 +382,18 @@ function formatDate(input: string | Date): string {
|
||||
}).format(dt);
|
||||
}
|
||||
|
||||
// Relative Tagesangabe für Meilensteine ("heute", "in 3 Tagen", "vor 2 Tagen").
|
||||
function relativeDays(dueIso: string, todayIso: string): string {
|
||||
const due = new Date(`${dueIso}T00:00:00`);
|
||||
const today = new Date(`${todayIso}T00:00:00`);
|
||||
if (Number.isNaN(due.getTime()) || Number.isNaN(today.getTime())) return '';
|
||||
const diff = Math.round((due.getTime() - today.getTime()) / 86_400_000);
|
||||
if (diff === 0) return 'heute';
|
||||
if (diff === 1) return 'morgen';
|
||||
if (diff === -1) return 'gestern';
|
||||
if (diff > 0) return `in ${diff} Tagen`;
|
||||
return `vor ${Math.abs(diff)} Tagen`;
|
||||
}
|
||||
|
||||
// Button als referenz behalten (Linter)
|
||||
void Button;
|
||||
+312
-13
@@ -4,10 +4,13 @@ import { trpc } from '../lib/trpc';
|
||||
import { voice } from '../lib/voice';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { Modal } from '../components/ui/Modal';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { toast } from 'sonner';
|
||||
import { X, Plus, RotateCw, BellRing, Play, Clock } from 'lucide-react';
|
||||
import { X, Plus, RotateCw, BellRing, Play, Clock, Check, LogOut } from 'lucide-react';
|
||||
import { TimelineSection, ManualDialog } from '../components/time/TimelineSection';
|
||||
import { formatDurationCompact } from '../lib/format-duration';
|
||||
import { usePresenceSeconds } from '../lib/use-presence-seconds';
|
||||
|
||||
/** Aktuelle Stunde in Europe/Berlin (0–23). */
|
||||
function berlinHourNow(): number {
|
||||
@@ -59,6 +62,10 @@ function CheckInForm({ onDone }: { onDone: () => void }) {
|
||||
toast(msg);
|
||||
await utils.dayEntry.today.invalidate();
|
||||
await utils.dayEntry.pendingCarryOver.invalidate();
|
||||
// Dashboard-Sichten sofort mitziehen (Quote, Anwesenheit, „Heute im Team").
|
||||
await utils.dayEntry.todayTeam.invalidate();
|
||||
await utils.dayEntry.todayPresence.invalidate();
|
||||
await utils.dashboard.overview.invalidate();
|
||||
onDone();
|
||||
},
|
||||
});
|
||||
@@ -182,7 +189,7 @@ function TodoRow({
|
||||
todo,
|
||||
allTodos,
|
||||
}: {
|
||||
todo: { id: string; title: string; status: 'open' | 'done' | 'dropped' };
|
||||
todo: { id: string; title: string; status: 'open' | 'done' | 'dropped'; unplanned?: boolean };
|
||||
allTodos: Array<{ id: string; title: string }>;
|
||||
}) {
|
||||
const utils = trpc.useUtils();
|
||||
@@ -200,7 +207,8 @@ function TodoRow({
|
||||
await utils.time.listToday.invalidate();
|
||||
},
|
||||
});
|
||||
const isRunningHere = now.data?.todoId === todo.id;
|
||||
const activeHere = now.data?.find((a) => a.todoId === todo.id);
|
||||
const isRunningHere = !!activeHere;
|
||||
const dotClass =
|
||||
todo.status === 'done'
|
||||
? 'h-2 w-2 rounded-full bg-[var(--color-ampel-green-fg)]'
|
||||
@@ -212,26 +220,30 @@ function TodoRow({
|
||||
<span className={dotClass} />
|
||||
<span
|
||||
className={
|
||||
todo.status === 'dropped'
|
||||
? 'flex-1 line-through text-[var(--color-ink-muted)]'
|
||||
: 'flex-1'
|
||||
todo.status === 'dropped' ? 'flex-1 line-through text-[var(--color-ink-muted)]' : 'flex-1'
|
||||
}
|
||||
>
|
||||
{todo.title}
|
||||
{todo.unplanned && (
|
||||
<span className="ml-2 rounded-full bg-black/5 px-1.5 py-0.5 text-[10px] text-[var(--color-ink-muted)]">
|
||||
ungeplant
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{todo.status !== 'done' && todo.status !== 'dropped' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
isRunningHere
|
||||
? stopMutation.mutate()
|
||||
activeHere
|
||||
? stopMutation.mutate({ id: activeHere.id })
|
||||
: startMutation.mutate({ todoId: todo.id, category: 'focus' })
|
||||
}
|
||||
aria-label={isRunningHere ? 'Timer stoppen' : 'Timer für diesen ToDo starten'}
|
||||
aria-label={isRunningHere ? 'Task pausieren' : 'Task starten / fortsetzen'}
|
||||
title={isRunningHere ? 'Pausieren' : 'Starten / fortsetzen'}
|
||||
className={
|
||||
isRunningHere
|
||||
? 'inline-flex h-7 items-center gap-1 rounded-full bg-[var(--color-ampel-red-bg)] px-2 text-xs font-medium text-[var(--color-ampel-red-fg)]'
|
||||
: 'inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--color-ink-muted)] opacity-0 hover:bg-black/5 hover:text-[var(--color-ink)] group-hover:opacity-100'
|
||||
: 'inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--color-ink-muted)] opacity-100 hover:bg-black/5 hover:text-[var(--color-ink)] sm:opacity-0 sm:group-hover:opacity-100'
|
||||
}
|
||||
>
|
||||
{isRunningHere ? (
|
||||
@@ -253,7 +265,7 @@ function TodoRow({
|
||||
onClick={() => setRetroOpen(true)}
|
||||
aria-label="Zeit nachtragen"
|
||||
title="Zeit nachtragen"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--color-ink-muted)] opacity-0 hover:bg-black/5 hover:text-[var(--color-ink)] group-hover:opacity-100"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--color-ink-muted)] opacity-100 hover:bg-black/5 hover:text-[var(--color-ink)] sm:opacity-0 sm:group-hover:opacity-100"
|
||||
>
|
||||
<Clock size={12} />
|
||||
</button>
|
||||
@@ -269,12 +281,289 @@ function TodoRow({
|
||||
);
|
||||
}
|
||||
|
||||
function AddTodoInline() {
|
||||
const utils = trpc.useUtils();
|
||||
const [title, setTitle] = useState('');
|
||||
const add = trpc.dayEntry.addTodo.useMutation({
|
||||
onSuccess: async () => {
|
||||
setTitle('');
|
||||
await utils.dayEntry.today.invalidate();
|
||||
await utils.dayEntry.todayTeam.invalidate();
|
||||
await utils.dashboard.overview.invalidate();
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="mt-3 flex items-center gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const v = title.trim();
|
||||
if (!v) return;
|
||||
add.mutate({ title: v });
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Neues ToDo hinzufügen …"
|
||||
maxLength={200}
|
||||
className="flex-1 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<Button type="submit" size="sm" variant="secondary" disabled={!title.trim() || add.isPending}>
|
||||
<Plus size={14} /> Hinzufügen
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function CheckInOutBar({
|
||||
checkedInAt,
|
||||
checkedOutAt,
|
||||
autoCheckedIn,
|
||||
todos,
|
||||
reflected,
|
||||
}: {
|
||||
checkedInAt: string | Date | null;
|
||||
checkedOutAt: string | Date | null;
|
||||
autoCheckedIn: boolean;
|
||||
todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped' }>;
|
||||
reflected: boolean;
|
||||
}) {
|
||||
const utils = trpc.useUtils();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const checkOut = trpc.dayEntry.checkOut.useMutation({
|
||||
onSuccess: async () => {
|
||||
setConfirmOpen(false);
|
||||
toast('Feierabend — Check-Out gespeichert.');
|
||||
await utils.dayEntry.today.invalidate();
|
||||
await utils.dashboard.overview.invalidate();
|
||||
},
|
||||
});
|
||||
const reopen = trpc.dayEntry.reopen.useMutation({
|
||||
onSuccess: async () => {
|
||||
toast('Willkommen zurück — Arbeit fortgesetzt.');
|
||||
await utils.dayEntry.today.invalidate();
|
||||
await utils.dashboard.overview.invalidate();
|
||||
},
|
||||
onError: (err) => toast(err.message),
|
||||
});
|
||||
const hhmm = (d: string | Date | null) =>
|
||||
d
|
||||
? new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: 'Europe/Berlin',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(d))
|
||||
: '—';
|
||||
// Anwesenheit (Lock-in → Feierabend bzw. jetzt) — reine Anzeige, kein Tracking.
|
||||
// Auto-Check-in vom 6-Uhr-Schnitt ist kein echter Lock-in → Fallback-Anker
|
||||
// (erster Zeiteintrag des Tages) aus listToday.
|
||||
const listToday = trpc.time.listToday.useQuery(undefined, { refetchInterval: 30_000 });
|
||||
const presenceFrom =
|
||||
!autoCheckedIn && checkedInAt ? checkedInAt : (listToday.data?.presenceStartedAt ?? null);
|
||||
const presenceSeconds = usePresenceSeconds(presenceFrom, checkedOutAt);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-[var(--radius-md)] border border-[var(--color-border)] px-4 py-2 text-sm">
|
||||
<span>
|
||||
Arbeitsantritt <span className="font-mono">{hhmm(checkedInAt)}</span>
|
||||
</span>
|
||||
{checkedOutAt ? (
|
||||
<>
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
· Feierabend <span className="font-mono">{hhmm(checkedOutAt)}</span>
|
||||
{presenceSeconds !== null && ` · ${formatDurationCompact(presenceSeconds)} anwesend`}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="ml-auto"
|
||||
disabled={reopen.isPending}
|
||||
onClick={() => reopen.mutate()}
|
||||
>
|
||||
<Play size={14} /> Arbeit fortsetzen
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{presenceSeconds !== null && (
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
· anwesend seit{' '}
|
||||
<span className="font-mono">{formatDurationCompact(presenceSeconds)}</span>
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="ml-auto"
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
<LogOut size={14} /> Feierabend / Check-Out
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<FeierabendDialog
|
||||
open={confirmOpen}
|
||||
onClose={() => setConfirmOpen(false)}
|
||||
todos={todos}
|
||||
reflected={reflected}
|
||||
pending={checkOut.isPending}
|
||||
onConfirm={() => checkOut.mutate()}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tagesabschluss vor dem Feierabend: kurze Zusammenfassung (erledigt/offen/
|
||||
* verworfen) und ein Hinweis, falls noch ToDos offen oder die Reflexion fehlt.
|
||||
* Feierabend ist reversibel ("Arbeit fortsetzen") — der Dialog ist daher Info,
|
||||
* keine harte Sperre.
|
||||
*/
|
||||
function FeierabendDialog({
|
||||
open,
|
||||
onClose,
|
||||
todos,
|
||||
reflected,
|
||||
pending,
|
||||
onConfirm,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped' }>;
|
||||
reflected: boolean;
|
||||
pending: boolean;
|
||||
onConfirm: () => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const done = todos.filter((t) => t.status === 'done');
|
||||
const dropped = todos.filter((t) => t.status === 'dropped');
|
||||
const offen = todos.filter((t) => t.status === 'open');
|
||||
const reflexionEmpfohlen = !reflected || offen.length > 0;
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Feierabend?" size="md">
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Kurzer Blick auf den Tag, bevor du abschließt.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
<span>
|
||||
<strong>{done.length}</strong> erledigt
|
||||
</span>
|
||||
<span>
|
||||
<strong>{offen.length}</strong> offen
|
||||
</span>
|
||||
{dropped.length > 0 && (
|
||||
<span>
|
||||
<strong>{dropped.length}</strong> verworfen
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{done.length > 0 && (
|
||||
<ul className="mt-3 space-y-1 text-sm">
|
||||
{done.map((t) => (
|
||||
<li key={t.id} className="flex items-center gap-2 text-[var(--color-ink-muted)]">
|
||||
<Check size={14} className="shrink-0 text-[var(--color-ampel-green-fg)]" />
|
||||
<span className="truncate">{t.title}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{offen.length > 0 && (
|
||||
<div className="mt-4 rounded-[var(--radius-md)] border border-[var(--color-ampel-amber-fg)] bg-[var(--color-ampel-amber-bg)] px-3 py-2 text-sm">
|
||||
<strong className="block">Noch offen — nicht reflektiert:</strong>
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{offen.map((t) => (
|
||||
<li key={t.id} className="truncate">
|
||||
· {t.title}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!reflected && (
|
||||
<p className="mt-3 text-sm text-[var(--color-ink-muted)]">
|
||||
Du hast heute noch nicht reflektiert.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-5 flex flex-wrap justify-end gap-2">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
{reflexionEmpfohlen && (
|
||||
<Button variant="secondary" onClick={() => navigate('/reflexion')}>
|
||||
Zur Reflexion
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="primary" disabled={pending} onClick={onConfirm}>
|
||||
Tag abschließen
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function AddUnplannedInline() {
|
||||
const utils = trpc.useUtils();
|
||||
const [title, setTitle] = useState('');
|
||||
const add = trpc.dayEntry.addUnplanned.useMutation({
|
||||
onSuccess: async () => {
|
||||
setTitle('');
|
||||
toast('Ungeplant erledigt — eingetragen.');
|
||||
await utils.dayEntry.today.invalidate();
|
||||
await utils.dayEntry.todayTeam.invalidate();
|
||||
await utils.dashboard.overview.invalidate();
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="mt-2 flex items-center gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const v = title.trim();
|
||||
if (!v) return;
|
||||
add.mutate({ title: v });
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Ungeplant erledigt? z. B. mItapp-Security-Fix für Yevgen …"
|
||||
maxLength={200}
|
||||
className="flex-1 rounded-[var(--radius-md)] border border-dashed border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<Button type="submit" size="sm" variant="ghost" disabled={!title.trim() || add.isPending}>
|
||||
<Check size={14} /> Erledigt eintragen
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function EinstempeltView({
|
||||
todos,
|
||||
entry,
|
||||
}: {
|
||||
todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped' }>;
|
||||
entry: { status: 'begun' | 'full' | 'absent' };
|
||||
todos: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
status: 'open' | 'done' | 'dropped';
|
||||
unplanned?: boolean;
|
||||
}>;
|
||||
entry: {
|
||||
status: 'begun' | 'full' | 'absent';
|
||||
checkedInAt: string | Date | null;
|
||||
checkedOutAt: string | Date | null;
|
||||
autoCheckedIn: boolean;
|
||||
};
|
||||
}) {
|
||||
// Reflexion ist „fällig", wenn nach 18:00 Berlin und noch nicht abgeschlossen.
|
||||
const reflectionDue = entry.status !== 'full' && berlinHourNow() >= 18;
|
||||
@@ -292,6 +581,14 @@ function EinstempeltView({
|
||||
<p className="mt-1 text-[var(--color-ink-muted)]">{subtitle}</p>
|
||||
</header>
|
||||
|
||||
<CheckInOutBar
|
||||
checkedInAt={entry.checkedInAt}
|
||||
checkedOutAt={entry.checkedOutAt}
|
||||
autoCheckedIn={entry.autoCheckedIn}
|
||||
todos={todos}
|
||||
reflected={entry.status === 'full'}
|
||||
/>
|
||||
|
||||
{reflectionDue && (
|
||||
<div
|
||||
role="alert"
|
||||
@@ -318,6 +615,8 @@ function EinstempeltView({
|
||||
<TodoRow key={t.id} todo={t} allTodos={todos} />
|
||||
))}
|
||||
</ul>
|
||||
<AddTodoInline />
|
||||
<AddUnplannedInline />
|
||||
</Card.Body>
|
||||
<Card.Footer className="flex justify-end">
|
||||
<Button onClick={() => (location.href = '/reflexion')}>{ctaLabel}</Button>
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { ChevronLeft, ChevronRight, Pencil } from 'lucide-react';
|
||||
import { clsx } from 'clsx';
|
||||
import type { inferRouterOutputs } from '@trpc/server';
|
||||
import type { AppRouter } from '@cockpit/api/router';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { useCurrentUser } from '../hooks/useCurrentUser';
|
||||
|
||||
type HistoryPerson = inferRouterOutputs<AppRouter>['dayEntry']['historyForDate']['entries'][number];
|
||||
|
||||
const AMPEL_META: Record<string, { label: string; badge: string }> = {
|
||||
green: {
|
||||
label: 'Im Plan',
|
||||
badge: 'bg-[var(--color-ampel-green-bg)] text-[var(--color-ampel-green-fg)]',
|
||||
},
|
||||
amber: {
|
||||
label: 'Gefährdet',
|
||||
badge: 'bg-[var(--color-ampel-amber-bg)] text-[var(--color-ampel-amber-fg)]',
|
||||
},
|
||||
red: {
|
||||
label: 'Blockiert',
|
||||
badge: 'bg-[var(--color-ampel-red-bg)] text-[var(--color-ampel-red-fg)]',
|
||||
},
|
||||
};
|
||||
const TREND_LABEL: Record<string, string> = {
|
||||
besser: '↗ Besser',
|
||||
gleich: '→ Gleich',
|
||||
schlechter: '↘ Schlechter',
|
||||
};
|
||||
|
||||
function formatDateLong(iso: string): string {
|
||||
return new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: 'Europe/Berlin',
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
}).format(new Date(`${iso}T12:00:00Z`));
|
||||
}
|
||||
|
||||
const todayStr = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Berlin' }).format(new Date());
|
||||
|
||||
// Editierbar bis 3 Kalendertage nach dem Tag (Spiegel der Backend-Nachfrist).
|
||||
function isWithinGraceFE(dateIso: string): boolean {
|
||||
const cur = new Date(`${dateIso}T12:00:00Z`).getTime();
|
||||
const today = new Date(`${todayStr}T12:00:00Z`).getTime();
|
||||
const diffDays = Math.round((today - cur) / 86_400_000);
|
||||
return diffDays >= 0 && diffDays <= 3;
|
||||
}
|
||||
|
||||
export function HistorieRoute() {
|
||||
const [date, setDate] = useState<string | undefined>(undefined);
|
||||
const me = useCurrentUser();
|
||||
const navigate = useNavigate();
|
||||
const q = trpc.dayEntry.historyForDate.useQuery({ date });
|
||||
|
||||
if (q.isPending) return <SkeletonCard lines={6} />;
|
||||
if (q.isError || !q.data)
|
||||
return (
|
||||
<ErrorState
|
||||
message="Historie konnte nicht geladen werden."
|
||||
onRetry={() => void q.refetch()}
|
||||
/>
|
||||
);
|
||||
const { date: current, prevDate, nextDate, entries, ohneEintrag } = q.data;
|
||||
const editableDay = isWithinGraceFE(current);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header>
|
||||
<h1 className="text-3xl font-bold">Historie</h1>
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Was hat das Team an einem Tag gemacht — Reflexion & ToDos.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => prevDate && setDate(prevDate)}
|
||||
disabled={!prevDate}
|
||||
aria-label="Vorheriger Tag mit Eintrag"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-ink)] hover:text-[var(--color-ink)] disabled:opacity-40 disabled:hover:border-[var(--color-border)]"
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
</button>
|
||||
<span className="min-w-[200px] text-center font-medium">{formatDateLong(current)}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => nextDate && setDate(nextDate)}
|
||||
disabled={!nextDate}
|
||||
aria-label="Nächster Tag mit Eintrag"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-ink)] hover:text-[var(--color-ink)] disabled:opacity-40 disabled:hover:border-[var(--color-border)]"
|
||||
>
|
||||
<ChevronRight size={16} />
|
||||
</button>
|
||||
<input
|
||||
type="date"
|
||||
value={current}
|
||||
max={todayStr}
|
||||
onChange={(e) => setDate(e.target.value || undefined)}
|
||||
className="ml-2 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">Keine Einträge an diesem Tag.</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{entries.map((p) => (
|
||||
<PersonCard
|
||||
key={p.userId}
|
||||
person={p}
|
||||
canEdit={p.userId === me?.id && editableDay}
|
||||
onEdit={() => navigate(`/reflexion?date=${current}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ohneEintrag.length > 0 && (
|
||||
<p className="text-xs text-[var(--color-ink-faint)]">
|
||||
Ohne Eintrag an diesem Tag: {ohneEintrag.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PersonCard({
|
||||
person: p,
|
||||
canEdit,
|
||||
onEdit,
|
||||
}: {
|
||||
person: HistoryPerson;
|
||||
canEdit: boolean;
|
||||
onEdit: () => void;
|
||||
}) {
|
||||
const ampel = p.ampel ? AMPEL_META[p.ampel] : null;
|
||||
return (
|
||||
<Card.Root>
|
||||
<Card.Body className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="font-semibold">{p.name}</p>
|
||||
{ampel && (
|
||||
<span className={clsx('rounded-full px-2 py-0.5 text-xs font-medium', ampel.badge)}>
|
||||
{ampel.label}
|
||||
</span>
|
||||
)}
|
||||
{p.trend && (
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">
|
||||
{TREND_LABEL[p.trend] ?? p.trend}
|
||||
</span>
|
||||
)}
|
||||
{p.status === 'begun' && (
|
||||
<span className="rounded-full bg-black/5 px-2 py-0.5 text-xs text-[var(--color-ink-muted)]">
|
||||
nicht reflektiert
|
||||
</span>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button size="sm" variant="ghost" className="ml-auto" onClick={onEdit}>
|
||||
<Pencil size={13} /> Bearbeiten
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{p.todos.length > 0 && (
|
||||
<ul className="space-y-1 text-sm">
|
||||
{p.todos.map((t) => (
|
||||
<li key={t.id} className="flex items-start gap-2">
|
||||
<span
|
||||
className={clsx(
|
||||
'mt-1.5 inline-block h-2 w-2 shrink-0 rounded-full',
|
||||
t.status === 'done'
|
||||
? 'bg-[var(--color-ampel-green-fg)]'
|
||||
: t.status === 'dropped'
|
||||
? 'bg-[var(--color-ink-faint)]'
|
||||
: 'bg-[var(--color-border-strong)]',
|
||||
)}
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<span
|
||||
className={clsx(
|
||||
t.status === 'dropped' && 'text-[var(--color-ink-muted)] line-through',
|
||||
)}
|
||||
>
|
||||
{t.title}
|
||||
{t.unplanned && (
|
||||
<span className="ml-2 rounded-full bg-black/5 px-1.5 py-0.5 text-[10px] text-[var(--color-ink-muted)]">
|
||||
ungeplant
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{t.dropReason && (
|
||||
<span className="mt-0.5 block whitespace-pre-wrap text-xs text-[var(--color-ink-muted)]">
|
||||
{t.dropReason}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{p.reflectionText && (
|
||||
<p className="whitespace-pre-wrap text-sm text-[var(--color-ink)]">{p.reflectionText}</p>
|
||||
)}
|
||||
{p.url && (
|
||||
<a
|
||||
href={p.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block truncate text-sm text-[var(--color-ink-muted)] underline hover:text-[var(--color-ink)]"
|
||||
>
|
||||
{p.url}
|
||||
</a>
|
||||
)}
|
||||
{p.todos.length === 0 && !p.reflectionText && !p.url && (
|
||||
<p className="text-xs text-[var(--color-ink-faint)]">Keine Details.</p>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,429 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { BellRing } from 'lucide-react';
|
||||
import { clsx } from 'clsx';
|
||||
import { toast } from 'sonner';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { voice } from '../lib/voice';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { Modal } from '../components/ui/Modal';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { LEAD_STATUS_META, LEAD_STATUS_ORDER, type LeadStatus } from '../lib/lead-meta';
|
||||
|
||||
export function LeadsRoute() {
|
||||
const q = trpc.lead.list.useQuery();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
|
||||
if (q.isPending) return <SkeletonCard lines={6} />;
|
||||
const leads = q.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header className="flex items-end justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
<Link to="/bereich/vertrieb" className="hover:underline">
|
||||
Vertrieb
|
||||
</Link>
|
||||
{' › Leads'}
|
||||
</p>
|
||||
<h1 className="text-3xl font-bold">Leads</h1>
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Qualitative Lead-Dossiers — Stammdaten, Pain, Strategie, Austausch-Log.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Link
|
||||
to="/pipeline"
|
||||
className="inline-flex h-9 items-center rounded-md px-4 text-sm font-medium text-[var(--color-ink)] transition-colors hover:bg-black/5"
|
||||
>
|
||||
Pipeline
|
||||
</Link>
|
||||
<Button variant="secondary" onClick={() => setImportOpen(true)}>
|
||||
CSV importieren
|
||||
</Button>
|
||||
<Button onClick={() => setOpen(true)}>{voice.cta.newLead}</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<DueFollowUps />
|
||||
|
||||
{leads.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">Noch keine Leads. Leg einen an.</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
LEAD_STATUS_ORDER.map((status) => {
|
||||
const group = leads.filter((l) => l.status === status);
|
||||
if (group.length === 0) return null;
|
||||
return (
|
||||
<section key={status}>
|
||||
<h2 className="mb-2 text-lg font-semibold">
|
||||
{LEAD_STATUS_META[status].label}{' '}
|
||||
<span className="text-sm font-normal text-[var(--color-ink-muted)]">
|
||||
({group.length})
|
||||
</span>
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||
{group.map((l) => (
|
||||
<LeadCard key={l.id} lead={l} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})
|
||||
)}
|
||||
|
||||
{open && <LeadCreateDialog onClose={() => setOpen(false)} />}
|
||||
{importOpen && <LeadImportDialog onClose={() => setImportOpen(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DueFollowUps() {
|
||||
const q = trpc.lead.dueFollowUps.useQuery();
|
||||
if (!q.data || q.data.length === 0) return null;
|
||||
return (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<h2 className="mb-2 flex items-center gap-2 text-lg font-semibold">
|
||||
<BellRing size={16} className="text-[var(--color-ampel-amber-fg)]" />
|
||||
Fällige Wiedervorlagen ({q.data.length})
|
||||
</h2>
|
||||
<ul className="space-y-1.5 text-sm">
|
||||
{q.data.map((l) => (
|
||||
<li key={l.id} className="flex items-center justify-between gap-3">
|
||||
<Link to={`/lead/${l.id}`} className="min-w-0 flex-1 truncate hover:underline">
|
||||
<span className="font-medium">{l.firma}</span>
|
||||
{l.naechsterSchritt && (
|
||||
<span className="text-[var(--color-ink-muted)]"> — {l.naechsterSchritt}</span>
|
||||
)}
|
||||
</Link>
|
||||
<span className="shrink-0 font-mono text-xs text-[var(--color-ampel-amber-fg)]">
|
||||
{l.faelligAm}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadImportDialog({ onClose }: { onClose: () => void }) {
|
||||
const projectsQ = trpc.project.list.useQuery();
|
||||
const projects = (projectsQ.data ?? []).map((r) => ({ id: r.project.id, name: r.project.name }));
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [fileName, setFileName] = useState('');
|
||||
const [csv, setCsv] = useState('');
|
||||
const [result, setResult] = useState<{
|
||||
created: number;
|
||||
skippedEmpty: number;
|
||||
skippedDuplicate: number;
|
||||
contacts: number;
|
||||
touchpoints: number;
|
||||
} | null>(null);
|
||||
const utils = trpc.useUtils();
|
||||
const importMut = trpc.lead.importCsv.useMutation({
|
||||
onSuccess: async (res) => {
|
||||
setResult(res);
|
||||
await utils.lead.list.invalidate();
|
||||
toast(`${res.created} Leads importiert.`);
|
||||
},
|
||||
});
|
||||
|
||||
function onFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setFileName(file.name);
|
||||
setResult(null);
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => setCsv(typeof reader.result === 'string' ? reader.result : '');
|
||||
reader.readAsText(file);
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title="Leads aus CSV importieren">
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Spalten: Quelle, Vorname, Nachname, Position, Firma, Straße, PLZ, Ort, Telefon, Mobil, Fax,
|
||||
E-Mail, Website, Branche, Notizen. Je Zeile entsteht ein Lead mit primärem Kontakt; Notizen
|
||||
werden als erster Austausch-Log-Eintrag gespeichert. Duplikate (gleicher Firmenname) werden
|
||||
übersprungen.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 space-y-3">
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Projekt zuordnen (optional)</span>
|
||||
<select
|
||||
value={projectId}
|
||||
onChange={(e) => setProjectId(e.target.value)}
|
||||
disabled={!!result}
|
||||
className="mt-1 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">— kein Projekt —</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">CSV-Datei</span>
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,text/csv"
|
||||
onChange={onFile}
|
||||
className="mt-1 block w-full text-sm file:mr-3 file:rounded-[var(--radius-md)] file:border file:border-[var(--color-border)] file:bg-white file:px-3 file:py-1.5 file:text-sm"
|
||||
/>
|
||||
</label>
|
||||
{fileName && !result && (
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
Bereit: {fileName} ({Math.max(0, csv.split('\n').filter((l) => l.trim()).length - 1)}{' '}
|
||||
Datenzeilen)
|
||||
</p>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="rounded-[var(--radius-md)] border border-[var(--color-border)] p-3 text-sm">
|
||||
<p className="font-medium text-[var(--color-ampel-green-fg)]">
|
||||
{result.created} Leads importiert
|
||||
</p>
|
||||
<ul className="mt-1 space-y-0.5 text-xs text-[var(--color-ink-muted)]">
|
||||
<li>{result.contacts} Kontakte angelegt</li>
|
||||
<li>{result.touchpoints} Notizen als Log-Eintrag</li>
|
||||
{result.skippedDuplicate > 0 && (
|
||||
<li>{result.skippedDuplicate} Duplikate übersprungen</li>
|
||||
)}
|
||||
{result.skippedEmpty > 0 && <li>{result.skippedEmpty} leere Zeilen übersprungen</li>}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
{result ? 'Schließen' : 'Abbrechen'}
|
||||
</Button>
|
||||
{!result && (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => importMut.mutate({ csv, projectId: projectId || undefined })}
|
||||
disabled={!csv || importMut.isPending}
|
||||
>
|
||||
{importMut.isPending ? 'Importiere…' : 'Importieren'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadCard({
|
||||
lead,
|
||||
}: {
|
||||
lead: {
|
||||
id: string;
|
||||
firma: string;
|
||||
status: LeadStatus;
|
||||
score: number;
|
||||
ownerName: string | null;
|
||||
projectName: string | null;
|
||||
branche: string | null;
|
||||
subSegment: string | null;
|
||||
naechsterSchrittDatum: string | null;
|
||||
};
|
||||
}) {
|
||||
const meta = LEAD_STATUS_META[lead.status];
|
||||
const sub = [lead.branche, lead.subSegment].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<Link to={`/lead/${lead.id}`} className="contents">
|
||||
<Card.Root className="cursor-pointer hover:shadow-[var(--shadow-md)]">
|
||||
<Card.Body className="space-y-2">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="font-semibold">{lead.firma}</p>
|
||||
<span className={clsx('shrink-0 rounded-full px-2 py-0.5 text-xs', meta.badge)}>
|
||||
{meta.label}
|
||||
</span>
|
||||
</div>
|
||||
{sub && <p className="text-xs text-[var(--color-ink-muted)]">{sub}</p>}
|
||||
{lead.projectName && (
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
<span className="rounded-full bg-black/5 px-2 py-0.5">↳ {lead.projectName}</span>
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between text-xs text-[var(--color-ink-muted)]">
|
||||
<span>{lead.ownerName ?? 'ohne Owner'}</span>
|
||||
<span className="font-mono tabular-nums">Score {lead.score}/10</span>
|
||||
</div>
|
||||
{lead.naechsterSchrittDatum && (
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
Nächster Schritt: {lead.naechsterSchrittDatum}
|
||||
</p>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadCreateDialog({ onClose }: { onClose: () => void }) {
|
||||
const users = trpc.user.list.useQuery();
|
||||
const projectsQ = trpc.project.list.useQuery();
|
||||
const projects = (projectsQ.data ?? []).map((r) => ({ id: r.project.id, name: r.project.name }));
|
||||
const [firma, setFirma] = useState('');
|
||||
const [branche, setBranche] = useState('');
|
||||
const [subSegment, setSubSegment] = useState('');
|
||||
const [website, setWebsite] = useState('');
|
||||
const [quelle, setQuelle] = useState('');
|
||||
const [ownerUserId, setOwnerUserId] = useState('');
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [status, setStatus] = useState<LeadStatus>('cold');
|
||||
const [score, setScore] = useState(0);
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
const create = trpc.lead.create.useMutation({
|
||||
onSuccess: async () => {
|
||||
toast(voice.toast.leadCreated);
|
||||
await utils.lead.list.invalidate();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!firma.trim()) return;
|
||||
create.mutate({
|
||||
firma: firma.trim(),
|
||||
branche: branche.trim() || undefined,
|
||||
subSegment: subSegment.trim() || undefined,
|
||||
website: website.trim() || undefined,
|
||||
quelle: quelle.trim() || undefined,
|
||||
ownerUserId: ownerUserId || undefined,
|
||||
projectId: projectId || undefined,
|
||||
status,
|
||||
score,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open onClose={onClose} title="Neuer Lead">
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Nur die Firma ist Pflicht — alles Weitere füllst du im Dossier.
|
||||
</p>
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<Field label="Firma">
|
||||
<input
|
||||
required
|
||||
value={firma}
|
||||
onChange={(e) => setFirma(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Branche">
|
||||
<input
|
||||
value={branche}
|
||||
onChange={(e) => setBranche(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nische / Sub-Segment">
|
||||
<input
|
||||
value={subSegment}
|
||||
onChange={(e) => setSubSegment(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Website">
|
||||
<input
|
||||
value={website}
|
||||
onChange={(e) => setWebsite(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Quelle (wie gefunden)">
|
||||
<input value={quelle} onChange={(e) => setQuelle(e.target.value)} className={inputCls} />
|
||||
</Field>
|
||||
<Field label="Projekt (optional)">
|
||||
<select
|
||||
value={projectId}
|
||||
onChange={(e) => setProjectId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">— kein Projekt —</option>
|
||||
{projects.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Owner">
|
||||
<select
|
||||
value={ownerUserId}
|
||||
onChange={(e) => setOwnerUserId(e.target.value)}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="">— niemand —</option>
|
||||
{(users.data ?? []).map((u) => (
|
||||
<option key={u.id} value={u.id}>
|
||||
{u.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Status">
|
||||
<select
|
||||
value={status}
|
||||
onChange={(e) => setStatus(e.target.value as LeadStatus)}
|
||||
className={inputCls}
|
||||
>
|
||||
{LEAD_STATUS_ORDER.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{LEAD_STATUS_META[s].label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label={`Score: ${score}/10`}>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={10}
|
||||
value={score}
|
||||
onChange={(e) => setScore(Number(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</Field>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={create.isPending}>
|
||||
Anlegen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
'w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm';
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">{label}</span>
|
||||
<div className="mt-1">{children}</div>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -25,9 +25,7 @@ export function LoginRoute() {
|
||||
<h1 className="inline-flex items-center gap-2 text-4xl font-bold">
|
||||
everythingbutwork <ToolCtrlLogo size={32} />
|
||||
</h1>
|
||||
<p className="mt-3 text-[var(--color-ink-muted)]">
|
||||
Internes ToolCTRL-Projektmanagement.
|
||||
</p>
|
||||
<p className="mt-3 text-[var(--color-ink-muted)]">Internes ToolCTRL-Projektmanagement.</p>
|
||||
{error && (
|
||||
<p
|
||||
className="mt-4 rounded-[var(--radius-md)] border border-[var(--color-ampel-red-bg)] bg-[var(--color-ampel-red-bg)] px-4 py-2 text-sm text-[var(--color-ampel-red-fg)]"
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
|
||||
const AMPEL_DOT: Record<string, string> = {
|
||||
green: 'bg-[var(--color-ampel-green-fg)]',
|
||||
amber: 'bg-[var(--color-ampel-amber-fg)]',
|
||||
red: 'bg-[var(--color-ampel-red-fg)]',
|
||||
};
|
||||
const TREND_LABEL: Record<string, string> = { besser: '↗', gleich: '→', schlechter: '↘' };
|
||||
|
||||
function weekday(iso: string): string {
|
||||
return new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: 'Europe/Berlin',
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
}).format(new Date(`${iso}T12:00:00Z`));
|
||||
}
|
||||
|
||||
function hhmm(d: string | Date | null): string {
|
||||
return d
|
||||
? new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: 'Europe/Berlin',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(d))
|
||||
: '—';
|
||||
}
|
||||
|
||||
export function MeineWocheRoute() {
|
||||
const q = trpc.dayEntry.myWeek.useQuery();
|
||||
if (q.isPending) return <SkeletonCard lines={7} />;
|
||||
if (q.isError || !q.data)
|
||||
return (
|
||||
<ErrorState
|
||||
message="Wochenübersicht konnte nicht geladen werden."
|
||||
onRetry={() => void q.refetch()}
|
||||
/>
|
||||
);
|
||||
|
||||
const days = q.data;
|
||||
const totalDone = days.reduce((s, d) => s + d.todos.done, 0);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl space-y-6">
|
||||
<header>
|
||||
<h1 className="text-3xl font-bold">Meine Woche</h1>
|
||||
<p className="mt-1 text-[var(--color-ink-muted)]">
|
||||
Die letzten 7 Tage — {totalDone} ToDos erledigt.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{days.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
Noch keine Einträge in den letzten 7 Tagen.
|
||||
</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
<Card.Root>
|
||||
<Card.Body className="divide-y divide-[var(--color-border)]">
|
||||
{days.map((d) => (
|
||||
<div
|
||||
key={d.date}
|
||||
className="flex items-center gap-3 py-2.5 text-sm first:pt-0 last:pb-0"
|
||||
>
|
||||
<span className="w-28 shrink-0 font-medium">{weekday(d.date)}</span>
|
||||
<span
|
||||
className={`h-2 w-2 shrink-0 rounded-full ${d.ampel ? (AMPEL_DOT[d.ampel] ?? '') : 'bg-[var(--color-border-strong)]'}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="flex-1 truncate text-[var(--color-ink-muted)]">
|
||||
{hhmm(d.checkedInAt)}
|
||||
{d.checkedOutAt ? `–${hhmm(d.checkedOutAt)}` : d.checkedInAt ? ' …' : ''}
|
||||
{d.trend ? ` · ${TREND_LABEL[d.trend] ?? ''}` : ''}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-[var(--color-ink-muted)]">
|
||||
{d.todos.done}✓{d.todos.open > 0 ? ` · ${d.todos.open} offen` : ''}
|
||||
{d.todos.dropped > 0 ? ` · ${d.todos.dropped} verworfen` : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Link } from 'react-router';
|
||||
import type { inferRouterOutputs } from '@trpc/server';
|
||||
import type { AppRouter } from '@cockpit/api/router';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
|
||||
type Deal = inferRouterOutputs<AppRouter>['deal']['list'][number];
|
||||
|
||||
const STAGES = [
|
||||
{ key: 'lead', label: 'Lead' },
|
||||
{ key: 'erstgespraech', label: 'Erstgespräch' },
|
||||
{ key: 'demo', label: 'Demo' },
|
||||
{ key: 'angebot', label: 'Angebot' },
|
||||
{ key: 'abschluss', label: 'Abschluss' },
|
||||
] as const;
|
||||
|
||||
type Stage = (typeof STAGES)[number]['key'];
|
||||
|
||||
// valueEur wird in Cent gespeichert.
|
||||
const euro = (cents: number) =>
|
||||
new Intl.NumberFormat('de-DE', {
|
||||
style: 'currency',
|
||||
currency: 'EUR',
|
||||
maximumFractionDigits: 0,
|
||||
}).format(cents / 100);
|
||||
|
||||
export function PipelineRoute() {
|
||||
const dealsQ = trpc.deal.list.useQuery();
|
||||
const kpisQ = trpc.deal.kpis.useQuery();
|
||||
|
||||
if (dealsQ.isPending) return <SkeletonCard lines={6} />;
|
||||
if (dealsQ.isError || !dealsQ.data)
|
||||
return (
|
||||
<ErrorState
|
||||
message="Pipeline konnte nicht geladen werden."
|
||||
onRetry={() => void dealsQ.refetch()}
|
||||
/>
|
||||
);
|
||||
|
||||
const deals = dealsQ.data;
|
||||
const k = kpisQ.data;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
<Link to="/bereich/vertrieb" className="hover:underline">
|
||||
Vertrieb
|
||||
</Link>
|
||||
{' › Pipeline'}
|
||||
</p>
|
||||
<h1 className="text-3xl font-bold">Pipeline</h1>
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Deals nach Stufe. Stufe ändern verschiebt den Deal; „Abschluss“ zählt als gewonnen.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{k && (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
<KpiCard label="Gewichtete Pipeline" value={euro(k.weightedPipelineEur)} />
|
||||
<KpiCard label="Offene Deals" value={String(k.openDealCount)} />
|
||||
<KpiCard
|
||||
label="Gewonnen (Quartal)"
|
||||
value={`${euro(k.wonValueQuarterEur)} · ${k.wonCountQuarter}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deals.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
Noch keine Deals. Promote einen Lead über das Lead-Dossier („Zu Deal machen“).
|
||||
</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||
{STAGES.map((stage) => {
|
||||
const stageDeals = deals.filter((d) => d.stage === stage.key);
|
||||
const sum = stageDeals.reduce((acc, d) => acc + d.valueEur, 0);
|
||||
return (
|
||||
<div key={stage.key} className="space-y-2">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<h2 className="text-sm font-semibold">
|
||||
{stage.label}{' '}
|
||||
<span className="font-normal text-[var(--color-ink-muted)]">
|
||||
({stageDeals.length})
|
||||
</span>
|
||||
</h2>
|
||||
{sum > 0 && (
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">{euro(sum)}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{stageDeals.map((d) => (
|
||||
<DealCard key={d.id} deal={d} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KpiCard({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">{label}</p>
|
||||
<p className="mt-0.5 text-lg font-semibold">{value}</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function DealCard({ deal }: { deal: Deal }) {
|
||||
const utils = trpc.useUtils();
|
||||
const move = trpc.deal.updateStage.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.deal.list.invalidate();
|
||||
await utils.deal.kpis.invalidate();
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div className="rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white p-2.5 text-sm">
|
||||
<p className="font-medium">{deal.name}</p>
|
||||
<p className="mt-0.5 text-xs text-[var(--color-ink-muted)]">
|
||||
{euro(deal.valueEur)} · {deal.probability}%{deal.wonAt ? ' · gewonnen' : ''}
|
||||
</p>
|
||||
<label className="sr-only" htmlFor={`stage-${deal.id}`}>
|
||||
Stufe von {deal.name}
|
||||
</label>
|
||||
<select
|
||||
id={`stage-${deal.id}`}
|
||||
value={deal.stage}
|
||||
onChange={(e) => move.mutate({ dealId: deal.id, stage: e.target.value as Stage })}
|
||||
disabled={move.isPending}
|
||||
className="mt-1.5 w-full rounded-[var(--radius-sm)] border border-[var(--color-border)] bg-white px-1.5 py-1 text-xs"
|
||||
>
|
||||
{STAGES.map((s) => (
|
||||
<option key={s.key} value={s.key}>
|
||||
{s.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+2379
-69
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useNavigate, useSearchParams } from 'react-router';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { voice } from '../lib/voice';
|
||||
import { Card } from '../components/ui/Card';
|
||||
@@ -7,34 +7,63 @@ import { Button } from '../components/ui/Button';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { toast } from 'sonner';
|
||||
import { clsx } from 'clsx';
|
||||
import { Check, X, Minus, TrendingUp, TrendingDown, ArrowRight } from 'lucide-react';
|
||||
import { Check, X, Minus, TrendingUp, TrendingDown, ArrowRight, Pencil } from 'lucide-react';
|
||||
|
||||
type Ampel = 'green' | 'amber' | 'red';
|
||||
type Trend = 'besser' | 'gleich' | 'schlechter';
|
||||
type TodoStatus = 'open' | 'done' | 'dropped';
|
||||
|
||||
export function ReflexionRoute() {
|
||||
const today = trpc.dayEntry.today.useQuery();
|
||||
const [params] = useSearchParams();
|
||||
const dateParam = params.get('date') ?? undefined;
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (today.isPending) return <SkeletonCard lines={6} />;
|
||||
if (!today.data?.entry) {
|
||||
// Ohne ?date: heutige Reflexion. Mit ?date: nachträglich aus der Historie.
|
||||
const todayQ = trpc.dayEntry.today.useQuery(undefined, { enabled: !dateParam });
|
||||
const pastQ = trpc.dayEntry.ownForDate.useQuery(
|
||||
{ date: dateParam ?? '' },
|
||||
{ enabled: !!dateParam },
|
||||
);
|
||||
const active = dateParam ? pastQ : todayQ;
|
||||
|
||||
if (active.isPending) return <SkeletonCard lines={6} />;
|
||||
|
||||
const entry = active.data?.entry ?? null;
|
||||
const todos = active.data?.todos ?? [];
|
||||
const editable = dateParam ? (pastQ.data?.editable ?? false) : true;
|
||||
|
||||
if (!entry) {
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl text-center">
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Du bist heute noch nicht locked in. {voice.hint.notCheckedInToday}
|
||||
{dateParam
|
||||
? 'Für diesen Tag gibt es keinen Eintrag von dir.'
|
||||
: `Du bist heute noch nicht locked in. ${voice.hint.notCheckedInToday}`}
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => navigate('/heute')}>
|
||||
Zum Lock-in
|
||||
<Button className="mt-4" onClick={() => navigate(dateParam ? '/historie' : '/heute')}>
|
||||
{dateParam ? 'Zur Historie' : 'Zum Lock-in'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!editable) {
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl text-center">
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Dieser Tag ist älter als 3 Tage und kann nicht mehr bearbeitet werden.
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => navigate('/historie')}>
|
||||
Zur Historie
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ReflectForm
|
||||
entry={today.data.entry}
|
||||
todos={today.data.todos}
|
||||
onDone={() => navigate('/dashboard')}
|
||||
entry={entry}
|
||||
todos={todos}
|
||||
allowUnplanned={!dateParam}
|
||||
onDone={() => navigate(dateParam ? '/historie' : '/dashboard')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -42,29 +71,46 @@ export function ReflexionRoute() {
|
||||
function ReflectForm({
|
||||
entry,
|
||||
todos,
|
||||
allowUnplanned = true,
|
||||
onDone,
|
||||
}: {
|
||||
entry: { id: string };
|
||||
entry: {
|
||||
id: string;
|
||||
reflectionText?: string | null;
|
||||
ampel?: Ampel | null;
|
||||
trend?: Trend | null;
|
||||
};
|
||||
todos: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
status: TodoStatus;
|
||||
bezugKind: 'project' | 'deal' | 'campaign' | 'allgemein' | null;
|
||||
unplanned?: boolean;
|
||||
dropReason?: string | null;
|
||||
}>;
|
||||
allowUnplanned?: boolean;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const [todoStates, setTodoStates] = useState<
|
||||
Record<string, { status: TodoStatus; reason?: string }>
|
||||
>(Object.fromEntries(todos.map((t) => [t.id, { status: t.status }])));
|
||||
const [reflectionText, setReflectionText] = useState('');
|
||||
const [ampel, setAmpel] = useState<Ampel | null>(null);
|
||||
const [trend, setTrend] = useState<Trend | null>(null);
|
||||
>(Object.fromEntries(todos.map((t) => [t.id, { status: t.status, reason: t.dropReason ?? '' }])));
|
||||
const [reflectionText, setReflectionText] = useState(entry.reflectionText ?? '');
|
||||
const [ampel, setAmpel] = useState<Ampel | null>(entry.ampel ?? null);
|
||||
const [trend, setTrend] = useState<Trend | null>(entry.trend ?? null);
|
||||
const [blockerEnabled, setBlockerEnabled] = useState(false);
|
||||
const [blockerTitle, setBlockerTitle] = useState('');
|
||||
const [blockerDescription, setBlockerDescription] = useState('');
|
||||
const [unplannedTitle, setUnplannedTitle] = useState('');
|
||||
|
||||
const hasProjectBezug = todos.some((t) => t.bezugKind === 'project');
|
||||
const utils = trpc.useUtils();
|
||||
const addUnplanned = trpc.dayEntry.addUnplanned.useMutation({
|
||||
onSuccess: async () => {
|
||||
setUnplannedTitle('');
|
||||
toast('Ungeplant erledigt eingetragen.');
|
||||
await utils.dayEntry.today.invalidate();
|
||||
},
|
||||
});
|
||||
const mutation = trpc.dayEntry.submitReflection.useMutation({
|
||||
onSuccess: async () => {
|
||||
toast(voice.toast.reflected);
|
||||
@@ -77,6 +123,10 @@ function ReflectForm({
|
||||
setTodoStates((prev) => ({ ...prev, [id]: { ...prev[id], status } }));
|
||||
}
|
||||
|
||||
function setTodoReason(id: string, reason: string) {
|
||||
setTodoStates((prev) => ({ ...prev, [id]: { status: prev[id]?.status ?? 'open', reason } }));
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!ampel) {
|
||||
@@ -93,10 +143,12 @@ function ReflectForm({
|
||||
}
|
||||
mutation.mutate({
|
||||
dayEntryId: entry.id,
|
||||
todos: Object.entries(todoStates).map(([id, s]) => ({
|
||||
id,
|
||||
status: s.status,
|
||||
dropReason: s.reason,
|
||||
// Über die aktuelle ToDo-Liste mappen (nicht nur den initialen Snapshot),
|
||||
// damit mitten am Tag ergänzte ToDos ihren Status behalten.
|
||||
todos: todos.map((t) => ({
|
||||
id: t.id,
|
||||
status: todoStates[t.id]?.status ?? t.status,
|
||||
dropReason: todoStates[t.id]?.reason?.trim() || undefined,
|
||||
})),
|
||||
reflectionText,
|
||||
ampel,
|
||||
@@ -125,10 +177,16 @@ function ReflectForm({
|
||||
</p>
|
||||
<ul className="space-y-2">
|
||||
{todos.map((t) => {
|
||||
const status = todoStates[t.id]?.status ?? 'open';
|
||||
const status = todoStates[t.id]?.status ?? t.status;
|
||||
return (
|
||||
<li key={t.id} className="flex items-center gap-2">
|
||||
<span className="flex-1 text-sm">{t.title}</span>
|
||||
<li key={t.id} className="space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<EditableTodoTitle id={t.id} title={t.title} />
|
||||
{t.unplanned && (
|
||||
<span className="rounded-full bg-black/5 px-1.5 py-0.5 text-[10px] text-[var(--color-ink-muted)]">
|
||||
ungeplant
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-1">
|
||||
<StatusBtn
|
||||
active={status === 'done'}
|
||||
@@ -152,17 +210,55 @@ function ReflectForm({
|
||||
<X size={14} />
|
||||
</StatusBtn>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={todoStates[t.id]?.reason ?? ''}
|
||||
onChange={(e) => setTodoReason(t.id, e.target.value)}
|
||||
placeholder="Notiz (optional) — Ergebnis, Kontext, Link …"
|
||||
maxLength={500}
|
||||
aria-label={`Notiz zu ${t.title}`}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1 text-xs focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{allowUnplanned && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={unplannedTitle}
|
||||
onChange={(e) => setUnplannedTitle(e.target.value)}
|
||||
placeholder="Ungeplant erledigt? Hier nachtragen …"
|
||||
maxLength={200}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const v = unplannedTitle.trim();
|
||||
if (v) addUnplanned.mutate({ title: v });
|
||||
}
|
||||
}}
|
||||
className="flex-1 rounded-[var(--radius-md)] border border-dashed border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={!unplannedTitle.trim() || addUnplanned.isPending}
|
||||
onClick={() => addUnplanned.mutate({ title: unplannedTitle.trim() })}
|
||||
>
|
||||
Erledigt eintragen
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Body className="space-y-3">
|
||||
<label className="block text-sm font-medium" htmlFor="reflection">
|
||||
Sonst noch was?
|
||||
Fazit
|
||||
</label>
|
||||
<textarea
|
||||
id="reflection"
|
||||
@@ -170,6 +266,7 @@ function ReflectForm({
|
||||
onChange={(e) => setReflectionText(e.target.value)}
|
||||
maxLength={1000}
|
||||
rows={4}
|
||||
placeholder="Fasse kurz zusammen, was du heute gemacht hast."
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<p className="text-xs text-[var(--color-ink-faint)] text-right">
|
||||
@@ -269,6 +366,91 @@ function ReflectForm({
|
||||
);
|
||||
}
|
||||
|
||||
function EditableTodoTitle({ id, title }: { id: string; title: string }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(title);
|
||||
const utils = trpc.useUtils();
|
||||
const edit = trpc.dayEntry.editTodoTitle.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.dayEntry.today.invalidate();
|
||||
setEditing(false);
|
||||
},
|
||||
});
|
||||
|
||||
function save() {
|
||||
const v = draft.trim();
|
||||
if (!v || v === title) {
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
edit.mutate({ todoId: id, title: v });
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center gap-1">
|
||||
<input
|
||||
ref={(el) => el?.focus()}
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
} else if (e.key === 'Escape') {
|
||||
setDraft(title);
|
||||
setEditing(false);
|
||||
}
|
||||
}}
|
||||
maxLength={200}
|
||||
aria-label="ToDo-Titel bearbeiten"
|
||||
className="flex-1 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1 text-sm focus:border-[var(--color-ink)] focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={save}
|
||||
disabled={edit.isPending}
|
||||
aria-label="Titel speichern"
|
||||
title="Speichern"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-ink)] bg-[var(--color-ink)] text-[var(--color-brand-fg)]"
|
||||
>
|
||||
<Check size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDraft(title);
|
||||
setEditing(false);
|
||||
}}
|
||||
aria-label="Bearbeiten abbrechen"
|
||||
title="Abbrechen"
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-border-strong)]"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDraft(title);
|
||||
setEditing(true);
|
||||
}}
|
||||
title="Zum Bearbeiten klicken"
|
||||
className="group flex flex-1 items-center gap-1.5 text-left text-sm"
|
||||
>
|
||||
<span>{title}</span>
|
||||
<Pencil
|
||||
size={12}
|
||||
className="text-[var(--color-ink-faint)] opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBtn({
|
||||
active,
|
||||
onClick,
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { clsx } from 'clsx';
|
||||
import { trpc } from '../lib/trpc';
|
||||
import { Card } from '../components/ui/Card';
|
||||
import { Button } from '../components/ui/Button';
|
||||
import { SkeletonCard } from '../components/ui/SkeletonCard';
|
||||
import { ErrorState } from '../components/ui/ErrorState';
|
||||
import { formatDurationCompact } from '../lib/format-duration';
|
||||
import { TIME_CATEGORIES } from '../lib/time-categories';
|
||||
|
||||
const CATEGORY_LABEL: Record<string, string> = Object.fromEntries(
|
||||
TIME_CATEGORIES.map((c) => [c.value, c.label]),
|
||||
);
|
||||
const CATEGORY_TINT: Record<string, string> = {
|
||||
focus: 'bg-[var(--color-ink)] text-[var(--color-brand-fg)]',
|
||||
meeting: 'bg-[var(--color-ampel-amber-fg)] text-white',
|
||||
admin: 'bg-[var(--color-ink-muted)] text-white',
|
||||
learning: 'bg-[var(--color-ampel-green-fg)] text-white',
|
||||
break: 'bg-[var(--color-ink-faint)] text-white',
|
||||
other: 'bg-[var(--color-border-strong)] text-[var(--color-ink)]',
|
||||
};
|
||||
|
||||
const BAR_H = 22; // px pro Sub-Spur
|
||||
const GAP = 4;
|
||||
|
||||
const todayStr = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Berlin' }).format(new Date());
|
||||
|
||||
function shiftDay(iso: string, delta: number): string {
|
||||
const d = new Date(`${iso}T12:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + delta);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
function pad(n: number): string {
|
||||
return n.toString().padStart(2, '0');
|
||||
}
|
||||
function hhmm(ms: number): string {
|
||||
const d = new Date(ms);
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
function floorHourMs(ms: number): number {
|
||||
const d = new Date(ms);
|
||||
d.setMinutes(0, 0, 0);
|
||||
return d.getTime();
|
||||
}
|
||||
function ceilHourMs(ms: number): number {
|
||||
const d = new Date(ms);
|
||||
if (d.getMinutes() || d.getSeconds() || d.getMilliseconds()) {
|
||||
d.setHours(d.getHours() + 1, 0, 0, 0);
|
||||
}
|
||||
return d.getTime();
|
||||
}
|
||||
function formatDateLong(iso: string): string {
|
||||
return new Intl.DateTimeFormat('de-DE', {
|
||||
timeZone: 'Europe/Berlin',
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
}).format(new Date(`${iso}T12:00:00Z`));
|
||||
}
|
||||
|
||||
type RawEntry = {
|
||||
id: string;
|
||||
start: string;
|
||||
end: string | null;
|
||||
category: string;
|
||||
description: string | null;
|
||||
todoTitle: string | null;
|
||||
};
|
||||
|
||||
type Bar = {
|
||||
id: string;
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
running: boolean;
|
||||
category: string;
|
||||
label: string;
|
||||
row: number;
|
||||
};
|
||||
|
||||
// Überlappende Blöcke auf parallele Sub-Spuren verteilen.
|
||||
function layout(entries: RawEntry[], nowMs: number): { bars: Bar[]; rows: number } {
|
||||
const sorted = entries
|
||||
.map((e) => {
|
||||
const startMs = new Date(e.start).getTime();
|
||||
const running = e.end === null;
|
||||
const endMs = running ? nowMs : new Date(e.end!).getTime();
|
||||
return {
|
||||
id: e.id,
|
||||
startMs,
|
||||
endMs: Math.max(endMs, startMs + 1),
|
||||
running,
|
||||
category: e.category,
|
||||
label: e.todoTitle || e.description || CATEGORY_LABEL[e.category] || 'Eintrag',
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.startMs - b.startMs);
|
||||
|
||||
const rowEnds: number[] = [];
|
||||
const bars: Bar[] = sorted.map((e) => {
|
||||
let row = rowEnds.findIndex((end) => end <= e.startMs);
|
||||
if (row === -1) {
|
||||
row = rowEnds.length;
|
||||
rowEnds.push(e.endMs);
|
||||
} else {
|
||||
rowEnds[row] = e.endMs;
|
||||
}
|
||||
return { ...e, row };
|
||||
});
|
||||
return { bars, rows: Math.max(rowEnds.length, 1) };
|
||||
}
|
||||
|
||||
export function TeamViewRoute() {
|
||||
const [date, setDate] = useState(todayStr);
|
||||
const isToday = date === todayStr;
|
||||
const q = trpc.time.teamTimeline.useQuery(
|
||||
{ date },
|
||||
{ refetchInterval: isToday ? 30_000 : false },
|
||||
);
|
||||
|
||||
// 1-Sekunden-Tick nur heute (für laufende Balken).
|
||||
const [, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!isToday) return undefined;
|
||||
const id = window.setInterval(() => setTick((t) => t + 1), 1000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [isToday]);
|
||||
|
||||
if (q.isPending) return <SkeletonCard lines={6} />;
|
||||
if (q.isError || !q.data)
|
||||
return (
|
||||
<ErrorState
|
||||
message="Team-Ansicht konnte nicht geladen werden."
|
||||
onRetry={() => void q.refetch()}
|
||||
/>
|
||||
);
|
||||
const lanes = q.data.lanes;
|
||||
const nowMs = Date.now();
|
||||
|
||||
// Achse aus allen Einträgen bestimmen.
|
||||
const allMs: number[] = [];
|
||||
for (const lane of lanes) {
|
||||
for (const e of lane.entries) {
|
||||
allMs.push(new Date(e.start).getTime());
|
||||
allMs.push(e.end === null ? nowMs : new Date(e.end).getTime());
|
||||
}
|
||||
}
|
||||
const hasData = allMs.length > 0;
|
||||
const axisStart = hasData ? floorHourMs(Math.min(...allMs)) : floorHourMs(nowMs);
|
||||
let axisEnd = hasData ? ceilHourMs(Math.max(...allMs)) : axisStart + 2 * 3600_000;
|
||||
if (axisEnd - axisStart < 2 * 3600_000) axisEnd = axisStart + 2 * 3600_000;
|
||||
const range = axisEnd - axisStart;
|
||||
const pct = (ms: number) =>
|
||||
((Math.min(Math.max(ms, axisStart), axisEnd) - axisStart) / range) * 100;
|
||||
|
||||
const hours: number[] = [];
|
||||
for (let t = axisStart; t <= axisEnd; t += 3600_000) hours.push(t);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header>
|
||||
<h1 className="text-3xl font-bold">Team-View</h1>
|
||||
<p className="text-[var(--color-ink-muted)]">
|
||||
Wer hat wann woran gearbeitet — horizontale Tages-Timeline mit parallelen Strängen.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDate(shiftDay(date, -1))}
|
||||
aria-label="Vorheriger Tag"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-ink)] hover:text-[var(--color-ink)]"
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
</button>
|
||||
<span className="min-w-[200px] text-center font-medium">{formatDateLong(date)}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDate(shiftDay(date, 1))}
|
||||
disabled={date >= todayStr}
|
||||
aria-label="Nächster Tag"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-[var(--radius-md)] border border-[var(--color-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-ink)] hover:text-[var(--color-ink)] disabled:opacity-40 disabled:hover:border-[var(--color-border)]"
|
||||
>
|
||||
<ChevronRight size={16} />
|
||||
</button>
|
||||
<input
|
||||
type="date"
|
||||
value={date}
|
||||
max={todayStr}
|
||||
onChange={(e) => setDate(e.target.value || todayStr)}
|
||||
className="ml-2 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
{!isToday && (
|
||||
<Button size="sm" variant="ghost" onClick={() => setDate(todayStr)}>
|
||||
Heute
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lanes.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
Keine Zeiterfassung an diesem Tag.
|
||||
</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
<Card.Root>
|
||||
<Card.Body className="overflow-x-auto">
|
||||
<div className="min-w-[640px]">
|
||||
{/* Stunden-Achse */}
|
||||
<div className="flex">
|
||||
<div className="w-40 shrink-0" />
|
||||
<div className="relative h-5 flex-1">
|
||||
{hours.map((t) => (
|
||||
<span
|
||||
key={t}
|
||||
className="absolute -translate-x-1/2 text-[10px] text-[var(--color-ink-faint)]"
|
||||
style={{ left: `${pct(t)}%` }}
|
||||
>
|
||||
{pad(new Date(t).getHours())}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Spuren */}
|
||||
{lanes.map((lane) => {
|
||||
const { bars, rows } = layout(lane.entries, nowMs);
|
||||
const laneHeight = rows * BAR_H + (rows - 1) * GAP;
|
||||
return (
|
||||
<div
|
||||
key={lane.userId}
|
||||
className="flex items-stretch border-t border-[var(--color-border)] py-1.5"
|
||||
>
|
||||
<div className="flex w-40 shrink-0 flex-col justify-center pr-2">
|
||||
<span className="truncate text-sm font-medium">{lane.name}</span>
|
||||
<span className="text-[10px] text-[var(--color-ink-muted)]">
|
||||
{bars.length} {bars.length === 1 ? 'Block' : 'Blöcke'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="relative flex-1" style={{ height: laneHeight }}>
|
||||
{/* Stunden-Gitter */}
|
||||
{hours.map((t) => (
|
||||
<div
|
||||
key={t}
|
||||
className="absolute top-0 bottom-0 w-px bg-[var(--color-border)]"
|
||||
style={{ left: `${pct(t)}%` }}
|
||||
/>
|
||||
))}
|
||||
{/* Blöcke */}
|
||||
{bars.map((b) => {
|
||||
const left = pct(b.startMs);
|
||||
const width = Math.max(pct(b.endMs) - left, 0.7);
|
||||
const dur = formatDurationCompact(Math.round((b.endMs - b.startMs) / 1000));
|
||||
return (
|
||||
<div
|
||||
key={b.id}
|
||||
title={`${b.label} · ${hhmm(b.startMs)}–${b.running ? 'läuft' : hhmm(b.endMs)} (${dur})`}
|
||||
className={clsx(
|
||||
'absolute flex items-center overflow-hidden rounded-[var(--radius-sm)] px-1.5 text-[11px]',
|
||||
CATEGORY_TINT[b.category] ?? CATEGORY_TINT.other,
|
||||
b.running && 'ring-2 ring-[var(--color-ampel-red-fg)]',
|
||||
)}
|
||||
style={{
|
||||
left: `${left}%`,
|
||||
width: `${width}%`,
|
||||
top: b.row * (BAR_H + GAP),
|
||||
height: BAR_H,
|
||||
}}
|
||||
>
|
||||
<span className="truncate">{b.label}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
)}
|
||||
|
||||
{/* Legende */}
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-[var(--color-ink-muted)]">
|
||||
{TIME_CATEGORIES.map((c) => (
|
||||
<span key={c.value} className="inline-flex items-center gap-1">
|
||||
<span className={clsx('h-2.5 w-2.5 rounded-sm', CATEGORY_TINT[c.value])} />
|
||||
{c.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,9 +8,9 @@
|
||||
font-weight: 300 700;
|
||||
font-display: swap;
|
||||
src: url(/fonts/space-grotesk-latin.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6,
|
||||
U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122,
|
||||
U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
unicode-range:
|
||||
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329,
|
||||
U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Space Grotesk';
|
||||
@@ -18,9 +18,9 @@
|
||||
font-weight: 300 700;
|
||||
font-display: swap;
|
||||
src: url(/fonts/space-grotesk-latin-ext.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7,
|
||||
U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
|
||||
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,
|
||||
unicode-range:
|
||||
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329,
|
||||
U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F,
|
||||
U+A720-A7FF;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,33 @@ services:
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
# Backup-Sidecar: täglicher pg_dump des postgres-Service nach cockpit_backups.
|
||||
# Nutzt scripts/backup.sh (Custom-Format-Dump + Retention + API-Heartbeat),
|
||||
# getaktet von scripts/backup-loop.sh. Stock postgres-Image → pg_dump passt
|
||||
# versionsgenau (16) zur DB. Restore: siehe docs/operations.md.
|
||||
backup:
|
||||
image: postgres:16-alpine
|
||||
container_name: cockpit-backup
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-cockpit}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-cockpit}
|
||||
PGHOST: postgres
|
||||
API_URL: http://api:3000
|
||||
CRON_BEARER_TOKEN: ${CRON_BEARER_TOKEN}
|
||||
BACKUP_HOUR: ${BACKUP_HOUR:-03}
|
||||
BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-14}
|
||||
TZ: Europe/Berlin
|
||||
volumes:
|
||||
- cockpit_backups:/backups
|
||||
- ./scripts/backup.sh:/usr/local/bin/backup.sh:ro
|
||||
- ./scripts/backup-loop.sh:/usr/local/bin/backup-loop.sh:ro
|
||||
entrypoint: ['/bin/sh', '/usr/local/bin/backup-loop.sh']
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
|
||||
+25
-4
@@ -54,14 +54,35 @@ docker compose exec api node -e "import('@cockpit/db/client').then(async ({ crea
|
||||
|
||||
## Backups (Story 6.3)
|
||||
|
||||
Tägliches `pg_dump` via Cron-Endpoint `POST /internal/cron/pg-dump-backup` mit Bearer-Token.
|
||||
14 Tage Retention. Restore-Drill quartalsweise.
|
||||
Tägliches `pg_dump` läuft im **Backup-Sidecar** (`docker-compose.yml` service `backup`):
|
||||
`scripts/backup-loop.sh` triggert `scripts/backup.sh` einmal pro Tag um
|
||||
`BACKUP_HOUR` (Default 03:00 Europe/Berlin). Dump im **Custom-Format** (`-Fc`,
|
||||
bereits komprimiert) nach `cockpit_backups:/backups` als `cockpit-<ts>.dump`.
|
||||
Retention `BACKUP_RETENTION_DAYS` (Default 14). Nach jedem Lauf ein Heartbeat an
|
||||
`POST /internal/cron/pg-dump-backup` (nur Logging — der Endpoint macht **kein**
|
||||
Backup). Restore-Drill quartalsweise.
|
||||
|
||||
Konfiguration (optional, in `.env.production`): `BACKUP_HOUR`, `BACKUP_RETENTION_DAYS`.
|
||||
|
||||
```bash
|
||||
# Status / letztes Backup ansehen
|
||||
docker compose logs --tail=20 backup
|
||||
docker compose exec backup ls -lh /backups
|
||||
|
||||
# Sofort ein Backup auslösen (außer der Reihe)
|
||||
docker compose exec backup /usr/local/bin/backup.sh
|
||||
```
|
||||
|
||||
### Restore-Anleitung
|
||||
|
||||
1. API stoppen: `docker compose stop api`
|
||||
2. Backup aus `/backups` auswählen.
|
||||
3. Restore in temporäre DB: `docker compose exec postgres pg_restore -U cockpit -d cockpit_restore /backups/<file>.sql.gz`
|
||||
2. Backup aus `/backups` auswählen (`docker compose exec postgres ls -lh /backups`).
|
||||
3. Restore in temporäre DB:
|
||||
```bash
|
||||
docker compose exec postgres createdb -U cockpit cockpit_restore
|
||||
docker compose exec postgres pg_restore -U cockpit -d cockpit_restore /backups/<file>.dump
|
||||
```
|
||||
(In die Produktiv-DB stattdessen mit `--clean --if-exists -d cockpit`.)
|
||||
4. Smoke-Test: `curl http://localhost:3000/api/health`
|
||||
5. API wieder starten: `docker compose start api`
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
CREATE TABLE "lead" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"area_id" uuid NOT NULL,
|
||||
"firma" text NOT NULL,
|
||||
"status" text DEFAULT 'cold' NOT NULL,
|
||||
"score" integer DEFAULT 0 NOT NULL,
|
||||
"owner_user_id" uuid,
|
||||
"branche" text,
|
||||
"sub_segment" text,
|
||||
"standorte" text,
|
||||
"mitarbeiterzahl" text,
|
||||
"umsatz" text,
|
||||
"website" text,
|
||||
"quelle" text,
|
||||
"pain_point" text,
|
||||
"status_quo_kosten" text,
|
||||
"bestehende_loesung" text,
|
||||
"wechselgrund" text,
|
||||
"persoenlicher_erfolg" text,
|
||||
"budget_indikation" text,
|
||||
"entscheidungshorizont" text,
|
||||
"compelling_event" text,
|
||||
"mitbewerber" text,
|
||||
"buying_center" text,
|
||||
"beschaffungsweg" text,
|
||||
"kommunikationsstil" text,
|
||||
"vorlieben" text,
|
||||
"hot_buttons" text,
|
||||
"no_gos" text,
|
||||
"druckpunkte" text,
|
||||
"anker" text,
|
||||
"vertrauenslevel" integer,
|
||||
"nutzen_hypothese" text,
|
||||
"differenzierer" text,
|
||||
"naechster_schritt" text,
|
||||
"naechster_schritt_datum" date,
|
||||
"risiken" text,
|
||||
"plan_b" text,
|
||||
"offene_fragen" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"anhaenge" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"promoted_deal_id" uuid,
|
||||
"created_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "lead_contact" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"lead_id" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"rolle" text,
|
||||
"funktion" text,
|
||||
"email" text,
|
||||
"telefon" text,
|
||||
"linkedin" text,
|
||||
"im_buying_center_seit" text,
|
||||
"sprache" text,
|
||||
"is_primary" boolean DEFAULT false NOT NULL,
|
||||
"order" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "lead_touchpoint" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"lead_id" uuid NOT NULL,
|
||||
"datum" date NOT NULL,
|
||||
"kanal" text NOT NULL,
|
||||
"bearbeiter_user_id" uuid,
|
||||
"inhalt" text NOT NULL,
|
||||
"outcome" text,
|
||||
"follow_up_bis" date,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "lead" ADD CONSTRAINT "lead_area_id_area_id_fk" FOREIGN KEY ("area_id") REFERENCES "public"."area"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead" ADD CONSTRAINT "lead_owner_user_id_user_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead" ADD CONSTRAINT "lead_promoted_deal_id_deal_id_fk" FOREIGN KEY ("promoted_deal_id") REFERENCES "public"."deal"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead" ADD CONSTRAINT "lead_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead_contact" ADD CONSTRAINT "lead_contact_lead_id_lead_id_fk" FOREIGN KEY ("lead_id") REFERENCES "public"."lead"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead_touchpoint" ADD CONSTRAINT "lead_touchpoint_lead_id_lead_id_fk" FOREIGN KEY ("lead_id") REFERENCES "public"."lead"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "lead_touchpoint" ADD CONSTRAINT "lead_touchpoint_bearbeiter_user_id_user_id_fk" FOREIGN KEY ("bearbeiter_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_status" ON "lead" USING btree ("status");--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_owner" ON "lead" USING btree ("owner_user_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_contact_lead" ON "lead_contact" USING btree ("lead_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_touchpoint_lead" ON "lead_touchpoint" USING btree ("lead_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_touchpoint_followup" ON "lead_touchpoint" USING btree ("follow_up_bis");
|
||||
@@ -0,0 +1,40 @@
|
||||
CREATE TABLE "risk" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"kind" text DEFAULT 'risiko' NOT NULL,
|
||||
"title" text NOT NULL,
|
||||
"wahrscheinlichkeit" text DEFAULT 'mittel' NOT NULL,
|
||||
"auswirkung" text DEFAULT 'mittel' NOT NULL,
|
||||
"herkunft" text,
|
||||
"showstopper" boolean DEFAULT false NOT NULL,
|
||||
"massnahme" text,
|
||||
"status" text DEFAULT 'offen' NOT NULL,
|
||||
"created_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "stakeholder" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"rolle" text,
|
||||
"interesse" text DEFAULT 'mittel' NOT NULL,
|
||||
"einfluss" text DEFAULT 'mittel' NOT NULL,
|
||||
"haltung" text DEFAULT 'neutral' NOT NULL,
|
||||
"beduerfnis" text,
|
||||
"notiz" text,
|
||||
"order" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "milestone" ADD COLUMN "ergebnis" text;--> statement-breakpoint
|
||||
ALTER TABLE "milestone" ADD COLUMN "kundennutzen" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "maxime" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "modus" text DEFAULT 'standard' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "risk" ADD CONSTRAINT "risk_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "risk" ADD CONSTRAINT "risk_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "stakeholder" ADD CONSTRAINT "stakeholder_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "idx_risk_project" ON "risk" USING btree ("project_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_risk_showstopper" ON "risk" USING btree ("showstopper");--> statement-breakpoint
|
||||
CREATE INDEX "idx_stakeholder_project" ON "stakeholder" USING btree ("project_id");
|
||||
@@ -0,0 +1,49 @@
|
||||
CREATE TABLE "change_entry" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"titel" text NOT NULL,
|
||||
"auswirkung" text,
|
||||
"entscheidung" text DEFAULT 'offen' NOT NULL,
|
||||
"created_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "phase_gate" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"phase" text NOT NULL,
|
||||
"ergebnis_erreicht" boolean NOT NULL,
|
||||
"notiz" text,
|
||||
"reviewed_by" uuid,
|
||||
"reviewed_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "project_status" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"ampel" text NOT NULL,
|
||||
"trend" text,
|
||||
"text" text,
|
||||
"extern_sichtbar" boolean DEFAULT false NOT NULL,
|
||||
"created_by" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "ziel" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "nicht_ziele" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "liefergegenstaende" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "zieldreieck_flex" text;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "phase" text DEFAULT 'definition' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "project" ADD COLUMN "abschlussvermerk" text;--> statement-breakpoint
|
||||
ALTER TABLE "risk" ADD COLUMN "strategie" text;--> statement-breakpoint
|
||||
ALTER TABLE "risk" ADD COLUMN "owner_user_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "change_entry" ADD CONSTRAINT "change_entry_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "change_entry" ADD CONSTRAINT "change_entry_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "phase_gate" ADD CONSTRAINT "phase_gate_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "phase_gate" ADD CONSTRAINT "phase_gate_reviewed_by_user_id_fk" FOREIGN KEY ("reviewed_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "project_status" ADD CONSTRAINT "project_status_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "project_status" ADD CONSTRAINT "project_status_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "idx_change_entry_project" ON "change_entry" USING btree ("project_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_phase_gate_project" ON "phase_gate" USING btree ("project_id");--> statement-breakpoint
|
||||
CREATE INDEX "idx_project_status_project" ON "project_status" USING btree ("project_id");--> statement-breakpoint
|
||||
ALTER TABLE "risk" ADD CONSTRAINT "risk_owner_user_id_user_id_fk" FOREIGN KEY ("owner_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "lead" ADD COLUMN "project_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "lead" ADD CONSTRAINT "lead_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "idx_lead_project" ON "lead" USING btree ("project_id");
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "todo" ADD COLUMN "unplanned" boolean DEFAULT false NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP INDEX "uniq_time_entry_user_active";--> statement-breakpoint
|
||||
CREATE INDEX "idx_time_entry_user_active" ON "time_entry" USING btree ("user_id") WHERE "time_entry"."ended_at" IS NULL;
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE "day_entry" ADD COLUMN "checked_out_at" timestamp with time zone;--> statement-breakpoint
|
||||
ALTER TABLE "day_entry" ADD COLUMN "kimai_timesheet_id" integer;--> statement-breakpoint
|
||||
ALTER TABLE "day_entry" ADD COLUMN "kimai_synced" boolean DEFAULT false NOT NULL;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Daten-Migration: ehemalige Pausen entfernen. Das Pause-Feature wurde
|
||||
-- abgeschafft (Lücken zwischen Tasks = Pause); alte 'break'-Einträge sollen
|
||||
-- nicht mehr als graue Blöcke in der Timeline erscheinen.
|
||||
DELETE FROM "time_entry" WHERE "category" = 'break';
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "project" ADD COLUMN "logo_url" text;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Verwaiste Verweise vor dem Setzen der Foreign Keys auf NULL bereinigen — sonst
|
||||
-- schlaegt ADD CONSTRAINT fehl, falls Altdaten auf geloeschte Zeilen zeigen.
|
||||
UPDATE "blocker" SET "area_id" = NULL WHERE "area_id" IS NOT NULL AND "area_id" NOT IN (SELECT "id" FROM "area");--> statement-breakpoint
|
||||
UPDATE "blocker" SET "project_id" = NULL WHERE "project_id" IS NOT NULL AND "project_id" NOT IN (SELECT "id" FROM "project");--> statement-breakpoint
|
||||
UPDATE "day_entry" SET "blocker_id" = NULL WHERE "blocker_id" IS NOT NULL AND "blocker_id" NOT IN (SELECT "id" FROM "blocker");--> statement-breakpoint
|
||||
ALTER TABLE "blocker" ADD CONSTRAINT "blocker_area_id_area_id_fk" FOREIGN KEY ("area_id") REFERENCES "public"."area"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "blocker" ADD CONSTRAINT "blocker_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "day_entry" ADD CONSTRAINT "day_entry_blocker_id_blocker_id_fk" FOREIGN KEY ("blocker_id") REFERENCES "public"."blocker"("id") ON DELETE set null ON UPDATE no action;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "project" ADD COLUMN "lessons_learned" jsonb;
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE "day_entry" ADD COLUMN "auto_checked_in" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
UPDATE "day_entry" SET "auto_checked_in" = true
|
||||
WHERE "checked_in_at" IS NOT NULL
|
||||
AND ("checked_in_at" AT TIME ZONE 'Europe/Berlin')::time = TIME '06:00:00';
|
||||
@@ -69,12 +69,8 @@
|
||||
"name": "absence_day_user_id_user_id_fk",
|
||||
"tableFrom": "absence_day",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -261,12 +257,8 @@
|
||||
"name": "audit_event_actor_user_id_user_id_fk",
|
||||
"tableFrom": "audit_event",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"actor_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["actor_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -402,12 +394,8 @@
|
||||
"name": "blocker_owner_user_id_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -415,12 +403,8 @@
|
||||
"name": "blocker_opened_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"opened_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["opened_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -428,12 +412,8 @@
|
||||
"name": "blocker_resolved_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"resolved_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["resolved_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -517,12 +497,8 @@
|
||||
"name": "campaign_area_id_area_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -530,12 +506,8 @@
|
||||
"name": "campaign_owner_user_id_user_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -702,12 +674,8 @@
|
||||
"name": "day_entry_user_id_user_id_fk",
|
||||
"tableFrom": "day_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -831,12 +799,8 @@
|
||||
"name": "deal_area_id_area_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -844,12 +808,8 @@
|
||||
"name": "deal_owner_user_id_user_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -933,12 +893,8 @@
|
||||
"name": "gtm_step_owner_user_id_user_id_fk",
|
||||
"tableFrom": "gtm_step",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -992,12 +948,8 @@
|
||||
"name": "lead_handover_campaign_id_campaign_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "campaign",
|
||||
"columnsFrom": [
|
||||
"campaign_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["campaign_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1005,12 +957,8 @@
|
||||
"name": "lead_handover_deal_id_deal_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "deal",
|
||||
"columnsFrom": [
|
||||
"deal_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["deal_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1018,12 +966,8 @@
|
||||
"name": "lead_handover_uebergeben_von_user_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"uebergeben_von"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["uebergeben_von"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1113,12 +1057,8 @@
|
||||
"name": "milestone_project_id_project_id_fk",
|
||||
"tableFrom": "milestone",
|
||||
"tableTo": "project",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["project_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1309,12 +1249,8 @@
|
||||
"name": "project_area_id_area_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1322,12 +1258,8 @@
|
||||
"name": "project_verantwortliche_user_id_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"verantwortliche_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["verantwortliche_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1335,12 +1267,8 @@
|
||||
"name": "project_created_by_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["created_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1431,12 +1359,8 @@
|
||||
"name": "session_user_id_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1577,12 +1501,8 @@
|
||||
"name": "todo_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1590,12 +1510,8 @@
|
||||
"name": "todo_user_id_user_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
|
||||
@@ -69,12 +69,8 @@
|
||||
"name": "absence_day_user_id_user_id_fk",
|
||||
"tableFrom": "absence_day",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -261,12 +257,8 @@
|
||||
"name": "audit_event_actor_user_id_user_id_fk",
|
||||
"tableFrom": "audit_event",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"actor_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["actor_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -402,12 +394,8 @@
|
||||
"name": "blocker_owner_user_id_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -415,12 +403,8 @@
|
||||
"name": "blocker_opened_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"opened_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["opened_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -428,12 +412,8 @@
|
||||
"name": "blocker_resolved_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"resolved_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["resolved_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -517,12 +497,8 @@
|
||||
"name": "campaign_area_id_area_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -530,12 +506,8 @@
|
||||
"name": "campaign_owner_user_id_user_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -702,12 +674,8 @@
|
||||
"name": "day_entry_user_id_user_id_fk",
|
||||
"tableFrom": "day_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -831,12 +799,8 @@
|
||||
"name": "deal_area_id_area_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -844,12 +808,8 @@
|
||||
"name": "deal_owner_user_id_user_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -933,12 +893,8 @@
|
||||
"name": "gtm_step_owner_user_id_user_id_fk",
|
||||
"tableFrom": "gtm_step",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -992,12 +948,8 @@
|
||||
"name": "lead_handover_campaign_id_campaign_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "campaign",
|
||||
"columnsFrom": [
|
||||
"campaign_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["campaign_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1005,12 +957,8 @@
|
||||
"name": "lead_handover_deal_id_deal_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "deal",
|
||||
"columnsFrom": [
|
||||
"deal_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["deal_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1018,12 +966,8 @@
|
||||
"name": "lead_handover_uebergeben_von_user_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"uebergeben_von"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["uebergeben_von"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1113,12 +1057,8 @@
|
||||
"name": "milestone_project_id_project_id_fk",
|
||||
"tableFrom": "milestone",
|
||||
"tableTo": "project",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["project_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1309,12 +1249,8 @@
|
||||
"name": "project_area_id_area_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1322,12 +1258,8 @@
|
||||
"name": "project_verantwortliche_user_id_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"verantwortliche_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["verantwortliche_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1335,12 +1267,8 @@
|
||||
"name": "project_created_by_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["created_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1431,12 +1359,8 @@
|
||||
"name": "session_user_id_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1611,12 +1535,8 @@
|
||||
"name": "todo_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1624,12 +1544,8 @@
|
||||
"name": "todo_user_id_user_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
|
||||
@@ -69,12 +69,8 @@
|
||||
"name": "absence_day_user_id_user_id_fk",
|
||||
"tableFrom": "absence_day",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -261,12 +257,8 @@
|
||||
"name": "audit_event_actor_user_id_user_id_fk",
|
||||
"tableFrom": "audit_event",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"actor_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["actor_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -402,12 +394,8 @@
|
||||
"name": "blocker_owner_user_id_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -415,12 +403,8 @@
|
||||
"name": "blocker_opened_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"opened_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["opened_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -428,12 +412,8 @@
|
||||
"name": "blocker_resolved_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"resolved_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["resolved_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -517,12 +497,8 @@
|
||||
"name": "campaign_area_id_area_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -530,12 +506,8 @@
|
||||
"name": "campaign_owner_user_id_user_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -702,12 +674,8 @@
|
||||
"name": "day_entry_user_id_user_id_fk",
|
||||
"tableFrom": "day_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -831,12 +799,8 @@
|
||||
"name": "deal_area_id_area_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -844,12 +808,8 @@
|
||||
"name": "deal_owner_user_id_user_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -933,12 +893,8 @@
|
||||
"name": "gtm_step_owner_user_id_user_id_fk",
|
||||
"tableFrom": "gtm_step",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -992,12 +948,8 @@
|
||||
"name": "lead_handover_campaign_id_campaign_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "campaign",
|
||||
"columnsFrom": [
|
||||
"campaign_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["campaign_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1005,12 +957,8 @@
|
||||
"name": "lead_handover_deal_id_deal_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "deal",
|
||||
"columnsFrom": [
|
||||
"deal_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["deal_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1018,12 +966,8 @@
|
||||
"name": "lead_handover_uebergeben_von_user_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"uebergeben_von"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["uebergeben_von"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1113,12 +1057,8 @@
|
||||
"name": "milestone_project_id_project_id_fk",
|
||||
"tableFrom": "milestone",
|
||||
"tableTo": "project",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["project_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1309,12 +1249,8 @@
|
||||
"name": "project_area_id_area_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1322,12 +1258,8 @@
|
||||
"name": "project_verantwortliche_user_id_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"verantwortliche_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["verantwortliche_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1335,12 +1267,8 @@
|
||||
"name": "project_created_by_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["created_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1431,12 +1359,8 @@
|
||||
"name": "session_user_id_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1593,12 +1517,8 @@
|
||||
"name": "time_entry_user_id_user_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1606,12 +1526,8 @@
|
||||
"name": "time_entry_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1619,12 +1535,8 @@
|
||||
"name": "time_entry_todo_id_todo_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "todo",
|
||||
"columnsFrom": [
|
||||
"todo_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["todo_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1799,12 +1711,8 @@
|
||||
"name": "todo_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1812,12 +1720,8 @@
|
||||
"name": "todo_user_id_user_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
|
||||
@@ -69,12 +69,8 @@
|
||||
"name": "absence_day_user_id_user_id_fk",
|
||||
"tableFrom": "absence_day",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -261,12 +257,8 @@
|
||||
"name": "audit_event_actor_user_id_user_id_fk",
|
||||
"tableFrom": "audit_event",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"actor_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["actor_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -402,12 +394,8 @@
|
||||
"name": "blocker_owner_user_id_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -415,12 +403,8 @@
|
||||
"name": "blocker_opened_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"opened_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["opened_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -428,12 +412,8 @@
|
||||
"name": "blocker_resolved_by_user_id_fk",
|
||||
"tableFrom": "blocker",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"resolved_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["resolved_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -517,12 +497,8 @@
|
||||
"name": "campaign_area_id_area_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -530,12 +506,8 @@
|
||||
"name": "campaign_owner_user_id_user_id_fk",
|
||||
"tableFrom": "campaign",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -702,12 +674,8 @@
|
||||
"name": "day_entry_user_id_user_id_fk",
|
||||
"tableFrom": "day_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -831,12 +799,8 @@
|
||||
"name": "deal_area_id_area_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -844,12 +808,8 @@
|
||||
"name": "deal_owner_user_id_user_id_fk",
|
||||
"tableFrom": "deal",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -933,12 +893,8 @@
|
||||
"name": "gtm_step_owner_user_id_user_id_fk",
|
||||
"tableFrom": "gtm_step",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"owner_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["owner_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -992,12 +948,8 @@
|
||||
"name": "lead_handover_campaign_id_campaign_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "campaign",
|
||||
"columnsFrom": [
|
||||
"campaign_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["campaign_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1005,12 +957,8 @@
|
||||
"name": "lead_handover_deal_id_deal_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "deal",
|
||||
"columnsFrom": [
|
||||
"deal_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["deal_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1018,12 +966,8 @@
|
||||
"name": "lead_handover_uebergeben_von_user_id_fk",
|
||||
"tableFrom": "lead_handover",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"uebergeben_von"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["uebergeben_von"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1113,12 +1057,8 @@
|
||||
"name": "milestone_project_id_project_id_fk",
|
||||
"tableFrom": "milestone",
|
||||
"tableTo": "project",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["project_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1315,12 +1255,8 @@
|
||||
"name": "project_area_id_area_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "area",
|
||||
"columnsFrom": [
|
||||
"area_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["area_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "restrict",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1328,12 +1264,8 @@
|
||||
"name": "project_verantwortliche_user_id_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"verantwortliche_user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["verantwortliche_user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1341,12 +1273,8 @@
|
||||
"name": "project_created_by_user_id_fk",
|
||||
"tableFrom": "project",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"created_by"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["created_by"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1437,12 +1365,8 @@
|
||||
"name": "session_user_id_user_id_fk",
|
||||
"tableFrom": "session",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1599,12 +1523,8 @@
|
||||
"name": "time_entry_user_id_user_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1612,12 +1532,8 @@
|
||||
"name": "time_entry_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1625,12 +1541,8 @@
|
||||
"name": "time_entry_todo_id_todo_id_fk",
|
||||
"tableFrom": "time_entry",
|
||||
"tableTo": "todo",
|
||||
"columnsFrom": [
|
||||
"todo_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["todo_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
@@ -1805,12 +1717,8 @@
|
||||
"name": "todo_day_entry_id_day_entry_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "day_entry",
|
||||
"columnsFrom": [
|
||||
"day_entry_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["day_entry_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
@@ -1818,12 +1726,8 @@
|
||||
"name": "todo_user_id_user_id_fk",
|
||||
"tableFrom": "todo",
|
||||
"tableTo": "user",
|
||||
"columnsFrom": [
|
||||
"user_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"columnsFrom": ["user_id"],
|
||||
"columnsTo": ["id"],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -57,6 +57,90 @@
|
||||
"when": 1780415208906,
|
||||
"tag": "0007_project_description",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "7",
|
||||
"when": 1780577284868,
|
||||
"tag": "0008_lead_crm",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 9,
|
||||
"version": "7",
|
||||
"when": 1780669990802,
|
||||
"tag": "0009_pm_insights",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 10,
|
||||
"version": "7",
|
||||
"when": 1780672129310,
|
||||
"tag": "0010_leitfaden_phases",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 11,
|
||||
"version": "7",
|
||||
"when": 1780754557002,
|
||||
"tag": "0011_lead_project_link",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 12,
|
||||
"version": "7",
|
||||
"when": 1780761840614,
|
||||
"tag": "0012_todo_unplanned",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 13,
|
||||
"version": "7",
|
||||
"when": 1780763141548,
|
||||
"tag": "0013_parallel_timers",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 14,
|
||||
"version": "7",
|
||||
"when": 1780764129593,
|
||||
"tag": "0014_checkout_kimai",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 15,
|
||||
"version": "7",
|
||||
"when": 1780765384409,
|
||||
"tag": "0015_delete_break_entries",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 16,
|
||||
"version": "7",
|
||||
"when": 1780771242601,
|
||||
"tag": "0016_project_logo_url",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 17,
|
||||
"version": "7",
|
||||
"when": 1780826387755,
|
||||
"tag": "0017_rare_oracle",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 18,
|
||||
"version": "7",
|
||||
"when": 1780828837324,
|
||||
"tag": "0018_last_lake",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 19,
|
||||
"version": "7",
|
||||
"when": 1781259091924,
|
||||
"tag": "0019_shocking_starbolt",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||
import pg from 'pg';
|
||||
import { area } from './schema.js';
|
||||
|
||||
// Fachliche Basis-Bereiche — Referenzdaten, die jede Instanz braucht (auch Prod,
|
||||
// die nicht geseedet wird). Werden idempotent beim API-Start sichergestellt.
|
||||
export const BASE_AREAS = [
|
||||
{ slug: 'entwicklung', name: 'Entwicklung', kind: 'dev' as const, order: 1 },
|
||||
{ slug: 'vertrieb', name: 'Vertrieb', kind: 'sales' as const, order: 2 },
|
||||
{ slug: 'marketing', name: 'Marketing', kind: 'marketing' as const, order: 3 },
|
||||
{ slug: 'allgemein', name: 'Allgemein', kind: 'allgemein' as const, order: 99 },
|
||||
];
|
||||
|
||||
/**
|
||||
* Legt die Basis-Bereiche an, falls sie fehlen. Idempotent (ON CONFLICT DO
|
||||
* NOTHING auf slug). Wird beim API-Start nach den Migrationen aufgerufen, damit
|
||||
* z. B. der „Neues Projekt"-Bereich-Dropdown nie leer ist.
|
||||
*/
|
||||
export async function ensureBaseAreas(connectionString: string): Promise<void> {
|
||||
const pool = new pg.Pool({ connectionString, max: 1 });
|
||||
try {
|
||||
const db = drizzle(pool);
|
||||
await db.insert(area).values(BASE_AREAS).onConflictDoNothing();
|
||||
} finally {
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export * from './schema.js';
|
||||
export { createDbClient } from './client.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
export { ensureBaseAreas, BASE_AREAS } from './base-data.js';
|
||||
export type { Db, CreateDbClientOptions } from './client.js';
|
||||
|
||||
export const DB_VERSION = '0.0.1';
|
||||
@@ -0,0 +1,31 @@
|
||||
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||
import { migrate } from 'drizzle-orm/node-postgres/migrator';
|
||||
import pg from 'pg';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Wendet alle ausstehenden Drizzle-Migrationen aus `packages/db/migrations` an.
|
||||
* Idempotent: Drizzle führt Buch über bereits eingespielte Migrationen in
|
||||
* `__drizzle_migrations` und überspringt sie. Wird beim API-Start aufgerufen,
|
||||
* damit ein Deploy automatisch das Schema aktualisiert.
|
||||
*
|
||||
* Der Migrations-Ordner liegt eine Ebene über dieser Datei — funktioniert
|
||||
* sowohl für die kompilierte Variante (`dist/migrate.js` → `../migrations`)
|
||||
* als auch im Dev-Modus (`src/migrate.ts` → `../migrations`).
|
||||
*/
|
||||
export async function runMigrations(connectionString: string): Promise<void> {
|
||||
const migrationsFolder = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
'..',
|
||||
'migrations',
|
||||
);
|
||||
|
||||
const pool = new pg.Pool({ connectionString, max: 1 });
|
||||
try {
|
||||
const db = drizzle(pool);
|
||||
await migrate(db, { migrationsFolder });
|
||||
} finally {
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user