Compare commits
27
Commits
b39c67d1aa
...
b340b45110
No files matched your search
@@ -17,6 +17,11 @@ 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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
previousWerktag,
|
||||
werktageBetween,
|
||||
berlinDayStartMs,
|
||||
addCalendarDays,
|
||||
workdayCutoffMs,
|
||||
isWorkdaySealed,
|
||||
isEditableWithinGrace,
|
||||
} from './werktag';
|
||||
|
||||
describe('werktag', () => {
|
||||
@@ -41,4 +45,50 @@ describe('werktag', () => {
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,14 @@ 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.
|
||||
*/
|
||||
@@ -12,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,
|
||||
@@ -40,7 +87,14 @@ export function berlinDayStartMs(iso: string): number {
|
||||
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 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;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ 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(() => ({
|
||||
@@ -34,6 +35,7 @@ export const appRouter = router({
|
||||
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(),
|
||||
|
||||
@@ -1,11 +1,124 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { and, eq, isNull, lt, asc, desc, inArray } from 'drizzle-orm';
|
||||
import { dayEntry, todo, blocker, user, 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, previousWerktag, nextWerktag } 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 })
|
||||
.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({
|
||||
/**
|
||||
* Heutige ToDos aller aktiven Mitarbeiter, gruppiert pro User.
|
||||
@@ -14,11 +127,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()
|
||||
@@ -65,25 +176,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 };
|
||||
}),
|
||||
|
||||
/**
|
||||
@@ -92,6 +200,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.
|
||||
@@ -181,24 +291,25 @@ export const dayEntryRouter = router({
|
||||
}),
|
||||
|
||||
/**
|
||||
* Check-Out / Arbeitsende: markiert das Ende der Arbeits-Session. Best-effort
|
||||
* 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 date = todayIso();
|
||||
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), eq(dayEntry.date, date)))
|
||||
.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 heute noch nicht locked in.' });
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Du bist gerade nicht eingestempelt.' });
|
||||
}
|
||||
if (entry.checkedOutAt) return entry;
|
||||
|
||||
const now = new Date();
|
||||
const [updated] = await ctx.db
|
||||
.update(dayEntry)
|
||||
.set({ checkedOutAt: now, updatedAt: now })
|
||||
@@ -211,6 +322,46 @@ export const dayEntryRouter = router({
|
||||
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).
|
||||
*/
|
||||
@@ -257,8 +408,8 @@ export const dayEntryRouter = router({
|
||||
|
||||
/**
|
||||
* Einzelnen ToDo-Titel korrigieren (z. B. Tippfehler) — auch noch in der
|
||||
* Reflexion. Erlaubt, solange das ToDo der eigenen Person gehört und vom
|
||||
* heutigen Berlin-Tag ist (gleiche Editierbarkeits-Regel wie die Reflexion).
|
||||
* 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)
|
||||
@@ -272,10 +423,10 @@ export const dayEntryRouter = router({
|
||||
if (!existing) {
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'ToDo nicht gefunden.' });
|
||||
}
|
||||
if (existing.date !== todayIso(new Date())) {
|
||||
if (!isEditableWithinGrace(existing.date, new Date())) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'ToDos eines Vortags können nicht mehr bearbeitet werden.',
|
||||
message: 'ToDos können nur bis 3 Tage nach dem Tag bearbeitet werden.',
|
||||
});
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
@@ -293,18 +444,11 @@ export const dayEntryRouter = router({
|
||||
addTodo: protectedProcedure
|
||||
.input(DayEntrySchemas.addTodoInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const date = todayIso();
|
||||
const entry = (
|
||||
await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), eq(dayEntry.date, date)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, new Date());
|
||||
if (!entry) {
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Du bist heute noch nicht locked in.',
|
||||
message: 'Du bist gerade nicht eingestempelt.',
|
||||
});
|
||||
}
|
||||
const existing = await ctx.db
|
||||
@@ -334,16 +478,12 @@ export const dayEntryRouter = router({
|
||||
addUnplanned: protectedProcedure
|
||||
.input(DayEntrySchemas.addUnplannedInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const date = todayIso();
|
||||
const entry = (
|
||||
await ctx.db
|
||||
.select()
|
||||
.from(dayEntry)
|
||||
.where(and(eq(dayEntry.userId, ctx.user.id), eq(dayEntry.date, date)))
|
||||
.limit(1)
|
||||
)[0];
|
||||
const entry = await getActiveEntry(ctx.db, ctx.user.id, new Date());
|
||||
if (!entry) {
|
||||
throw new TRPCError({ code: 'BAD_REQUEST', message: 'Du bist heute noch nicht locked in.' });
|
||||
throw new TRPCError({
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Du bist gerade nicht eingestempelt.',
|
||||
});
|
||||
}
|
||||
const existing = await ctx.db
|
||||
.select({ id: todo.id })
|
||||
@@ -382,13 +522,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.',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -479,7 +618,18 @@ export const dayEntryRouter = router({
|
||||
.input(DayEntrySchemas.historyForDateInput)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const today = todayIso();
|
||||
const date = input.date ?? previousWerktag(today);
|
||||
// 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));
|
||||
@@ -491,7 +641,11 @@ export const dayEntryRouter = router({
|
||||
|
||||
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))
|
||||
? 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) {
|
||||
@@ -526,11 +680,28 @@ export const dayEntryRouter = router({
|
||||
.map((u) => u.name)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const nw = nextWerktag(date);
|
||||
// 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: previousWerktag(date),
|
||||
nextDate: nw < today ? nw : null,
|
||||
prevDate: prevRow?.d ?? null,
|
||||
nextDate: nextRow?.d ?? null,
|
||||
entries: list,
|
||||
ohneEintrag,
|
||||
};
|
||||
@@ -550,11 +721,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();
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { asc, desc, eq, sql } from 'drizzle-orm';
|
||||
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';
|
||||
|
||||
@@ -30,6 +31,35 @@ export const leadRouter = router({
|
||||
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)
|
||||
@@ -61,11 +91,13 @@ export const leadRouter = router({
|
||||
.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
|
||||
? ((
|
||||
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,
|
||||
@@ -75,58 +107,55 @@ export const leadRouter = router({
|
||||
};
|
||||
}),
|
||||
|
||||
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;
|
||||
}),
|
||||
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;
|
||||
}),
|
||||
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 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({
|
||||
@@ -222,7 +251,13 @@ export const leadRouter = router({
|
||||
.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 };
|
||||
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);
|
||||
@@ -243,7 +278,8 @@ export const leadRouter = router({
|
||||
branche: col('branche'),
|
||||
notizen: col('notizen'),
|
||||
};
|
||||
const get = (row: string[], i: number) => (i >= 0 && i < row.length ? (row[i] ?? '').trim() : '');
|
||||
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()));
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import { TRPCError } from '@trpc/server';
|
||||
import { z } from 'zod';
|
||||
import { and, eq, desc } from 'drizzle-orm';
|
||||
import { project, milestone, area, user, projectStatus, phaseGate, 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] {
|
||||
@@ -108,7 +116,7 @@ export const projectRouter = router({
|
||||
return result;
|
||||
}),
|
||||
|
||||
archive: protectedProcedure
|
||||
archive: auditedProcedure('project.archive')
|
||||
.input(ProjectSchemas.archiveProjectInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const p = (
|
||||
@@ -129,6 +137,7 @@ export const projectRouter = router({
|
||||
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))
|
||||
@@ -137,7 +146,7 @@ export const projectRouter = router({
|
||||
}),
|
||||
|
||||
// Phase direkt setzen (Leitfaden Kap. 2).
|
||||
setPhase: protectedProcedure
|
||||
setPhase: auditedProcedure('project.setPhase')
|
||||
.input(ProjectSchemas.setPhaseInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [updated] = await ctx.db
|
||||
@@ -150,7 +159,7 @@ export const projectRouter = router({
|
||||
}),
|
||||
|
||||
// Gate-Review am Phasenende (Leitfaden Kap. 5), optional Folgephase freigeben.
|
||||
addPhaseGate: protectedProcedure
|
||||
addPhaseGate: auditedProcedure('project.addPhaseGate')
|
||||
.input(ProjectSchemas.addPhaseGateInput)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [gate] = await ctx.db
|
||||
@@ -258,7 +267,8 @@ export const projectRouter = router({
|
||||
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.' });
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Projekt nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
@@ -312,7 +322,8 @@ export const projectRouter = router({
|
||||
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.' });
|
||||
if (!existing)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Meilenstein nicht gefunden.' });
|
||||
return existing;
|
||||
}
|
||||
const [updated] = await ctx.db
|
||||
@@ -320,7 +331,8 @@ export const projectRouter = router({
|
||||
.set(patch)
|
||||
.where(eq(milestone.id, milestoneId))
|
||||
.returning();
|
||||
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Meilenstein nicht gefunden.' });
|
||||
if (!updated)
|
||||
throw new TRPCError({ code: 'NOT_FOUND', message: 'Meilenstein nicht gefunden.' });
|
||||
return updated;
|
||||
}),
|
||||
|
||||
|
||||
@@ -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 })),
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -44,7 +44,10 @@ function unionSeconds(intervals: Array<readonly [number, number]>): number {
|
||||
}
|
||||
|
||||
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 durationSeconds = Math.max(
|
||||
0,
|
||||
Math.round((now.getTime() - entry.startedAt.getTime()) / 1000),
|
||||
);
|
||||
const [stopped] = await db
|
||||
.update(timeEntry)
|
||||
.set({ endedAt: now, durationSeconds, updatedAt: now })
|
||||
@@ -199,7 +202,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;
|
||||
@@ -211,8 +218,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))
|
||||
@@ -368,7 +374,9 @@ export const timeRouter = router({
|
||||
.where(cond)
|
||||
.orderBy(asc(timeEntry.startedAt));
|
||||
|
||||
const todoIds = Array.from(new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)));
|
||||
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
|
||||
@@ -412,4 +420,38 @@ export const timeRouter = router({
|
||||
|
||||
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 };
|
||||
}),
|
||||
});
|
||||
+26
-21
@@ -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,
|
||||
action,
|
||||
entityKind: action.split('.')[0] ?? 'unknown',
|
||||
payload: { input: opts.input as unknown },
|
||||
});
|
||||
/**
|
||||
* 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: (rawInput ?? null) as unknown },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn({ err, action }, 'audit_event konnte nicht geschrieben werden');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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>
|
||||
<Router />
|
||||
<Toaster position="bottom-right" richColors={false} />
|
||||
<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,49 +24,40 @@ 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>
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Was klemmt?</span>
|
||||
<input
|
||||
required
|
||||
ref={(el) => {
|
||||
if (el && !title) el.focus();
|
||||
}}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
maxLength={200}
|
||||
className="mt-1 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Mehr Kontext (optional)</span>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
className="mt-1 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Erstellen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<input
|
||||
required
|
||||
ref={(el) => {
|
||||
if (el && !title) el.focus();
|
||||
}}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
maxLength={200}
|
||||
className="mt-1 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Mehr Kontext (optional)</span>
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
maxLength={1000}
|
||||
className="mt-1 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Erstellen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -3,10 +3,12 @@ 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',
|
||||
@@ -20,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.
|
||||
@@ -49,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 &&
|
||||
@@ -56,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(
|
||||
@@ -96,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,7 @@ 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' },
|
||||
@@ -37,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,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>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
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 { TIME_CATEGORIES, type TimeCategory } from '../../lib/time-categories';
|
||||
|
||||
@@ -80,10 +81,7 @@ export function TimelineSection() {
|
||||
)}
|
||||
|
||||
{manualOpen && (
|
||||
<ManualDialog
|
||||
onClose={() => setManualOpen(false)}
|
||||
todos={todayQuery.data?.todos ?? []}
|
||||
/>
|
||||
<ManualDialog onClose={() => setManualOpen(false)} todos={todayQuery.data?.todos ?? []} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
@@ -258,7 +256,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
|
||||
@@ -270,7 +271,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}
|
||||
@@ -333,97 +334,78 @@ 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>
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Start</span>
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={startedAt}
|
||||
onChange={(e) => setStartedAt(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Ende</span>
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={endedAt}
|
||||
onChange={(e) => setEndedAt(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
</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">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Bezug auf ToDo (optional)</span>
|
||||
<select
|
||||
value={todoId}
|
||||
onChange={(e) => setTodoId(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
>
|
||||
<option value="">— kein ToDo —</option>
|
||||
{todos.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Kategorie</span>
|
||||
<select
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value as TimeCategory)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
>
|
||||
{TIME_CATEGORIES.map((c) => (
|
||||
<option key={c.value} value={c.value}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Beschreibung (optional)</span>
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Start</span>
|
||||
<input
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
maxLength={200}
|
||||
type="datetime-local"
|
||||
required
|
||||
value={startedAt}
|
||||
onChange={(e) => setStartedAt(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Speichern
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Ende</span>
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={endedAt}
|
||||
onChange={(e) => setEndedAt(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Bezug auf ToDo (optional)</span>
|
||||
<select
|
||||
value={todoId}
|
||||
onChange={(e) => setTodoId(e.target.value)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
>
|
||||
<option value="">— kein ToDo —</option>
|
||||
{todos.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Kategorie</span>
|
||||
<select
|
||||
value={category}
|
||||
onChange={(e) => setCategory(e.target.value as TimeCategory)}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
>
|
||||
{TIME_CATEGORIES.map((c) => (
|
||||
<option key={c.value} value={c.value}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs text-[var(--color-ink-muted)]">Beschreibung (optional)</span>
|
||||
<input
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
maxLength={200}
|
||||
className="mt-0.5 w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Speichern
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -43,7 +43,9 @@ if (typeof window !== 'undefined') {
|
||||
const Dashboard = lazyWithReload(() =>
|
||||
import('../routes/dashboard').then((m) => ({ default: m.DashboardRoute })),
|
||||
);
|
||||
const Heute = lazyWithReload(() => import('../routes/heute').then((m) => ({ default: m.HeuteRoute })));
|
||||
const Heute = lazyWithReload(() =>
|
||||
import('../routes/heute').then((m) => ({ default: m.HeuteRoute })),
|
||||
);
|
||||
const Reflexion = lazyWithReload(() =>
|
||||
import('../routes/reflexion').then((m) => ({ default: m.ReflexionRoute })),
|
||||
);
|
||||
@@ -53,7 +55,9 @@ const Bereich = lazyWithReload(() =>
|
||||
const Projekt = lazyWithReload(() =>
|
||||
import('../routes/projekt').then((m) => ({ default: m.ProjektRoute })),
|
||||
);
|
||||
const Leads = lazyWithReload(() => import('../routes/leads').then((m) => ({ default: m.LeadsRoute })));
|
||||
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 })),
|
||||
@@ -64,10 +68,18 @@ const Historie = lazyWithReload(() =>
|
||||
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 = lazyWithReload(() => 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 (
|
||||
@@ -103,11 +115,13 @@ const router = createBrowserRouter([
|
||||
{ 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 />) },
|
||||
|
||||
+104
-110
@@ -4,6 +4,7 @@ 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';
|
||||
@@ -111,22 +112,22 @@ function Section({
|
||||
<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>
|
||||
<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} />
|
||||
@@ -220,95 +221,86 @@ function ProjectCreateDialog({
|
||||
});
|
||||
}
|
||||
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>
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<Field label="Name">
|
||||
<input
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Beschreibung (optional)">
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="Worum geht's? Kurz beschreiben."
|
||||
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
|
||||
value={areaId}
|
||||
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…'}
|
||||
<Modal open onClose={onClose} title="Neues Projekt">
|
||||
<form onSubmit={submit} className="mt-4 space-y-3">
|
||||
<Field label="Name">
|
||||
<input
|
||||
required
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Beschreibung (optional)">
|
||||
<textarea
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="Worum geht's? Kurz beschreiben."
|
||||
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
|
||||
value={areaId}
|
||||
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}
|
||||
</option>
|
||||
{areas.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Projektart">
|
||||
<select
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value as 'kundenprojekt' | 'internes_projekt')}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="kundenprojekt">Kundenprojekt</option>
|
||||
<option value="internes_projekt">Internes Projekt</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Outline-Steckbrief-URL">
|
||||
<input
|
||||
required
|
||||
type="url"
|
||||
value={steckbrief}
|
||||
onChange={(e) => setSteckbrief(e.target.value)}
|
||||
placeholder="https://outline.tool-ctrl.de/..."
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Plane-Board-URL">
|
||||
<input
|
||||
required
|
||||
type="url"
|
||||
value={plane}
|
||||
onChange={(e) => setPlane(e.target.value)}
|
||||
placeholder="https://plane.tool-ctrl.de/..."
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Projektart">
|
||||
<select
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value as 'kundenprojekt' | 'internes_projekt')}
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="kundenprojekt">Kundenprojekt</option>
|
||||
<option value="internes_projekt">Internes Projekt</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Outline-Steckbrief-URL">
|
||||
<input
|
||||
required
|
||||
type="url"
|
||||
value={steckbrief}
|
||||
onChange={(e) => setSteckbrief(e.target.value)}
|
||||
placeholder="https://outline.tool-ctrl.de/..."
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Plane-Board-URL">
|
||||
<input
|
||||
required
|
||||
type="url"
|
||||
value={plane}
|
||||
onChange={(e) => setPlane(e.target.value)}
|
||||
placeholder="https://plane.tool-ctrl.de/..."
|
||||
className="w-full rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-3 py-2 text-sm"
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -373,14 +365,15 @@ 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);
|
||||
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">
|
||||
<Link
|
||||
to="/leads"
|
||||
className="text-sm text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
Alle Leads ({leads.length}) →
|
||||
</Link>
|
||||
</div>
|
||||
@@ -409,7 +402,9 @@ function LeadsTeaser() {
|
||||
<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 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)]">
|
||||
@@ -456,4 +451,3 @@ function ProjektListeFuerBereich({ slug }: { slug: 'vertrieb' | 'marketing' }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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';
|
||||
@@ -23,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';
|
||||
|
||||
+167
-27
@@ -4,6 +4,7 @@ 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, Check, LogOut } from 'lucide-react';
|
||||
@@ -218,9 +219,7 @@ 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}
|
||||
@@ -243,7 +242,7 @@ function TodoRow({
|
||||
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 ? (
|
||||
@@ -265,7 +264,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>
|
||||
@@ -320,18 +319,32 @@ function AddTodoInline() {
|
||||
function CheckInOutBar({
|
||||
checkedInAt,
|
||||
checkedOutAt,
|
||||
todos,
|
||||
reflected,
|
||||
}: {
|
||||
checkedInAt: string | Date | null;
|
||||
checkedOutAt: string | Date | null;
|
||||
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', {
|
||||
@@ -343,32 +356,149 @@ function CheckInOutBar({
|
||||
const duration =
|
||||
checkedInAt && checkedOutAt
|
||||
? formatDurationCompact(
|
||||
Math.max(0, Math.round((new Date(checkedOutAt).getTime() - new Date(checkedInAt).getTime()) / 1000)),
|
||||
Math.max(
|
||||
0,
|
||||
Math.round((new Date(checkedOutAt).getTime() - new Date(checkedInAt).getTime()) / 1000),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
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>
|
||||
{duration && ` · ${duration}`}
|
||||
<>
|
||||
<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>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="ml-auto"
|
||||
disabled={checkOut.isPending}
|
||||
onClick={() => checkOut.mutate()}
|
||||
>
|
||||
<LogOut size={14} /> Feierabend / Check-Out
|
||||
</Button>
|
||||
{checkedOutAt ? (
|
||||
<>
|
||||
<span className="text-[var(--color-ink-muted)]">
|
||||
· Feierabend <span className="font-mono">{hhmm(checkedOutAt)}</span>
|
||||
{duration && ` · ${duration}`}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="ml-auto"
|
||||
disabled={reopen.isPending}
|
||||
onClick={() => reopen.mutate()}
|
||||
>
|
||||
<Play size={14} /> Arbeit fortsetzen
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -413,7 +543,12 @@ function EinstempeltView({
|
||||
todos,
|
||||
entry,
|
||||
}: {
|
||||
todos: Array<{ id: string; title: string; status: 'open' | 'done' | 'dropped'; unplanned?: boolean }>;
|
||||
todos: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
status: 'open' | 'done' | 'dropped';
|
||||
unplanned?: boolean;
|
||||
}>;
|
||||
entry: {
|
||||
status: 'begun' | 'full' | 'absent';
|
||||
checkedInAt: string | Date | null;
|
||||
@@ -436,7 +571,12 @@ function EinstempeltView({
|
||||
<p className="mt-1 text-[var(--color-ink-muted)]">{subtitle}</p>
|
||||
</header>
|
||||
|
||||
<CheckInOutBar checkedInAt={entry.checkedInAt} checkedOutAt={entry.checkedOutAt} />
|
||||
<CheckInOutBar
|
||||
checkedInAt={entry.checkedInAt}
|
||||
checkedOutAt={entry.checkedOutAt}
|
||||
todos={todos}
|
||||
reflected={entry.status === 'full'}
|
||||
/>
|
||||
|
||||
{reflectionDue && (
|
||||
<div
|
||||
|
||||
@@ -1,18 +1,31 @@
|
||||
import { useState } from 'react';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-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)]' },
|
||||
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',
|
||||
@@ -32,13 +45,30 @@ function formatDateLong(iso: string): string {
|
||||
|
||||
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.data) return null;
|
||||
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">
|
||||
@@ -52,9 +82,10 @@ export function HistorieRoute() {
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDate(prevDate)}
|
||||
aria-label="Vorheriger Werktag"
|
||||
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)]"
|
||||
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>
|
||||
@@ -63,7 +94,7 @@ export function HistorieRoute() {
|
||||
type="button"
|
||||
onClick={() => nextDate && setDate(nextDate)}
|
||||
disabled={!nextDate}
|
||||
aria-label="Nächster Werktag"
|
||||
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} />
|
||||
@@ -80,15 +111,18 @@ export function HistorieRoute() {
|
||||
{entries.length === 0 ? (
|
||||
<Card.Root>
|
||||
<Card.Body>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
Keine Einträge an diesem Tag.
|
||||
</p>
|
||||
<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} />
|
||||
<PersonCard
|
||||
key={p.userId}
|
||||
person={p}
|
||||
canEdit={p.userId === me?.id && editableDay}
|
||||
onEdit={() => navigate(`/reflexion?date=${current}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
@@ -102,7 +136,15 @@ export function HistorieRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
function PersonCard({ person: p }: { person: HistoryPerson }) {
|
||||
function PersonCard({
|
||||
person: p,
|
||||
canEdit,
|
||||
onEdit,
|
||||
}: {
|
||||
person: HistoryPerson;
|
||||
canEdit: boolean;
|
||||
onEdit: () => void;
|
||||
}) {
|
||||
const ampel = p.ampel ? AMPEL_META[p.ampel] : null;
|
||||
return (
|
||||
<Card.Root>
|
||||
@@ -124,6 +166,11 @@ function PersonCard({ person: p }: { person: HistoryPerson }) {
|
||||
nicht reflektiert
|
||||
</span>
|
||||
)}
|
||||
{canEdit && (
|
||||
<Button size="sm" variant="ghost" className="ml-auto" onClick={onEdit}>
|
||||
<Pencil size={13} /> Bearbeiten
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{p.todos.length > 0 && (
|
||||
@@ -140,21 +187,25 @@ function PersonCard({ person: p }: { person: HistoryPerson }) {
|
||||
: 'bg-[var(--color-border-strong)]',
|
||||
)}
|
||||
/>
|
||||
<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
|
||||
<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>
|
||||
)}
|
||||
{t.status === 'dropped' && t.dropReason && (
|
||||
<span className="text-xs text-[var(--color-ink-faint)]"> — {t.dropReason}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -163,7 +214,17 @@ function PersonCard({ person: p }: { person: HistoryPerson }) {
|
||||
{p.reflectionText && (
|
||||
<p className="whitespace-pre-wrap text-sm text-[var(--color-ink)]">{p.reflectionText}</p>
|
||||
)}
|
||||
{p.todos.length === 0 && !p.reflectionText && (
|
||||
{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>
|
||||
|
||||
+184
-78
@@ -10,6 +10,9 @@ 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 { Modal } from '../components/ui/Modal';
|
||||
import { useConfirm } from '../components/ui/ConfirmProvider';
|
||||
import {
|
||||
LEAD_STATUS_META,
|
||||
LEAD_STATUS_ORDER,
|
||||
@@ -71,7 +74,10 @@ export function LeadRoute() {
|
||||
const q = trpc.lead.byId.useQuery({ id });
|
||||
|
||||
if (q.isPending) return <SkeletonCard lines={8} />;
|
||||
if (!q.data) return null;
|
||||
if (q.isError || !q.data)
|
||||
return (
|
||||
<ErrorState message="Lead konnte nicht geladen werden." onRetry={() => void q.refetch()} />
|
||||
);
|
||||
const { lead, contacts, touchpoints } = q.data;
|
||||
|
||||
function goBack() {
|
||||
@@ -297,9 +303,7 @@ function Header({ lead, onBack }: { lead: LeadDossier; onBack: () => void }) {
|
||||
<span className="text-[var(--color-ink-muted)]">Owner</span>
|
||||
<select
|
||||
value={lead.ownerUserId ?? ''}
|
||||
onChange={(e) =>
|
||||
update.mutate({ id: lead.id, ownerUserId: e.target.value || null })
|
||||
}
|
||||
onChange={(e) => update.mutate({ id: lead.id, ownerUserId: e.target.value || null })}
|
||||
className="rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1 text-sm"
|
||||
>
|
||||
<option value="">— niemand —</option>
|
||||
@@ -354,54 +358,48 @@ function PromoteDialog({ leadId, onClose }: { leadId: string; onClose: () => voi
|
||||
},
|
||||
});
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
|
||||
<div
|
||||
className="w-full max-w-sm rounded-[var(--radius-xl)] bg-[var(--color-bg)] p-6 shadow-[var(--shadow-lg)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
<Modal open onClose={onClose} title="Zu Deal machen" size="sm">
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Legt einen Pipeline-Deal in Stufe „Lead“ an und verknüpft ihn.
|
||||
</p>
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
promote.mutate({ leadId, valueEur: Math.round(euro * 100), probability });
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-semibold">Zu Deal machen</h2>
|
||||
<p className="mt-1 text-sm text-[var(--color-ink-muted)]">
|
||||
Legt einen Pipeline-Deal in Stufe „Lead“ an und verknüpft ihn.
|
||||
</p>
|
||||
<form
|
||||
className="mt-4 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
promote.mutate({ leadId, valueEur: Math.round(euro * 100), probability });
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Wert (EUR)</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={euro}
|
||||
onChange={(e) => setEuro(Number(e.target.value))}
|
||||
className={clsx(inputCls, 'mt-1')}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Wahrscheinlichkeit: {probability}%</span>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={probability}
|
||||
onChange={(e) => setProbability(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={promote.isPending}>
|
||||
Anlegen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Wert (EUR)</span>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={euro}
|
||||
onChange={(e) => setEuro(Number(e.target.value))}
|
||||
className={clsx(inputCls, 'mt-1')}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-sm font-medium">Wahrscheinlichkeit: {probability}%</span>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={probability}
|
||||
onChange={(e) => setProbability(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Abbrechen
|
||||
</Button>
|
||||
<Button type="submit" disabled={promote.isPending}>
|
||||
Anlegen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -522,13 +520,7 @@ function EditableSection({
|
||||
);
|
||||
}
|
||||
|
||||
function VertrauenslevelControl({
|
||||
leadId,
|
||||
value,
|
||||
}: {
|
||||
leadId: string;
|
||||
value: number | null;
|
||||
}) {
|
||||
function VertrauenslevelControl({ leadId, value }: { leadId: string; value: number | null }) {
|
||||
const utils = trpc.useUtils();
|
||||
const update = trpc.lead.update.useMutation({
|
||||
onSuccess: async () => {
|
||||
@@ -541,7 +533,10 @@ function VertrauenslevelControl({
|
||||
<select
|
||||
value={value ?? ''}
|
||||
onChange={(e) =>
|
||||
update.mutate({ id: leadId, vertrauenslevel: e.target.value ? Number(e.target.value) : null })
|
||||
update.mutate({
|
||||
id: leadId,
|
||||
vertrauenslevel: e.target.value ? Number(e.target.value) : null,
|
||||
})
|
||||
}
|
||||
className="rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1 text-sm"
|
||||
>
|
||||
@@ -593,6 +588,7 @@ function ContactRow({ leadId, contact }: { leadId: string; contact: Contact }) {
|
||||
await utils.lead.byId.invalidate({ id: leadId });
|
||||
},
|
||||
});
|
||||
const confirm = useConfirm();
|
||||
const details = [
|
||||
contact.email,
|
||||
contact.telefon,
|
||||
@@ -630,7 +626,16 @@ function ContactRow({ leadId, contact }: { leadId: string; contact: Contact }) {
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove.mutate({ contactId: contact.id })}
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Kontakt entfernen?',
|
||||
destructive: true,
|
||||
confirmLabel: 'Entfernen',
|
||||
})
|
||||
)
|
||||
remove.mutate({ contactId: contact.id });
|
||||
}}
|
||||
aria-label="Kontakt entfernen"
|
||||
className="text-[var(--color-ink-faint)] hover:text-[var(--color-ampel-red-fg)]"
|
||||
>
|
||||
@@ -687,8 +692,18 @@ function AddContactForm({ leadId, onDone }: { leadId: string; onDone: () => void
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input placeholder="Name *" value={name} onChange={(e) => setName(e.target.value)} className={inputCls} />
|
||||
<input placeholder="Rolle / Titel" value={rolle} onChange={(e) => setRolle(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
placeholder="Name *"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="Rolle / Titel"
|
||||
value={rolle}
|
||||
onChange={(e) => setRolle(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<select value={funktion} onChange={(e) => setFunktion(e.target.value)} className={inputCls}>
|
||||
<option value="">Funktion im Kaufprozess</option>
|
||||
{Object.entries(CONTACT_FUNKTION_LABEL).map(([v, l]) => (
|
||||
@@ -697,14 +712,43 @@ function AddContactForm({ leadId, onDone }: { leadId: string; onDone: () => void
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input placeholder="E-Mail" value={email} onChange={(e) => setEmail(e.target.value)} className={inputCls} />
|
||||
<input placeholder="Telefon" value={telefon} onChange={(e) => setTelefon(e.target.value)} className={inputCls} />
|
||||
<input placeholder="LinkedIn-URL" value={linkedin} onChange={(e) => setLinkedin(e.target.value)} className={inputCls} />
|
||||
<input placeholder="Sprache / Anrede" value={sprache} onChange={(e) => setSprache(e.target.value)} className={inputCls} />
|
||||
<input placeholder="Im Buying-Center seit" value={seit} onChange={(e) => setSeit(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
placeholder="E-Mail"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="Telefon"
|
||||
value={telefon}
|
||||
onChange={(e) => setTelefon(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="LinkedIn-URL"
|
||||
value={linkedin}
|
||||
onChange={(e) => setLinkedin(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="Sprache / Anrede"
|
||||
value={sprache}
|
||||
onChange={(e) => setSprache(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="Im Buying-Center seit"
|
||||
value={seit}
|
||||
onChange={(e) => setSeit(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={isPrimary} onChange={(e) => setIsPrimary(e.target.checked)} />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isPrimary}
|
||||
onChange={(e) => setIsPrimary(e.target.checked)}
|
||||
/>
|
||||
Hauptkontakt
|
||||
</label>
|
||||
<div className="flex justify-end gap-2">
|
||||
@@ -767,6 +811,7 @@ function TouchpointRow({ leadId, touchpoint }: { leadId: string; touchpoint: Tou
|
||||
await utils.lead.byId.invalidate({ id: leadId });
|
||||
},
|
||||
});
|
||||
const confirm = useConfirm();
|
||||
return (
|
||||
<div className="rounded-[var(--radius-md)] border border-[var(--color-border)] p-3 text-sm">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
@@ -784,7 +829,16 @@ function TouchpointRow({ leadId, touchpoint }: { leadId: string; touchpoint: Tou
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove.mutate({ touchpointId: touchpoint.id })}
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Touchpoint löschen?',
|
||||
destructive: true,
|
||||
confirmLabel: 'Löschen',
|
||||
})
|
||||
)
|
||||
remove.mutate({ touchpointId: touchpoint.id });
|
||||
}}
|
||||
aria-label="Eintrag entfernen"
|
||||
className="text-[var(--color-ink-faint)] hover:text-[var(--color-ampel-red-fg)]"
|
||||
>
|
||||
@@ -832,7 +886,12 @@ function AddTouchpointForm({ leadId, onDone }: { leadId: string; onDone: () => v
|
||||
}}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input type="date" value={datum} onChange={(e) => setDatum(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
type="date"
|
||||
value={datum}
|
||||
onChange={(e) => setDatum(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<select value={kanal} onChange={(e) => setKanal(e.target.value)} className={inputCls}>
|
||||
{Object.entries(TOUCHPOINT_KANAL_LABEL).map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
@@ -849,10 +908,20 @@ function AddTouchpointForm({ leadId, onDone }: { leadId: string; onDone: () => v
|
||||
className={inputCls}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input placeholder="Outcome" value={outcome} onChange={(e) => setOutcome(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
placeholder="Outcome"
|
||||
value={outcome}
|
||||
onChange={(e) => setOutcome(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<label className="flex flex-col text-xs text-[var(--color-ink-muted)]">
|
||||
Follow-up bis
|
||||
<input type="date" value={followUp} onChange={(e) => setFollowUp(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
type="date"
|
||||
value={followUp}
|
||||
onChange={(e) => setFollowUp(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
@@ -882,6 +951,7 @@ function OffeneFragenSection({
|
||||
await utils.lead.byId.invalidate({ id: leadId });
|
||||
},
|
||||
});
|
||||
const confirm = useConfirm();
|
||||
function persist(next: Array<{ text: string; done: boolean }>) {
|
||||
update.mutate({ id: leadId, offeneFragen: next });
|
||||
}
|
||||
@@ -904,12 +974,23 @@ function OffeneFragenSection({
|
||||
persist(fragen.map((x, j) => (j === i ? { ...x, done: !x.done } : x)))
|
||||
}
|
||||
/>
|
||||
<span className={clsx('flex-1', f.done && 'text-[var(--color-ink-muted)] line-through')}>
|
||||
<span
|
||||
className={clsx('flex-1', f.done && 'text-[var(--color-ink-muted)] line-through')}
|
||||
>
|
||||
{f.text}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => persist(fragen.filter((_, j) => j !== i))}
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Frage löschen?',
|
||||
destructive: true,
|
||||
confirmLabel: 'Löschen',
|
||||
})
|
||||
)
|
||||
persist(fragen.filter((_, j) => j !== i));
|
||||
}}
|
||||
aria-label="Frage entfernen"
|
||||
className="text-[var(--color-ink-faint)] hover:text-[var(--color-ampel-red-fg)]"
|
||||
>
|
||||
@@ -959,6 +1040,7 @@ function AnhaengeSection({
|
||||
await utils.lead.byId.invalidate({ id: leadId });
|
||||
},
|
||||
});
|
||||
const confirm = useConfirm();
|
||||
function persist(next: Array<{ label: string; url: string }>) {
|
||||
update.mutate({ id: leadId, anhaenge: next });
|
||||
}
|
||||
@@ -977,7 +1059,16 @@ function AnhaengeSection({
|
||||
<ExternalLink url={a.url} label={a.label} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => persist(anhaenge.filter((_, j) => j !== i))}
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Anhang entfernen?',
|
||||
destructive: true,
|
||||
confirmLabel: 'Entfernen',
|
||||
})
|
||||
)
|
||||
persist(anhaenge.filter((_, j) => j !== i));
|
||||
}}
|
||||
aria-label="Anhang entfernen"
|
||||
className="text-[var(--color-ink-faint)] hover:text-[var(--color-ampel-red-fg)]"
|
||||
>
|
||||
@@ -996,8 +1087,18 @@ function AnhaengeSection({
|
||||
setUrl('');
|
||||
}}
|
||||
>
|
||||
<input placeholder="Bezeichnung" value={label} onChange={(e) => setLabel(e.target.value)} className={inputCls} />
|
||||
<input placeholder="URL" value={url} onChange={(e) => setUrl(e.target.value)} className={inputCls} />
|
||||
<input
|
||||
placeholder="Bezeichnung"
|
||||
value={label}
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<input
|
||||
placeholder="URL"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
className={inputCls}
|
||||
/>
|
||||
<Button type="submit" size="sm" variant="secondary">
|
||||
<Plus size={14} />
|
||||
</Button>
|
||||
@@ -1010,7 +1111,12 @@ function AnhaengeSection({
|
||||
function ExternalLink({ url, label }: { url: string; label?: string }) {
|
||||
const href = url.startsWith('http') ? url : `https://${url}`;
|
||||
return (
|
||||
<a href={href} target="_blank" rel="noreferrer" className="truncate text-[var(--color-ink)] hover:underline">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="truncate text-[var(--color-ink)] hover:underline"
|
||||
>
|
||||
{label ?? url}
|
||||
</a>
|
||||
);
|
||||
|
||||
+202
-166
@@ -1,17 +1,15 @@
|
||||
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';
|
||||
import { LEAD_STATUS_META, LEAD_STATUS_ORDER, type LeadStatus } from '../lib/lead-meta';
|
||||
|
||||
export function LeadsRoute() {
|
||||
const q = trpc.lead.list.useQuery();
|
||||
@@ -37,6 +35,12 @@ export function LeadsRoute() {
|
||||
</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>
|
||||
@@ -44,12 +48,12 @@ export function LeadsRoute() {
|
||||
</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>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">Noch keine Leads. Leg einen an.</p>
|
||||
</Card.Body>
|
||||
</Card.Root>
|
||||
) : (
|
||||
@@ -80,6 +84,36 @@ export function LeadsRoute() {
|
||||
);
|
||||
}
|
||||
|
||||
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 }));
|
||||
@@ -113,83 +147,79 @@ function LeadImportDialog({ 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">Leads aus CSV importieren</h2>
|
||||
<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>
|
||||
<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)
|
||||
<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>
|
||||
)}
|
||||
|
||||
{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>
|
||||
)}
|
||||
<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>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -281,102 +311,108 @@ function LeadCreateDialog({ onClose }: { onClose: () => void }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30" onClick={onClose}>
|
||||
<div
|
||||
className="max-h-[90vh] w-full max-w-md overflow-y-auto 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 Lead</h2>
|
||||
<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">
|
||||
<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
|
||||
required
|
||||
value={firma}
|
||||
onChange={(e) => setFirma(e.target.value)}
|
||||
value={branche}
|
||||
onChange={(e) => setBranche(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 label="Nische / Sub-Segment">
|
||||
<input
|
||||
value={subSegment}
|
||||
onChange={(e) => setSubSegment(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}
|
||||
</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>
|
||||
<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 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 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>
|
||||
</div>
|
||||
</div>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+669
-189
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';
|
||||
@@ -14,27 +14,56 @@ 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,24 +71,32 @@ 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('');
|
||||
@@ -86,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) {
|
||||
@@ -107,7 +148,7 @@ function ReflectForm({
|
||||
todos: todos.map((t) => ({
|
||||
id: t.id,
|
||||
status: todoStates[t.id]?.status ?? t.status,
|
||||
dropReason: todoStates[t.id]?.reason,
|
||||
dropReason: todoStates[t.id]?.reason?.trim() || undefined,
|
||||
})),
|
||||
reflectionText,
|
||||
ampel,
|
||||
@@ -138,66 +179,79 @@ function ReflectForm({
|
||||
{todos.map((t) => {
|
||||
const status = todoStates[t.id]?.status ?? t.status;
|
||||
return (
|
||||
<li key={t.id} 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'}
|
||||
onClick={() => setTodoStatus(t.id, 'done')}
|
||||
label="Erledigt"
|
||||
>
|
||||
<Check size={14} />
|
||||
</StatusBtn>
|
||||
<StatusBtn
|
||||
active={status === 'open'}
|
||||
onClick={() => setTodoStatus(t.id, 'open')}
|
||||
label="Offen"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</StatusBtn>
|
||||
<StatusBtn
|
||||
active={status === 'dropped'}
|
||||
onClick={() => setTodoStatus(t.id, 'dropped')}
|
||||
label="Verworfen"
|
||||
>
|
||||
<X size={14} />
|
||||
</StatusBtn>
|
||||
<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'}
|
||||
onClick={() => setTodoStatus(t.id, 'done')}
|
||||
label="Erledigt"
|
||||
>
|
||||
<Check size={14} />
|
||||
</StatusBtn>
|
||||
<StatusBtn
|
||||
active={status === 'open'}
|
||||
onClick={() => setTodoStatus(t.id, 'open')}
|
||||
label="Offen"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</StatusBtn>
|
||||
<StatusBtn
|
||||
active={status === 'dropped'}
|
||||
onClick={() => setTodoStatus(t.id, 'dropped')}
|
||||
label="Verworfen"
|
||||
>
|
||||
<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>
|
||||
<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>
|
||||
{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>
|
||||
|
||||
@@ -391,7 +445,7 @@ function EditableTodoTitle({ id, title }: { id: string; title: string }) {
|
||||
<span>{title}</span>
|
||||
<Pencil
|
||||
size={12}
|
||||
className="text-[var(--color-ink-faint)] opacity-0 transition-opacity group-hover:opacity-100"
|
||||
className="text-[var(--color-ink-faint)] opacity-100 transition-opacity sm:opacity-0 sm:group-hover:opacity-100"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ 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';
|
||||
|
||||
@@ -124,7 +125,13 @@ export function TeamViewRoute() {
|
||||
}, [isToday]);
|
||||
|
||||
if (q.isPending) return <SkeletonCard lines={6} />;
|
||||
if (!q.data) return null;
|
||||
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();
|
||||
|
||||
|
||||
@@ -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,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;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -120,6 +120,20 @@
|
||||
"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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -166,6 +166,14 @@ export const project = pgTable(
|
||||
lessonsLearnedUrl: text('lessons_learned_url'),
|
||||
// Abschluss (Leitfaden Phase 4): kurzer Abschlussvermerk — Ziel erreicht? Aufwand vs. Plan?
|
||||
abschlussvermerk: text('abschlussvermerk'),
|
||||
// Strukturierte Retrospektive (Lessons-Learned-Vorlage). Ersetzt die freie
|
||||
// Vermerk-Textarea durch geführte Felder; alte Einträge nutzen abschlussvermerk.
|
||||
lessonsLearned: jsonb('lessons_learned').$type<{
|
||||
zielErreicht: string;
|
||||
aufwand: string;
|
||||
liefGut: string;
|
||||
liefSchlecht: string;
|
||||
} | null>(),
|
||||
createdBy: uuid('created_by').references(() => user.id, { onDelete: 'set null' }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
@@ -231,7 +239,7 @@ export const dayEntry = pgTable(
|
||||
ampel: text('ampel', { enum: ['green', 'amber', 'red'] }),
|
||||
trend: text('trend', { enum: ['besser', 'gleich', 'schlechter'] }),
|
||||
url: text('url'),
|
||||
blockerId: uuid('blocker_id'),
|
||||
blockerId: uuid('blocker_id').references(() => blocker.id, { onDelete: 'set null' }),
|
||||
editLockedAt: timestamp('edit_locked_at', { withTimezone: true }),
|
||||
publishedAt: timestamp('published_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
@@ -402,8 +410,12 @@ export const leadHandover = pgTable('lead_handover', {
|
||||
export const timeEntry = pgTable(
|
||||
'time_entry',
|
||||
{
|
||||
id: uuid('id').default(sql`gen_random_uuid()`).primaryKey(),
|
||||
userId: uuid('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
|
||||
id: uuid('id')
|
||||
.default(sql`gen_random_uuid()`)
|
||||
.primaryKey(),
|
||||
userId: uuid('user_id')
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: 'cascade' }),
|
||||
dayEntryId: uuid('day_entry_id').references(() => dayEntry.id, { onDelete: 'set null' }),
|
||||
todoId: uuid('todo_id').references(() => todo.id, { onDelete: 'set null' }),
|
||||
bezugKind: text('bezug_kind', { enum: ['project', 'deal', 'campaign', 'allgemein'] }),
|
||||
@@ -442,8 +454,8 @@ export const blocker = pgTable(
|
||||
.primaryKey(),
|
||||
title: text('title').notNull(),
|
||||
description: text('description'),
|
||||
areaId: uuid('area_id'),
|
||||
projectId: uuid('project_id'),
|
||||
areaId: uuid('area_id').references(() => area.id, { onDelete: 'set null' }),
|
||||
projectId: uuid('project_id').references(() => project.id, { onDelete: 'set null' }),
|
||||
ownerUserId: uuid('owner_user_id').references(() => user.id, { onDelete: 'set null' }),
|
||||
openedBy: uuid('opened_by')
|
||||
.notNull()
|
||||
@@ -590,7 +602,9 @@ export const leadTouchpoint = pgTable(
|
||||
kanal: text('kanal', {
|
||||
enum: ['call', 'mail', 'linkedin', 'termin', 'event', 'sonstiges'],
|
||||
}).notNull(),
|
||||
bearbeiterUserId: uuid('bearbeiter_user_id').references(() => user.id, { onDelete: 'set null' }),
|
||||
bearbeiterUserId: uuid('bearbeiter_user_id').references(() => user.id, {
|
||||
onDelete: 'set null',
|
||||
}),
|
||||
inhalt: text('inhalt').notNull(),
|
||||
outcome: text('outcome'),
|
||||
followUpBis: date('follow_up_bis'),
|
||||
|
||||
@@ -28,7 +28,9 @@ export const submitReflectionInput = z.object({
|
||||
z.object({
|
||||
id: z.string().uuid(),
|
||||
status: todoStatusSchema,
|
||||
dropReason: z.string().max(200).optional(),
|
||||
// Optionale Notiz pro Task (frühere „Verworfen-Grund"-Spalte, jetzt für
|
||||
// jeden Status als freie Beschreibung nutzbar).
|
||||
dropReason: z.string().max(500).optional(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
|
||||
@@ -44,10 +44,20 @@ export const createProjectInput = z.object({
|
||||
});
|
||||
export type CreateProjectInput = z.infer<typeof createProjectInput>;
|
||||
|
||||
export const lessonsLearnedSchema = z.object({
|
||||
zielErreicht: z.string().max(2000),
|
||||
aufwand: z.string().max(2000),
|
||||
liefGut: z.string().max(2000),
|
||||
liefSchlecht: z.string().max(2000),
|
||||
});
|
||||
export type LessonsLearned = z.infer<typeof lessonsLearnedSchema>;
|
||||
|
||||
export const archiveProjectInput = z.object({
|
||||
projectId: z.string().uuid(),
|
||||
lessonsLearnedUrl: z.string().url(),
|
||||
abschlussvermerk: z.string().max(2000).optional(),
|
||||
// Strukturierte Retrospektive (Lessons-Learned-Vorlage), optional.
|
||||
lessonsLearned: lessonsLearnedSchema.optional(),
|
||||
});
|
||||
export type ArchiveProjectInput = z.infer<typeof archiveProjectInput>;
|
||||
|
||||
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Minimaler Tages-Scheduler für den Backup-Sidecar: führt backup.sh einmal
|
||||
# täglich zur Stunde BACKUP_HOUR (Container-TZ = Europe/Berlin) aus.
|
||||
#
|
||||
# Bewusst kein cron: ein simpler Poll-Loop erbt das Container-Environment
|
||||
# zuverlässig (POSTGRES_PASSWORD u. a.) und hat keine busybox-cron-Eigenheiten.
|
||||
|
||||
set -eu
|
||||
|
||||
HOUR="${BACKUP_HOUR:-03}"
|
||||
echo "Backup-Sidecar aktiv — täglich um ${HOUR}:00 (TZ=${TZ:-UTC}), Retention ${BACKUP_RETENTION_DAYS:-14} Tage."
|
||||
|
||||
while true; do
|
||||
if [ "$(date +%H)" = "$HOUR" ] && [ "$(date +%M)" = "00" ]; then
|
||||
/usr/local/bin/backup.sh || echo "Backup fehlgeschlagen (Exit $?)" >&2
|
||||
sleep 61 # diese Minute überspringen, damit nicht doppelt ausgelöst wird
|
||||
fi
|
||||
sleep 30
|
||||
done
|
||||
+19
-9
@@ -1,21 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Tägliches pg_dump in /backups, 14 Tage Retention.
|
||||
# Läuft im Postgres-Container via System-Cron.
|
||||
# pg_dump des Cockpit-Postgres nach /backups. Custom-Format (-Fc): bereits
|
||||
# komprimiert UND erlaubt selektives pg_restore — daher KEIN zusätzliches gzip.
|
||||
#
|
||||
# Läuft im Backup-Sidecar (docker-compose.yml service "backup") gegen den
|
||||
# postgres-Service (PGHOST). Einmal pro Tag getriggert von backup-loop.sh.
|
||||
# Manuell ausführbar: `docker compose exec backup /usr/local/bin/backup.sh`.
|
||||
|
||||
set -eu
|
||||
|
||||
PGHOST="${PGHOST:-postgres}"
|
||||
PGUSER="${POSTGRES_USER:-cockpit}"
|
||||
PGDATABASE="${POSTGRES_DB:-cockpit}"
|
||||
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-14}"
|
||||
DATE=$(date +%Y%m%d-%H%M%S)
|
||||
OUT="/backups/cockpit-${DATE}.sql.gz"
|
||||
OUT="/backups/cockpit-${DATE}.dump"
|
||||
mkdir -p /backups
|
||||
|
||||
pg_dump -U "${POSTGRES_USER:-cockpit}" -d "${POSTGRES_DB:-cockpit}" -Fc | gzip > "$OUT"
|
||||
echo "Backup written: $OUT"
|
||||
export PGPASSWORD="${POSTGRES_PASSWORD:-}"
|
||||
pg_dump -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -Fc -f "$OUT"
|
||||
echo "Backup geschrieben: $OUT ($(du -h "$OUT" | cut -f1))"
|
||||
|
||||
# Retention: lösche Dumps älter als 14 Tage.
|
||||
find /backups -type f -name "cockpit-*.sql.gz" -mtime +14 -delete
|
||||
# Retention: Dumps älter als N Tage löschen.
|
||||
find /backups -type f -name 'cockpit-*.dump' -mtime "+${RETENTION_DAYS}" -delete
|
||||
|
||||
# Heartbeat an API (logging).
|
||||
if [ -n "${CRON_BEARER_TOKEN:-}" ] && [ -n "${API_URL:-}" ]; then
|
||||
# Heartbeat an die API (nur Observability/Logging — macht selbst kein Backup).
|
||||
API_URL="${API_URL:-http://api:3000}"
|
||||
if [ -n "${CRON_BEARER_TOKEN:-}" ]; then
|
||||
wget -q --header="Authorization: Bearer ${CRON_BEARER_TOKEN}" \
|
||||
-O- "${API_URL}/internal/cron/pg-dump-backup" || true
|
||||
fi
|
||||
Reference in new issue
Block a user