Files
tickettracker/frontend/src/views/TicketDetailPage.tsx
T
2026-09-23 11:09:10 +00:00

2154 lines
91 KiB
TypeScript

import { ArrowLeft, CheckCircle2, ChevronDown, ChevronUp, ClipboardList, Copy, EyeOff, FolderKanban, Pencil, Plus, RotateCcw, Save, Star, Trash2 } from "lucide-react";
import { FormEvent, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Alert } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { CopyTicketButton } from "@/components/CopyTicketButton";
import { HelpLink } from "@/components/HelpLink";
import { OrganizationSelect } from "@/components/OrganizationSelect";
import { TodoPanel } from "@/components/TodoPanel";
import {
createSession,
deleteProject,
deleteSession,
hideProject,
addFavoriteTicket,
getDashboardPreference,
getTicketDetails,
getTicketPeriod,
removeFavoriteTicket,
updateSessionBilling,
updateSessionDetails,
updateTicket,
updateTicketDayBilling,
updateProject,
updateProjectStatus
} from "../api";
import { currentDay, currentMonth, formatDate, formatDateTime, formatMinutes, formatTimeRange } from "../format";
import { ticketHasRecurringBilling } from "../recurring-billings";
import type { BillingStatus, PeriodType, ProjectSummary, ProjectTeamspaceEntry, SessionEntry, TicketDetailPeriodType, TicketPeriod, WorkType } from "../types";
import { ZammadPriorityBadge, ZammadStateBadge } from "../zammad-meta";
import { cn } from "@/lib/utils";
type TicketDetailPageProps = {
periodType: TicketDetailPeriodType;
period: string;
ticketId: string;
onNavigate: (to: string) => void;
onOpenTicketChange?: (ticket: {
key: string;
ticketId: string;
ticketNumber: string;
periodType: TicketDetailPeriodType;
period: string;
path: string;
returnPath?: string;
dirty: boolean;
}) => void;
returnPath: string;
};
type TicketSessionFormState = {
organizationId: string;
organizationName: string | null;
projectTeamspaceEntryId: string;
activity: string;
billingStatus: BillingStatus;
workType: WorkType;
day: string;
startTime: string;
endTime: string;
};
type ProjectEditFormState = {
title: string;
organizationId: string;
organizationName: string | null;
description: string;
startsOn: string;
endsOn: string;
teamspaceEntries: ProjectTeamspaceEntryForm[];
};
type ProjectTeamspaceEntryForm = {
clientId: string;
teamspaceProject: string;
hourBudget: string;
budgetSyncDisabled: boolean;
manualConsumption: string;
isDefault: boolean;
};
function emptyTicketSessionForm(): TicketSessionFormState {
return {
organizationId: "",
organizationName: null,
projectTeamspaceEntryId: "",
activity: "",
billingStatus: null,
workType: "support",
day: currentDay(),
startTime: "09:00",
endTime: "09:30"
};
}
function projectEntryId() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `entry-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function projectTeamspaceEntries(project: ProjectSummary): ProjectTeamspaceEntry[] {
if (project.teamspace_entries?.length) {
return project.teamspace_entries;
}
return [
{
id: `${project.id}-default`,
teamspace_project: project.teamspace_project,
is_default: true,
hour_budget_minutes: project.hour_budget_minutes,
manual_consumption_minutes: project.manual_consumption_minutes ?? 0,
teamspace_consumption_minutes: project.teamspace_consumption_minutes ?? 0,
consumption_minutes: project.consumption_minutes ?? project.teamspace_consumption_minutes ?? 0,
display_order: 0
}
];
}
function budgetedProjectTeamspaceEntries(project: ProjectSummary) {
return projectTeamspaceEntries(project).filter((entry) => Number(entry.hour_budget_minutes ?? 0) > 0);
}
function teamspaceEntryOptionLabel(entry: { teamspace_project: string | null; is_default: boolean }) {
const label = entry.teamspace_project || "Ohne Teamspace-ID";
return entry.is_default ? `${label} (Standard)` : label;
}
function projectEditForm(project: ProjectSummary): ProjectEditFormState {
const entries = projectTeamspaceEntries(project).map((entry, index) => ({
clientId: entry.id || projectEntryId(),
teamspaceProject: entry.teamspace_project ?? "",
hourBudget: formatHoursInput(entry.hour_budget_minutes),
budgetSyncDisabled: entry.budget_sync_disabled ?? false,
manualConsumption: formatHoursInput(entry.manual_consumption_minutes),
isDefault: entry.is_default || index === 0
}));
const hasDefault = entries.some((entry) => entry.isDefault);
return {
title: project.title ?? "",
organizationId: project.organization_id ?? "",
organizationName: project.organization_name ?? project.customer_name ?? null,
description: combinedProjectDescription(project),
startsOn: project.starts_on ?? "",
endsOn: project.ends_on ?? "",
teamspaceEntries: hasDefault ? entries : entries.map((entry, index) => ({ ...entry, isDefault: index === 0 }))
};
}
function combinedProjectDescription(project: ProjectSummary) {
return [project.description, project.goals].map((part) => part.trim()).filter(Boolean).join("\n\n");
}
function BillingButtons({
session,
disabled,
loading,
onChange
}: {
session: SessionEntry;
disabled: boolean;
loading: boolean;
onChange: (status: BillingStatus) => void;
}) {
const status = session.billing_status;
return (
<div className="grid grid-cols-3 gap-1.5 sm:inline-grid">
<Button
type="button"
size="sm"
variant={status === "billable" ? "default" : "secondary"}
disabled={loading || (disabled && status !== "billable")}
onClick={() => onChange(status === "billable" ? null : "billable")}
className={cn("h-8", status === "billable" ? "" : "bg-secondary/70")}
>
Abrechenbar
</Button>
<Button
type="button"
size="sm"
variant={status === "billed" ? "default" : "secondary"}
disabled={loading || (disabled && status !== "billed")}
onClick={() => onChange(status === "billed" ? null : "billed")}
className={cn("h-8", status === "billed" ? "" : "bg-secondary/70")}
>
Abgerechnet
</Button>
<Button
type="button"
size="sm"
variant={status === "non_billable" ? "default" : "secondary"}
disabled={loading || (disabled && status !== "non_billable")}
onClick={() => onChange(status === "non_billable" ? null : "non_billable")}
className={cn("h-8", status === "non_billable" ? "" : "bg-secondary/70")}
>
Nicht abrechenbar
</Button>
</div>
);
}
function BillingCaptureSelect({
id,
value,
onChange
}: {
id: string;
value: BillingStatus;
onChange: (status: BillingStatus) => void;
}) {
return (
<select
id={id}
className="h-9 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={value ?? ""}
onChange={(event) => onChange(event.currentTarget.value === "" ? null : event.currentTarget.value as Exclude<BillingStatus, null>)}
>
<option value="">---</option>
<option value="billable">Abrechenbar</option>
<option value="non_billable">Nicht abrechenbar</option>
</select>
);
}
function sessionDayKey(value: string) {
const date = new Date(value);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
}
async function writeTextToClipboard(value: string) {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(value);
return;
}
if (typeof document === "undefined") {
throw new Error("Zwischenablage nicht verfügbar");
}
const textarea = document.createElement("textarea");
textarea.value = value;
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
textarea.setAttribute("readonly", "");
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
try {
if (!document.execCommand("copy")) {
throw new Error("Zwischenablage nicht verfügbar");
}
} finally {
document.body.removeChild(textarea);
}
}
function teamspacePreparationText(ticket: TicketPeriod["ticket"] | null | undefined, sessions: SessionEntry[]) {
const ticketNumber = ticket?.ticket_number ?? "Ticket#-";
const customerName = ticket?.organization_name ?? ticket?.customer_name ?? "-";
const activities = sessions
.slice()
.sort((left, right) => new Date(left.started_at).getTime() - new Date(right.started_at).getTime())
.map((session) => session.activity.trim())
.filter(Boolean)
.join("\n");
return [`${ticketNumber} - ${customerName}`, "", activities, "", "Tickethandling und Dokumentation"].join("\n");
}
function toDateLocalValue(value: string) {
const date = new Date(value);
const offsetMs = date.getTimezoneOffset() * 60_000;
return new Date(date.getTime() - offsetMs).toISOString().slice(0, 10);
}
function toTimeLocalValue(value: string) {
const date = new Date(value);
const offsetMs = date.getTimezoneOffset() * 60_000;
return new Date(date.getTime() - offsetMs).toISOString().slice(11, 16);
}
function formatHoursInput(minutes?: number | null) {
if (minutes === null || minutes === undefined) {
return "";
}
return new Intl.NumberFormat("de-DE", { maximumFractionDigits: 2 }).format(minutes / 60);
}
function parseHoursInput(value: string) {
const trimmed = value.trim();
if (!trimmed) {
return null;
}
if (/[,.]$/.test(trimmed)) {
return undefined;
}
const hours = Number(trimmed.replace(",", "."));
if (!Number.isFinite(hours) || hours < 0) {
return undefined;
}
return Math.round(hours * 60);
}
function projectConsumptionBarClass(percent: number) {
if (percent >= 100) {
return "bg-blue-500";
}
if (percent >= 90) {
return "bg-red-500";
}
return "bg-emerald-500";
}
function projectConsumptionPercent(consumptionMinutes: number, budgetMinutes?: number | null) {
if (!budgetMinutes || budgetMinutes <= 0) {
return null;
}
return Math.round((consumptionMinutes / budgetMinutes) * 100);
}
function projectRemainingLabel(remainingMinutes: number | null) {
if (remainingMinutes === null) {
return "Rest offen";
}
if (remainingMinutes < 0) {
return `Überzogen ${formatMinutes(Math.abs(remainingMinutes))}`;
}
return `Rest ${formatMinutes(remainingMinutes)}`;
}
function isPartialHoursInput(value: string) {
return /^\d*(?:[,.]\d*)?$/.test(value.trim());
}
function normalizeProjectTeamspaceEntryForms(entries: ProjectTeamspaceEntryForm[]) {
const source = entries.length
? entries
: [
{
clientId: projectEntryId(),
teamspaceProject: "",
hourBudget: "",
budgetSyncDisabled: false,
manualConsumption: "",
isDefault: true
}
];
const defaultIndex = Math.max(0, source.findIndex((entry) => entry.isDefault));
return source.map((entry, index) => ({
...entry,
isDefault: index === defaultIndex
}));
}
function parseProjectTeamspaceEntryForms(entries: ProjectTeamspaceEntryForm[]) {
const normalizedEntries = normalizeProjectTeamspaceEntryForms(entries);
const parsedEntries = normalizedEntries.map((entry) => {
const hourBudgetMinutes = parseHoursInput(entry.hourBudget);
const manualConsumptionMinutes = parseHoursInput(entry.manualConsumption);
if (hourBudgetMinutes === undefined || manualConsumptionMinutes === undefined) {
return undefined;
}
return {
id: /^\d+$/.test(entry.clientId) ? entry.clientId : null,
teamspaceProject: entry.teamspaceProject.trim() || null,
isDefault: entry.isDefault,
hourBudgetMinutes,
budgetSyncDisabled: entry.budgetSyncDisabled,
manualConsumptionMinutes: manualConsumptionMinutes ?? 0
};
});
if (parsedEntries.some((entry) => entry === undefined)) {
return undefined;
}
return parsedEntries as Array<{
id?: string | null;
teamspaceProject: string | null;
isDefault: boolean;
hourBudgetMinutes: number | null;
budgetSyncDisabled: boolean;
manualConsumptionMinutes: number;
}>;
}
function ProjectTeamspaceEntriesEditor({
entries,
onChange
}: {
entries: ProjectTeamspaceEntryForm[];
onChange: (entries: ProjectTeamspaceEntryForm[]) => void;
}) {
const normalizedEntries = normalizeProjectTeamspaceEntryForms(entries);
function updateEntry(clientId: string, changes: Partial<ProjectTeamspaceEntryForm>) {
onChange(normalizeProjectTeamspaceEntryForms(normalizedEntries.map((entry) => (entry.clientId === clientId ? { ...entry, ...changes } : entry))));
}
function removeEntry(clientId: string) {
onChange(normalizeProjectTeamspaceEntryForms(normalizedEntries.filter((entry) => entry.clientId !== clientId)));
}
return (
<div className="space-y-2">
<div className="flex items-center justify-between gap-2">
<label className="text-sm font-medium">Teamspace-Einträge</label>
<Button type="button" size="sm" variant="secondary" onClick={() => onChange([...normalizedEntries, { clientId: projectEntryId(), teamspaceProject: "", hourBudget: "", budgetSyncDisabled: false, manualConsumption: "", isDefault: false }])}>
<Plus className="size-3.5" />
Eintrag
</Button>
</div>
{normalizedEntries.map((entry, index) => (
<div key={entry.clientId} className="grid gap-2 rounded-lg border bg-muted/10 p-3 lg:grid-cols-[minmax(180px,1fr)_120px_150px_130px_120px_36px] lg:items-end">
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground" htmlFor={`project-ticket-teamspace-${entry.clientId}`}>
Teamspace-Projekt {entry.isDefault ? "(Standard)" : ""}
</label>
<Input
id={`project-ticket-teamspace-${entry.clientId}`}
value={entry.teamspaceProject}
onChange={(event) => updateEntry(entry.clientId, { teamspaceProject: event.currentTarget.value })}
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground" htmlFor={`project-ticket-budget-${entry.clientId}`}>Budget h</label>
<Input id={`project-ticket-budget-${entry.clientId}`} inputMode="decimal" value={entry.hourBudget} onChange={(event) => updateEntry(entry.clientId, { hourBudget: event.currentTarget.value, budgetSyncDisabled: true })} />
</div>
<label className="flex min-h-9 items-center gap-2 rounded-md border bg-background px-3 text-xs">
<Checkbox checked={entry.budgetSyncDisabled} onCheckedChange={(checked) => updateEntry(entry.clientId, { budgetSyncDisabled: checked === true })} />
<span>Budget schützen</span>
</label>
<div className="space-y-1.5">
<label className="text-xs font-medium text-muted-foreground" htmlFor={`project-ticket-manual-${entry.clientId}`}>Manueller Verbrauch h</label>
<Input id={`project-ticket-manual-${entry.clientId}`} inputMode="decimal" value={entry.manualConsumption} onChange={(event) => updateEntry(entry.clientId, { manualConsumption: event.currentTarget.value })} />
</div>
<Button
type="button"
size="sm"
variant={entry.isDefault ? "default" : "secondary"}
onClick={() => onChange(normalizedEntries.map((candidate) => ({ ...candidate, isDefault: candidate.clientId === entry.clientId })))}
>
{entry.isDefault ? "Standard" : "Als Standard"}
</Button>
<Button type="button" size="icon" variant="ghost" disabled={normalizedEntries.length === 1} onClick={() => removeEntry(entry.clientId)}>
<Trash2 className="size-4 text-destructive" />
<span className="sr-only">Teamspace-Eintrag {index + 1} löschen</span>
</Button>
</div>
))}
<p className="text-xs text-muted-foreground">Der Standard-Eintrag erhält die gebuchten Teamspace-Tageswerte. Manuelle Stunden zählen nur im Projektverbrauch.</p>
</div>
);
}
export function TicketDetailPage({ periodType, period, ticketId, onNavigate, onOpenTicketChange, returnPath }: TicketDetailPageProps) {
const initialGlobalMonthFilter = periodType === "all" && period !== "all" ? period : currentMonth();
const [data, setData] = useState<TicketPeriod | null>(null);
const [loadingId, setLoadingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [savingTicket, setSavingTicket] = useState(false);
const [savingFavorite, setSavingFavorite] = useState(false);
const [isFavorite, setIsFavorite] = useState(false);
const [editTicketNumber, setEditTicketNumber] = useState("");
const [editTicketTitle, setEditTicketTitle] = useState("");
const [editOrganizationId, setEditOrganizationId] = useState("");
const [editOrganizationName, setEditOrganizationName] = useState<string | null>(null);
const [editWorkType, setEditWorkType] = useState<WorkType>("support");
const [editingSession, setEditingSession] = useState<SessionEntry | null>(null);
const [pendingProjectDelete, setPendingProjectDelete] = useState<{ projectId: string } | null>(null);
const [editSessionOrganizationId, setEditSessionOrganizationId] = useState("");
const [editSessionOrganizationName, setEditSessionOrganizationName] = useState<string | null>(null);
const [editSessionActivity, setEditSessionActivity] = useState("");
const [editSessionWorkType, setEditSessionWorkType] = useState<WorkType>("support");
const [editSessionProjectTeamspaceEntryId, setEditSessionProjectTeamspaceEntryId] = useState("");
const [editSessionDay, setEditSessionDay] = useState("");
const [editSessionStartTime, setEditSessionStartTime] = useState("");
const [editSessionEndTime, setEditSessionEndTime] = useState("");
const [savingSessionDetails, setSavingSessionDetails] = useState(false);
const [dayBillingInputs, setDayBillingInputs] = useState<Record<string, string>>({});
const [savingDayBillingKey, setSavingDayBillingKey] = useState<string | null>(null);
const [ticketSession, setTicketSession] = useState<TicketSessionFormState>(() => emptyTicketSessionForm());
const [savingTicketSession, setSavingTicketSession] = useState(false);
const [globalMonthFilter, setGlobalMonthFilter] = useState(initialGlobalMonthFilter);
const [globalStatusFilter, setGlobalStatusFilter] = useState<"all" | "open" | "billable" | "billed" | "non_billable">("all");
const [globalSourceFilter, setGlobalSourceFilter] = useState<"all" | "manual" | "recurring">("all");
const [editingProject, setEditingProject] = useState(false);
const [savingProject, setSavingProject] = useState(false);
const [deletingEmptyProject, setDeletingEmptyProject] = useState(false);
const [savingProjectStatus, setSavingProjectStatus] = useState(false);
const [projectForm, setProjectForm] = useState<ProjectEditFormState>({
title: "",
organizationId: "",
organizationName: null,
description: "",
startsOn: "",
endsOn: "",
teamspaceEntries: [
{
clientId: projectEntryId(),
teamspaceProject: "",
hourBudget: "",
budgetSyncDisabled: false,
manualConsumption: "",
isDefault: true
}
]
});
const [todoFilter, setTodoFilter] = useState<"open" | "all" | "done">("open");
const [expandedSessionIds, setExpandedSessionIds] = useState<string[]>([]);
const [projectDescriptionExpanded, setProjectDescriptionExpanded] = useState(false);
const [teamspacePreparation, setTeamspacePreparation] = useState<{ day: string; label: string; text: string } | null>(null);
async function load() {
try {
setData(
periodType === "all"
? await getTicketDetails(ticketId, {
month: globalMonthFilter,
status: globalStatusFilter,
source: globalSourceFilter
})
: await getTicketPeriod(periodType, period, ticketId)
);
} catch (error) {
toast.error("Ticket konnte nicht geladen werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
}
}
useEffect(() => {
void load();
}, [periodType, period, ticketId, globalMonthFilter, globalStatusFilter, globalSourceFilter]);
useEffect(() => {
if (periodType !== "all") {
return;
}
setGlobalMonthFilter(period !== "all" ? period : currentMonth());
}, [periodType, period, ticketId]);
useEffect(() => {
const nextInputs = Object.fromEntries((data?.dayBillings ?? []).map((billing) => [billing.day, formatHoursInput(billing.billed_minutes)]));
setDayBillingInputs(nextInputs);
}, [data?.dayBillings]);
useEffect(() => {
if (!data?.ticket) {
return;
}
setEditTicketNumber(data.ticket.ticket_number);
setEditTicketTitle(data.ticket.title ?? "");
setEditOrganizationId(data.ticket.organization_id ?? "");
setEditOrganizationName(data.ticket.organization_name ?? null);
setEditWorkType(data.ticket.work_type ?? "support");
const loadedProjectEntries = data.project ? projectTeamspaceEntries(data.project) : [];
setTicketSession((current) => ({
...current,
organizationId: data.ticket.organization_id ?? current.organizationId,
organizationName: data.ticket.organization_name ?? current.organizationName,
projectTeamspaceEntryId: loadedProjectEntries.length === 1 ? loadedProjectEntries[0].id : current.projectTeamspaceEntryId,
workType: data.ticket.work_type ?? current.workType
}));
}, [data?.ticket, data?.project]);
useEffect(() => {
setProjectDescriptionExpanded(false);
}, [data?.project?.id]);
const ticket = data?.ticket;
const project = data?.project ?? null;
const isRecurringBillingTicket = ticketHasRecurringBilling(ticket);
const projectDescription = project ? combinedProjectDescription(project) : "";
const projectEntries = useMemo(() => (project ? projectTeamspaceEntries(project) : []), [project]);
const budgetedProjectEntries = useMemo(() => (project ? budgetedProjectTeamspaceEntries(project) : []), [project]);
const hasMultipleProjectTeamspaceEntries = projectEntries.length > 1;
const showBudgetedProjectEntries = budgetedProjectEntries.length > 1;
const requiresProjectTeamspaceEntry = Boolean(project && hasMultipleProjectTeamspaceEntries);
const projectConsumptionMinutes = project?.consumption_minutes ?? 0;
const projectBudgetMinutes = project?.hour_budget_minutes ?? null;
const projectConsumptionUsagePercent = project ? projectConsumptionPercent(projectConsumptionMinutes, projectBudgetMinutes) : null;
const projectRemainingMinutes = projectBudgetMinutes && projectBudgetMinutes > 0 ? projectBudgetMinutes - projectConsumptionMinutes : null;
const canEditProject = project?.can_edit !== false;
const canEditTicketData = !project || canEditProject;
const isProject = Boolean(project);
const isGlobalTicket = periodType === "all";
const isPeriodClosed = Boolean(data?.closed);
const periodLabel = periodType === "month" ? "Monat" : periodType === "day" ? "Tag" : "Ticket";
const sessionsScopeLabel = isGlobalTicket
? globalMonthFilter === "all"
? "im gesamten Ticketverlauf"
: `im Monat ${globalMonthFilter}`
: `im ${periodLabel.toLowerCase()} ${period}`;
const teamspaceLabel = isGlobalTicket || periodType === "month" ? "Teamspace gesamt" : "Teamspace Tag";
const availableMonths = data?.availableMonths ?? [];
const selectedMonthHasSessions = availableMonths.some((month) => month.month === globalMonthFilter);
const dayBillingMap = useMemo(() => new Map((data?.dayBillings ?? []).map((billing) => [billing.day, billing.billed_minutes])), [data?.dayBillings]);
const savedDayBillingInput = (day: string) => formatHoursInput(dayBillingMap.get(day));
const isDayBillingDirty = (day: string) => (dayBillingInputs[day] ?? "") !== savedDayBillingInput(day);
const sessionGroups = useMemo(() => {
const groups = new Map<
string,
{ key: string; label: string; totalMinutes: number; billableMinutes: number; nonBillableMinutes: number; openMinutes: number; sessions: SessionEntry[] }
>();
for (const session of data?.sessions ?? []) {
const key = sessionDayKey(session.started_at);
const group = groups.get(key);
const billedMinutes = session.billing_status === "billed" ? session.rounded_minutes : 0;
const billableMinutes = session.billing_status === "billable" ? session.rounded_minutes : 0;
const nonBillableMinutes = session.billing_status === "non_billable" ? session.rounded_minutes : 0;
const openMinutes = session.billing_status === null ? session.rounded_minutes : 0;
if (group) {
group.sessions.push(session);
group.totalMinutes += billedMinutes;
group.billableMinutes += billableMinutes;
group.nonBillableMinutes += nonBillableMinutes;
group.openMinutes += openMinutes;
continue;
}
groups.set(key, {
key,
label: formatDate(session.started_at),
totalMinutes: billedMinutes,
billableMinutes,
nonBillableMinutes,
openMinutes,
sessions: [session]
});
}
return Array.from(groups.values());
}, [data?.sessions]);
const sessionIds = useMemo(() => sessionGroups.flatMap((group) => group.sessions.map((session) => session.id)), [sessionGroups]);
const allSessionsExpanded = sessionIds.length > 0 && sessionIds.every((sessionId) => expandedSessionIds.includes(sessionId));
const periodTotalMinutes = sessionGroups.reduce((sum, group) => sum + group.totalMinutes, 0);
const periodTeamspaceMinutes = Array.from(dayBillingMap.values()).reduce((sum, minutes) => sum + Number(minutes ?? 0), 0);
const ticketDataDirty = Boolean(
ticket &&
(editTicketNumber !== ticket.ticket_number ||
editTicketTitle !== (ticket.title ?? "") ||
editOrganizationId !== (ticket.organization_id ?? "") ||
editWorkType !== (ticket.work_type ?? "support"))
);
const todos = data?.todos ?? [];
const visibleTodos = todoFilter === "all" ? todos : todos.filter((todo) => todo.status === todoFilter);
const todoCounts = {
open: todos.filter((todo) => todo.status === "open").length,
done: todos.filter((todo) => todo.status === "done").length,
all: todos.length
};
const hasUnsavedChanges = ticketDataDirty || sessionGroups.some((group) => isDayBillingDirty(group.key));
useEffect(() => {
setExpandedSessionIds((current) => current.filter((sessionId) => sessionIds.includes(sessionId)));
}, [sessionIds]);
useEffect(() => {
if (!ticket) {
return;
}
const ticketMonth = isGlobalTicket ? globalMonthFilter : periodType === "day" ? period.slice(0, 7) : period;
onOpenTicketChange?.({
key: `ticket:${ticket.id}`,
ticketId: ticket.id,
ticketNumber: ticket.ticket_number,
periodType: "all",
period: ticketMonth,
path: `/tickets/${ticket.id}?month=${ticketMonth}`,
returnPath,
dirty: hasUnsavedChanges
});
}, [ticket, periodType, period, isGlobalTicket, globalMonthFilter, returnPath, hasUnsavedChanges, onOpenTicketChange]);
useEffect(() => {
let cancelled = false;
if (!ticket?.ticket_number) {
setIsFavorite(false);
return;
}
async function loadFavoriteStatus() {
try {
const result = await getDashboardPreference();
const favorites = Array.isArray(result.preference.favorites) ? result.preference.favorites : [];
if (!cancelled) {
setIsFavorite(favorites.some((favorite) => favorite.ticketNumber === ticket?.ticket_number));
}
} catch {
if (!cancelled) {
setIsFavorite(false);
}
}
}
void loadFavoriteStatus();
return () => {
cancelled = true;
};
}, [ticket?.ticket_number]);
async function setBilling(sessionId: string, billingStatus: BillingStatus) {
if (isPeriodClosed && billingStatus !== null) {
toast.warning("Monat ist abgeschlossen", {
description: "Öffne den Monat zuerst wieder, um Bewertungen zu ändern."
});
return;
}
setLoadingId(sessionId);
try {
await updateSessionBilling(sessionId, billingStatus);
await load();
} catch (error) {
toast.error("Status konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setLoadingId(null);
}
}
function toggleSessionDetails(sessionId: string) {
setExpandedSessionIds((current) =>
current.includes(sessionId) ? current.filter((id) => id !== sessionId) : [...current, sessionId]
);
}
function toggleAllSessionDetails() {
setExpandedSessionIds(allSessionsExpanded ? [] : sessionIds);
}
async function saveDayBilling(day: string) {
if (!ticket) {
return;
}
if (isPeriodClosed) {
toast.warning("Monat ist abgeschlossen", {
description: "Öffne den Monat zuerst wieder, um Teamspace-Zeiten zu ändern."
});
return;
}
const parsedMinutes = parseHoursInput(dayBillingInputs[day] ?? "");
if (parsedMinutes === undefined) {
toast.error("Teamspace-Zeit prüfen", {
description: "Bitte Stunden als positive Zahl eintragen, z.B. 1,5."
});
return;
}
const currentMinutes = dayBillingMap.get(day) ?? null;
if (parsedMinutes === currentMinutes) {
return;
}
setSavingDayBillingKey(day);
try {
await updateTicketDayBilling(ticket.id, day, parsedMinutes);
toast.success("Zeit gespeichert");
await load();
} catch (error) {
toast.error("Zeit konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingDayBillingKey(null);
}
}
async function saveTicketData(event: FormEvent) {
event.preventDefault();
if (!ticket) {
return;
}
if (!canEditTicketData) {
toast.error("Projekt ist geteilt", {
description: "Nur der Zammad-Owner kann Ticket- und Projektdaten ändern."
});
return;
}
if (!editOrganizationId) {
toast.error("Organisation wählen");
return;
}
const removeProjectData = Boolean(project && editWorkType === "support");
if (removeProjectData) {
const confirmed = window.confirm(
`Ticket "${ticket.title || ticket.ticket_number}" auf Support umstellen? Projektdaten, Kontingent und Teamspace-Zeiten werden entfernt. Sessions und ToDos bleiben erhalten.`
);
if (!confirmed) {
return;
}
}
setSavingTicket(true);
try {
await updateTicket(ticket.id, {
ticketNumber: editTicketNumber,
title: editTicketTitle || null,
organizationId: editOrganizationId,
workType: editWorkType,
removeProjectData
});
toast.success("Ticketdaten gespeichert", {
description: editWorkType === "consulting" ? "Das Ticket ist jetzt als Projekt angelegt." : "Organisation und Art wurden auf die vorhandenen Sessions übernommen."
});
await load();
} catch (error) {
toast.error("Ticketdaten konnten nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingTicket(false);
}
}
function openProjectEditor() {
if (!project) {
return;
}
if (project.can_edit === false) {
toast.error("Projekt ist geteilt", {
description: "Nur der Zammad-Owner kann die Projektdaten bearbeiten."
});
return;
}
setProjectForm(projectEditForm(project));
setEditingProject(true);
}
async function saveProjectData(event: FormEvent) {
event.preventDefault();
if (!project || !ticket) {
return;
}
if (project.can_edit === false) {
toast.error("Projekt ist geteilt", {
description: "Nur der Zammad-Owner kann die Projektdaten bearbeiten."
});
return;
}
if (!projectForm.organizationId) {
toast.error("Organisation wählen");
return;
}
const teamspaceEntries = parseProjectTeamspaceEntryForms(projectForm.teamspaceEntries);
if (!teamspaceEntries) {
toast.error("Teamspace-Einträge prüfen", {
description: "Bitte Stunden als Zahl eintragen, z.B. 12,5."
});
return;
}
const defaultTeamspaceEntry = teamspaceEntries.find((entry) => entry.isDefault) ?? teamspaceEntries[0];
setSavingProject(true);
try {
await updateProject(project.id, {
ticketNumber: ticket.ticket_number,
title: projectForm.title || null,
organizationId: projectForm.organizationId,
teamspaceProject: defaultTeamspaceEntry.teamspaceProject,
teamspaceEntries,
description: projectForm.description,
goals: "",
startsOn: projectForm.startsOn || null,
endsOn: projectForm.endsOn || null,
hourBudgetMinutes: defaultTeamspaceEntry.hourBudgetMinutes,
manualConsumptionMinutes: defaultTeamspaceEntry.manualConsumptionMinutes
});
toast.success("Projekt gespeichert");
setEditingProject(false);
await load();
} catch (error) {
toast.error("Projekt konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingProject(false);
}
}
async function setProjectClosed(closed: boolean) {
if (!project) {
return;
}
if (project.can_edit === false) {
toast.error("Projekt ist geteilt", {
description: "Nur der Zammad-Owner kann den Projektstatus ändern."
});
return;
}
setSavingProjectStatus(true);
try {
await updateProjectStatus(project.id, closed);
toast.success(closed ? "Projekt geschlossen" : "Projekt wieder geöffnet");
await load();
} catch (error) {
toast.error("Projektstatus konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingProjectStatus(false);
}
}
async function submitTicketSession(event: FormEvent) {
event.preventDefault();
if (!ticket) {
return;
}
if (isRecurringBillingTicket) {
toast.error("Fixe Abrechnung", {
description: "Für fixe Abrechnungen dürfen keine Sessions nachgetragen werden. Bitte die Definition bearbeiten."
});
return;
}
const effectiveOrganizationId = ticket.organization_id ?? ticketSession.organizationId;
const effectiveWorkType = ticket.work_type ?? ticketSession.workType;
if (!effectiveOrganizationId) {
toast.error("Organisation wählen");
return;
}
if (effectiveWorkType === "consulting" && requiresProjectTeamspaceEntry && !ticketSession.projectTeamspaceEntryId) {
toast.error("Teamspace-Eintrag wählen", {
description: "Dieses Projekt hat mehrere Teamspace-Einträge."
});
return;
}
const startedAt = new Date(`${ticketSession.day}T${ticketSession.startTime}:00`);
const endedAt = new Date(`${ticketSession.day}T${ticketSession.endTime}:00`);
if (Number.isNaN(startedAt.getTime()) || Number.isNaN(endedAt.getTime())) {
toast.error("Datum oder Uhrzeit prüfen");
return;
}
if (endedAt <= startedAt) {
toast.error("Ende muss nach Beginn liegen");
return;
}
if (editSessionWorkType === "consulting" && requiresProjectTeamspaceEntry && !editSessionProjectTeamspaceEntryId) {
toast.error("Teamspace-Eintrag wählen", {
description: "Dieses Projekt hat mehrere Teamspace-Einträge."
});
return;
}
const durationSeconds = Math.floor((endedAt.getTime() - startedAt.getTime()) / 1000);
setSavingTicketSession(true);
try {
await createSession({
ticketNumber: ticket.ticket_number,
organizationId: effectiveOrganizationId,
activity: ticketSession.activity,
workType: effectiveWorkType,
startedAt: startedAt.toISOString(),
endedAt: endedAt.toISOString(),
durationSeconds,
projectTeamspaceEntryId: effectiveWorkType === "consulting" && requiresProjectTeamspaceEntry ? ticketSession.projectTeamspaceEntryId : null,
billingStatus: ticketSession.billingStatus
});
toast.success("Session nachgetragen", {
description: "Der Eintrag wurde diesem Ticket zugeordnet. Betroffene Abschlüsse wurden wieder geöffnet."
});
setTicketSession({
...emptyTicketSessionForm(),
organizationId: ticket.organization_id ?? "",
organizationName: ticket.organization_name ?? null,
projectTeamspaceEntryId: "",
workType: ticket.work_type ?? "support",
day: ticketSession.day,
billingStatus: null
});
await load();
} catch (error) {
toast.error("Session konnte nicht nachgetragen werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingTicketSession(false);
}
}
function openSessionEditor(session: SessionEntry) {
setEditingSession(session);
setEditSessionOrganizationId(session.organization_id ?? "");
setEditSessionOrganizationName(session.organization_name ?? null);
setEditSessionActivity(session.activity);
setEditSessionWorkType(session.work_type);
setEditSessionProjectTeamspaceEntryId(session.project_teamspace_entry_id ?? "");
setEditSessionDay(toDateLocalValue(session.started_at));
setEditSessionStartTime(toTimeLocalValue(session.started_at));
setEditSessionEndTime(toTimeLocalValue(session.ended_at));
}
function openTeamspacePreparation(group: (typeof sessionGroups)[number]) {
setTeamspacePreparation({
day: group.key,
label: group.label,
text: teamspacePreparationText(ticket, group.sessions)
});
}
async function copyTeamspacePreparation() {
if (!teamspacePreparation) {
return;
}
try {
await writeTextToClipboard(teamspacePreparation.text);
toast.success("TS Aufbereitung kopiert", {
description: teamspacePreparation.label
});
} catch (error) {
toast.error("TS Aufbereitung konnte nicht kopiert werden", {
description: error instanceof Error ? error.message : "Zwischenablage nicht verfügbar"
});
}
}
async function saveSessionData(event: FormEvent) {
event.preventDefault();
if (!editingSession) {
return;
}
if (!editSessionOrganizationId) {
toast.error("Organisation wählen");
return;
}
const startedAt = new Date(`${editSessionDay}T${editSessionStartTime}:00`);
const endedAt = new Date(`${editSessionDay}T${editSessionEndTime}:00`);
if (Number.isNaN(startedAt.getTime()) || Number.isNaN(endedAt.getTime())) {
toast.error("Beginn und Ende prüfen");
return;
}
if (endedAt <= startedAt) {
toast.error("Ende muss nach Beginn liegen");
return;
}
const removeProjectData = Boolean(project && editingSession.work_type === "consulting" && editSessionWorkType === "support");
if (removeProjectData) {
const confirmed = window.confirm(
`Session auf Support umstellen? Falls dadurch keine Consulting-Sessions mehr für "${ticket?.title || ticket?.ticket_number || "dieses Ticket"}" bleiben, werden Projektdaten, Kontingent und Teamspace-Zeiten entfernt. Sessions und ToDos bleiben erhalten.`
);
if (!confirmed) {
return;
}
}
setSavingSessionDetails(true);
try {
await updateSessionDetails(editingSession.id, {
organizationId: editSessionOrganizationId,
activity: editSessionActivity,
workType: editSessionWorkType,
removeProjectData,
projectTeamspaceEntryId: editSessionWorkType === "consulting" && requiresProjectTeamspaceEntry ? editSessionProjectTeamspaceEntryId : null,
startedAt: startedAt.toISOString(),
endedAt: endedAt.toISOString()
});
toast.success("Session aktualisiert");
setEditingSession(null);
await load();
} catch (error) {
toast.error("Session konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingSessionDetails(false);
}
}
async function removeSession(session: SessionEntry) {
const confirmed = window.confirm(`Session vom ${formatDateTime(session.started_at)} wirklich löschen?`);
if (!confirmed) {
return;
}
setDeletingId(session.id);
try {
const result = await deleteSession(session.id);
if (result.deleted.projectDeleteAvailable && result.deleted.project_id) {
setPendingProjectDelete({ projectId: result.deleted.project_id });
toast.success("Session gelöscht", {
description: "Für dieses Projekt sind keine Sessions mehr vorhanden."
});
return;
}
if (result.deleted.ticketDeleted || result.deleted.userTicketEmpty) {
toast.success("Letzte Session gelöscht", {
description: result.deleted.ticketDeleted ? "Das leere Ticket wurde entfernt." : "Für dich gibt es zu diesem Ticket keine Einträge mehr."
});
onNavigate(returnPath);
return;
}
toast.success("Session gelöscht", {
description: "Betroffene Abschlüsse wurden wieder geöffnet."
});
await load();
} catch (error) {
toast.error("Session konnte nicht gelöscht werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setDeletingId(null);
}
}
async function keepEmptyProject() {
setPendingProjectDelete(null);
toast.success("Projekt behalten");
await load();
}
async function deleteEmptyProject() {
if (!pendingProjectDelete) {
return;
}
setDeletingEmptyProject(true);
try {
await deleteProject(pendingProjectDelete.projectId);
toast.success("Projekt gelöscht");
setPendingProjectDelete(null);
onNavigate(returnPath);
} catch (error) {
toast.error("Projekt konnte nicht gelöscht werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setDeletingEmptyProject(false);
}
}
async function toggleTicketFavorite() {
if (!ticket?.ticket_number) {
return;
}
setSavingFavorite(true);
try {
if (isFavorite) {
await removeFavoriteTicket(ticket.ticket_number);
setIsFavorite(false);
toast.success("Favorit entfernt", {
description: ticket.ticket_number
});
return;
}
await addFavoriteTicket(ticket.ticket_number);
setIsFavorite(true);
toast.success("Favorit gespeichert", {
description: ticket.ticket_number
});
} catch (error) {
toast.error(isFavorite ? "Favorit konnte nicht entfernt werden" : "Favorit konnte nicht gespeichert werden", {
description: error instanceof Error ? error.message : "Unbekannter Fehler"
});
} finally {
setSavingFavorite(false);
}
}
return (
<div className="space-y-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div>
<Button variant="ghost" size="sm" className="-ml-2 mb-1 h-8" onClick={() => onNavigate(returnPath)}>
<ArrowLeft className="size-4" />
Zurück
</Button>
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-xl font-semibold tracking-normal sm:text-2xl">{ticket?.title || ticket?.ticket_number || "Ticket"}</h2>
{isProject ? <Badge variant="outline">Projekt</Badge> : null}
<ZammadStateBadge stateId={ticket?.zammad_state_id} />
<ZammadPriorityBadge priorityId={ticket?.zammad_priority_id} />
{(periodType === "month" || (isGlobalTicket && globalMonthFilter !== "all")) && data?.closed ? <Badge variant="outline">Monat geschlossen</Badge> : null}
{ticket?.ticket_number ? <CopyTicketButton ticketNumber={ticket.ticket_number} /> : null}
</div>
<p className="text-sm text-muted-foreground">
{ticket?.title ? `${ticket.ticket_number} · ` : ""}
Sessions {sessionsScopeLabel}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{ticket?.ticket_number ? (
<Button type="button" size="sm" variant={isFavorite ? "default" : "secondary"} disabled={savingFavorite} onClick={() => void toggleTicketFavorite()}>
<Star className={cn("size-4", isFavorite && "fill-current")} />
{isFavorite ? "Favorit entfernen" : "Favorit"}
</Button>
) : null}
<Badge variant={data?.openCount === 0 ? "success" : "warning"}>
{data?.openCount === 0 ? "Bewertet" : `${data?.openCount ?? 0} offen`}
</Badge>
</div>
</div>
{(periodType === "month" || (isGlobalTicket && globalMonthFilter !== "all")) && data?.closed ? (
<Alert variant="success" className="py-3 text-sm">
Dieser Monat ist abgeschlossen. Bewertungen und Änderungen sind geschützt, bis du den Monat im Monatsabschluss wieder öffnest.
</Alert>
) : null}
<div className={cn("grid gap-4", isGlobalTicket && "details:grid-cols-2")}>
{isGlobalTicket ? (
<Card>
<CardHeader className="p-4">
<CardTitle>Filter</CardTitle>
<CardDescription>Grenzt die Sessionliste dieses Tickets ein. Die Ticketdaten selbst bleiben global.</CardDescription>
</CardHeader>
<CardContent className="grid gap-3 px-4 pb-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-month-filter">Monat</label>
<select
id="ticket-month-filter"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={globalMonthFilter}
onChange={(event) => setGlobalMonthFilter(event.currentTarget.value)}
>
<option value="all">Alle Monate</option>
{globalMonthFilter !== "all" && !selectedMonthHasSessions ? <option value={globalMonthFilter}>{globalMonthFilter} (0)</option> : null}
{availableMonths.map((month) => (
<option key={month.month} value={month.month}>
{month.month} ({month.session_count})
</option>
))}
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-status-filter">Bewertung</label>
<select
id="ticket-status-filter"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={globalStatusFilter}
onChange={(event) => setGlobalStatusFilter(event.currentTarget.value as typeof globalStatusFilter)}
>
<option value="all">Alle Bewertungen</option>
<option value="open">Offen</option>
<option value="billable">Abrechenbar</option>
<option value="non_billable">Nicht abrechenbar</option>
</select>
</div>
</CardContent>
</Card>
) : null}
<Card>
<CardHeader className="p-4">
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle>Ticketdaten</CardTitle>
<CardDescription>
{canEditTicketData
? "Änderungen an Organisation und Art werden auf alle vorhandenen Sessions dieses Tickets übernommen."
: "Dieses Projekt ist geteilt. Nur der Zammad-Owner kann Ticket- und Projektdaten ändern."}
</CardDescription>
</div>
<HelpLink anchor="ticketdaten" label="Hilfe zu Ticketdaten" />
</div>
</CardHeader>
<CardContent className="px-4 pb-4">
<form className="grid grid-cols-2 gap-3 [@media_(min-width:85rem)_and_(max-width:108.124rem)]:grid-cols-1 xxl:grid-cols-2" onSubmit={saveTicketData}>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="edit-ticket-number">Ticketnummer</label>
<Input id="edit-ticket-number" value={editTicketNumber} disabled={!canEditTicketData} onChange={(event) => setEditTicketNumber(event.currentTarget.value)} required />
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="edit-ticket-work-type">Art</label>
<select
id="edit-ticket-work-type"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={editWorkType}
disabled={!canEditTicketData}
onChange={(event) => setEditWorkType(event.currentTarget.value as WorkType)}
>
<option value="support">Support</option>
<option value="consulting">Consulting</option>
</select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="edit-ticket-title">Titel</label>
<Input id="edit-ticket-title" value={editTicketTitle} disabled={!canEditTicketData} onChange={(event) => setEditTicketTitle(event.currentTarget.value)} placeholder="optional" />
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="edit-ticket-organization">Organisation</label>
{ticket?.customer_name && !ticket.organization_id ? (
<p className="text-xs text-muted-foreground">Bisheriger Freitext: {ticket.customer_name}</p>
) : null}
<OrganizationSelect
value={editOrganizationId}
selectedName={editOrganizationName}
disabled={!canEditTicketData}
onChange={(organization) => {
setEditOrganizationId(organization.id);
setEditOrganizationName(organization.name);
}}
required
/>
</div>
<Button type="submit" className="col-span-2 justify-self-end [@media_(min-width:85rem)_and_(max-width:108.124rem)]:col-span-1 xxl:col-span-2" disabled={!canEditTicketData || savingTicket}>
<Save className="size-4" />
{savingTicket ? "Speichert..." : "Speichern"}
</Button>
</form>
</CardContent>
</Card>
</div>
<div className={cn("grid gap-4", project && "xl:grid-cols-2")}>
{project ? (
<Card>
<CardHeader className="p-4">
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle className="flex items-center gap-2">
<FolderKanban className="size-5 text-muted-foreground" />
Projekt
{project.closed_at ? <Badge variant="secondary">Geschlossen</Badge> : <Badge variant="success">Offen</Badge>}
<ZammadStateBadge stateId={project.zammad_state_id} />
<ZammadPriorityBadge priorityId={project.zammad_priority_id} />
{!canEditProject ? <Badge variant="outline">geteilt</Badge> : null}
{project.close_review_required ? <Badge variant="warning">TS/TT prüfen</Badge> : null}
{(project.unassigned_teamspace_session_count ?? 0) > 0 ? <Badge variant="warning">{project.unassigned_teamspace_session_count} ohne TS</Badge> : null}
</CardTitle>
<CardDescription>
{!canEditProject && project.owner_display_name
? `Eigentümer: ${project.owner_display_name}`
: showBudgetedProjectEntries
? `${budgetedProjectEntries.length} budgetierte Teamspace-Einträge`
: budgetedProjectEntries[0]?.teamspace_project || project.teamspace_project || "Kein Teamspace-Projekt hinterlegt"}
</CardDescription>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
type="button"
size="sm"
variant="secondary"
disabled={!canEditProject || savingProjectStatus}
onClick={() => void setProjectClosed(!project.closed_at)}
>
{project.closed_at ? <RotateCcw className="size-4" /> : <CheckCircle2 className="size-4" />}
{project.closed_at ? "Öffnen" : "Schließen"}
</Button>
<Button type="button" size="sm" variant="secondary" disabled={!canEditProject} onClick={openProjectEditor}>
<Pencil className="size-4" />
Bearbeiten
</Button>
<HelpLink anchor="projekte" label="Hilfe zu Projekten" />
</div>
</div>
</CardHeader>
<CardContent className="space-y-3 px-4 pb-4">
{(project.unassigned_teamspace_session_count ?? 0) > 0 ? (
<Alert variant="warning">
<div className="font-medium">Nicht zugeordnete Sessions</div>
<div className="text-sm text-muted-foreground">
{project.unassigned_teamspace_session_count} Session(s) haben keinen Teamspace-Eintrag. Bitte über die Session-Bearbeitung neu zuordnen.
</div>
</Alert>
) : null}
{project.close_review_required ? (
<Alert variant="warning">
<div className="font-medium">Zeiten prüfen</div>
<div className="text-sm text-muted-foreground">
Zammad meldet dieses Consulting-Ticket als geschlossen. Bitte Zeiten in Teamspace und TicketTracker prüfen und das Projekt danach schließen.
</div>
</Alert>
) : null}
<div className="flex flex-wrap gap-2 text-sm">
<Badge variant="secondary">Zeitraum {project.starts_on || "offen"} - {project.ends_on || "offen"}</Badge>
<Badge variant="secondary">Kontingent {projectBudgetMinutes ? formatMinutes(projectBudgetMinutes) : "offen"}</Badge>
<Badge variant="secondary">Verbrauch {formatMinutes(projectConsumptionMinutes)}</Badge>
<Badge variant={projectRemainingMinutes !== null && projectRemainingMinutes < 0 ? "destructive" : "secondary"}>{projectRemainingLabel(projectRemainingMinutes)}</Badge>
{showBudgetedProjectEntries ? <Badge variant="outline">{budgetedProjectEntries.length} Budgets</Badge> : null}
</div>
<div className="space-y-2">
<div>
<div className="mb-1 flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span>Budgetverbrauch</span>
<span className="shrink-0 text-right">
{projectBudgetMinutes && projectBudgetMinutes > 0
? `${formatMinutes(projectConsumptionMinutes)} / ${formatMinutes(projectBudgetMinutes)} · ${projectRemainingLabel(projectRemainingMinutes)}`
: `${formatMinutes(projectConsumptionMinutes)} / offen`}
</span>
</div>
<div
className="h-2 overflow-hidden rounded-full bg-muted"
title={projectConsumptionUsagePercent !== null ? `${projectConsumptionUsagePercent}% Verbrauch` : "ohne Gesamtbudget"}
aria-label={projectConsumptionUsagePercent !== null ? `${projectConsumptionUsagePercent}% Verbrauch` : "ohne Gesamtbudget"}
>
<div
className={cn("h-full rounded-full", projectConsumptionUsagePercent === null ? "bg-muted-foreground/20" : projectConsumptionBarClass(projectConsumptionUsagePercent))}
style={{ width: `${projectConsumptionUsagePercent === null ? 0 : Math.min(100, projectConsumptionUsagePercent)}%` }}
/>
</div>
</div>
{showBudgetedProjectEntries ? (
<div className="grid gap-1.5 md:grid-cols-2">
{budgetedProjectEntries.map((entry) => {
const consumption = Number(entry.consumption_minutes ?? 0);
const percent = projectConsumptionPercent(consumption, entry.hour_budget_minutes);
const label = entry.teamspace_project || (entry.is_default ? "Standard" : "Ohne Teamspace-ID");
return (
<div key={entry.id} className="rounded-md border bg-background/50 px-2 py-1">
<div className="mb-1 flex min-w-0 items-center justify-between gap-2 text-[11px]">
<span className="truncate text-muted-foreground">
{label}
{entry.is_default ? " · Standard" : ""}
{entry.budget_sync_disabled ? " · Budget geschützt" : ""}
</span>
<span className="shrink-0 font-medium">
{formatMinutes(consumption)} / {entry.hour_budget_minutes ? formatMinutes(entry.hour_budget_minutes) : "offen"}
</span>
</div>
<div className="h-1 overflow-hidden rounded-full bg-muted">
<div
className={cn("h-full rounded-full", percent === null ? "bg-muted-foreground/20" : projectConsumptionBarClass(percent))}
style={{ width: `${percent === null ? 0 : Math.min(100, percent)}%` }}
/>
</div>
</div>
);
})}
</div>
) : null}
</div>
<div className="text-sm">
<div className="min-w-0">
<div className="mb-1 flex items-center gap-2 font-medium">
<FolderKanban className="size-4 text-muted-foreground" />
Beschreibung/Ziele
</div>
<p className={cn("whitespace-pre-wrap text-muted-foreground", !projectDescriptionExpanded && "line-clamp-4")}>
{projectDescription || "Noch keine Beschreibung/Ziele."}
</p>
{projectDescription ? (
<Button
type="button"
size="sm"
variant="ghost"
className="mt-1 h-7 px-2 text-xs"
onClick={() => setProjectDescriptionExpanded((current) => !current)}
>
{projectDescriptionExpanded ? (
<>
<ChevronUp className="size-3.5" />
Einklappen
</>
) : (
<>
<ChevronDown className="size-3.5" />
Vollständig anzeigen
</>
)}
</Button>
) : null}
</div>
</div>
</CardContent>
</Card>
) : null}
<Dialog open={editingProject} onOpenChange={setEditingProject}>
<DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Projekt bearbeiten</DialogTitle>
<DialogDescription>Projektinformationen zum geöffneten Ticket aktualisieren.</DialogDescription>
</DialogHeader>
<form className="space-y-4" onSubmit={saveProjectData}>
<div className="grid gap-3 lg:grid-cols-[minmax(220px,1fr)_minmax(220px,1fr)]">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="project-edit-title">Titel</label>
<Input
id="project-edit-title"
value={projectForm.title}
onChange={(event) => setProjectForm({ ...projectForm, title: event.currentTarget.value })}
placeholder="optional"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Organisation</label>
<OrganizationSelect
value={projectForm.organizationId}
selectedName={projectForm.organizationName}
onChange={(organization) =>
setProjectForm({
...projectForm,
organizationId: organization.id,
organizationName: organization.name
})
}
required
/>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="project-edit-start">Von</label>
<Input id="project-edit-start" type="date" value={projectForm.startsOn} onChange={(event) => setProjectForm({ ...projectForm, startsOn: event.currentTarget.value })} />
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="project-edit-end">Bis</label>
<Input id="project-edit-end" type="date" value={projectForm.endsOn} onChange={(event) => setProjectForm({ ...projectForm, endsOn: event.currentTarget.value })} />
</div>
</div>
<ProjectTeamspaceEntriesEditor
entries={projectForm.teamspaceEntries}
onChange={(teamspaceEntries) => setProjectForm({ ...projectForm, teamspaceEntries })}
/>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="project-edit-description">Beschreibung/Ziele</label>
<Textarea
id="project-edit-description"
className="min-h-32"
value={projectForm.description}
onChange={(event) => setProjectForm({ ...projectForm, description: event.currentTarget.value })}
/>
</div>
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="secondary"
disabled={savingProjectStatus}
onClick={() => void setProjectClosed(!project?.closed_at)}
>
{project?.closed_at ? <RotateCcw className="size-4" /> : <CheckCircle2 className="size-4" />}
{project?.closed_at ? "Wieder öffnen" : "Projekt schließen"}
</Button>
<Button type="submit" disabled={savingProject}>
<Save className="size-4" />
{savingProject ? "Speichert..." : "Projekt speichern"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
<Card>
<CardHeader className="p-4">
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle className="flex items-center gap-2">
<ClipboardList className="size-5 text-muted-foreground" />
ToDos
</CardTitle>
<CardDescription>Aufgaben zu diesem Ticket oder Projekt verwalten.</CardDescription>
</div>
<div className="flex shrink-0 items-center gap-2">
<div className="flex rounded-md border bg-muted/20 p-0.5">
{(["open", "all", "done"] as const).map((value) => (
<Button
key={value}
type="button"
size="sm"
variant={todoFilter === value ? "default" : "ghost"}
className="h-7 px-2 text-xs"
onClick={() => setTodoFilter(value)}
>
{value === "open" ? `Offen ${todoCounts.open}` : value === "done" ? `Erledigt ${todoCounts.done}` : `Alle ${todoCounts.all}`}
</Button>
))}
</div>
<HelpLink anchor="todos" label="Hilfe zu ToDos" />
</div>
</div>
</CardHeader>
<CardContent className="px-4 pb-4">
<TodoPanel ticketId={ticket?.id} todos={visibleTodos} onChanged={load} />
</CardContent>
</Card>
</div>
<Card>
<CardHeader className="gap-3 p-4 sm:flex-row sm:items-start sm:justify-between sm:space-y-0">
<div>
<CardTitle>Session-Einträge</CardTitle>
<CardDescription>Wähle für jede Session genau eine Bewertung aus oder lösche falsche Einträge.</CardDescription>
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm">
<span className="text-muted-foreground">Abgerechnet</span>
<span className="font-semibold">{formatMinutes(periodTotalMinutes)}</span>
</div>
<div className="flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm">
<span className="text-muted-foreground">{teamspaceLabel}</span>
<span className="font-semibold">{formatMinutes(periodTeamspaceMinutes)}</span>
</div>
<HelpLink anchor="ticketdetail" label="Hilfe zur Ticketdetailansicht" />
</div>
</CardHeader>
<CardContent className="px-4 pb-4">
{data?.sessions.length ? (
<div className="mb-3 flex justify-end">
<Button type="button" size="sm" variant="secondary" onClick={toggleAllSessionDetails}>
{allSessionsExpanded ? (
<>
<ChevronUp className="size-4" />
Alle einklappen
</>
) : (
<>
<ChevronDown className="size-4" />
Alle aufklappen
</>
)}
</Button>
</div>
) : null}
<div className="space-y-2">
{sessionGroups.map((group) => (
<div key={group.key} className="rounded-md border bg-background">
<div className="grid min-w-0 gap-2 border-b bg-muted/25 px-3 py-2 lg:grid-cols-[minmax(180px,1fr)_auto] lg:items-center">
<div className="min-w-0 text-left">
<p className="truncate font-medium">{group.label}</p>
<p className="text-xs text-muted-foreground">{group.sessions.length} Session(s)</p>
</div>
<div className="grid w-full gap-2 sm:grid-cols-[13rem_10rem_10rem_8rem] xl:w-auto xl:grid-cols-[13rem_10rem_10rem_8rem_auto] xl:items-center xl:justify-end">
<Button type="button" size="sm" variant="secondary" className="h-7 w-full justify-center" onClick={() => openTeamspacePreparation(group)}>
<ClipboardList className="size-3.5" />
TS Aufbereitung
</Button>
<Badge variant="outline" className="flex h-7 w-full justify-center whitespace-nowrap">
Abgerechnet {formatMinutes(group.totalMinutes)}
</Badge>
<Badge variant="outline" className="flex h-7 w-full justify-center whitespace-nowrap">
Abrechenbar {formatMinutes(group.billableMinutes)}
</Badge>
<Badge variant={group.openMinutes > 0 ? "warning" : "success"} className="flex h-7 w-full justify-center whitespace-nowrap">
Offen {formatMinutes(group.openMinutes)}
</Badge>
<div className="flex items-center gap-2 text-xs text-muted-foreground sm:col-span-4 xl:col-span-1">
<label htmlFor={`crm-billing-${group.key}`}>Teamspace</label>
<Input
id={`crm-billing-${group.key}`}
type="text"
className="h-7 w-24 bg-background text-right"
autoComplete="off"
inputMode="decimal"
value={dayBillingInputs[group.key] ?? ""}
disabled={isPeriodClosed || savingDayBillingKey === group.key}
placeholder="0"
onChange={(event) => {
const nextValue = event.currentTarget.value;
if (!isPartialHoursInput(nextValue)) {
return;
}
setDayBillingInputs((current) => ({
...current,
[group.key]: nextValue
}));
}}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
}
}}
/>
<span>h</span>
<Button
type="button"
size="sm"
className={cn("h-7 w-[104px]", !isDayBillingDirty(group.key) && "invisible")}
disabled={isPeriodClosed || !isDayBillingDirty(group.key) || savingDayBillingKey === group.key}
onMouseDown={(event) => event.preventDefault()}
onClick={() => void saveDayBilling(group.key)}
>
<Save className="size-3.5" />
{savingDayBillingKey === group.key ? "Speichert..." : "Speichern"}
</Button>
</div>
{group.nonBillableMinutes > 0 ? (
<Badge variant="secondary" className="flex h-7 w-full justify-center whitespace-nowrap sm:col-span-3 xl:col-span-1 xl:col-start-2">
Nicht {formatMinutes(group.nonBillableMinutes)}
</Badge>
) : null}
</div>
</div>
<div className="space-y-1.5 p-2 sm:p-3">
{group.sessions.map((session) => {
const expanded = expandedSessionIds.includes(session.id);
return (
<div key={session.id} className="ml-3 rounded-md border bg-card/40 sm:ml-6">
<div className="grid gap-2 p-2 lg:grid-cols-[220px_minmax(0,150px)_minmax(260px,1fr)_auto] lg:items-center">
<button
type="button"
className="flex min-w-0 items-center gap-2 rounded-md text-left text-sm text-muted-foreground hover:cursor-pointer hover:text-foreground focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
onClick={() => toggleSessionDetails(session.id)}
aria-expanded={expanded}
>
{expanded ? <ChevronUp className="size-4 shrink-0" /> : <ChevronDown className="size-4 shrink-0" />}
<span className="truncate">
{formatTimeRange(session.started_at, session.ended_at)}
</span>
</button>
<div className="flex min-w-0 flex-col items-start gap-1">
<Badge variant="outline" className="w-fit">{formatMinutes(session.rounded_minutes)}</Badge>
{session.recurring_billing_id ? <Badge variant="secondary">fix</Badge> : null}
{requiresProjectTeamspaceEntry ? (
session.project_teamspace_entry_id ? (
<Badge variant="info" className="max-w-full justify-start truncate">{session.project_teamspace_project || "Teamspace"}</Badge>
) : (
<Badge variant="warning">ohne Teamspace</Badge>
)
) : null}
</div>
<BillingButtons
session={session}
disabled={isPeriodClosed}
loading={loadingId === session.id}
onChange={(value) => setBilling(session.id, value)}
/>
<div className="flex gap-1 lg:justify-end">
<Button size="icon" variant="ghost" className="size-8" onClick={() => openSessionEditor(session)}>
<Pencil className="size-4" />
<span className="sr-only">Session bearbeiten</span>
</Button>
<Button
size="icon"
variant="ghost"
className="size-8 text-destructive hover:text-destructive"
disabled={deletingId === session.id}
onClick={() => removeSession(session)}
>
<Trash2 className="size-4" />
<span className="sr-only">Session löschen</span>
</Button>
</div>
</div>
{expanded ? (
<div className="border-t px-3 pb-3 pt-2">
<p className="whitespace-pre-wrap break-words text-sm font-medium">{session.activity}</p>
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span>{session.organization_name ?? session.customer_name}</span>
<span>{session.work_type === "support" ? "Support" : "Consulting"}</span>
<span>Erfasst {formatDateTime(session.created_at)}</span>
</div>
</div>
) : null}
</div>
);
})}
</div>
</div>
))}
</div>
{data?.sessions.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">Keine Sessions für dieses Ticket im gewählten Filter.</p>
) : null}
</CardContent>
</Card>
{isRecurringBillingTicket ? (
<Alert variant="warning">
<div className="font-medium">Fixe Abrechnung</div>
<div className="text-sm text-muted-foreground">Sessions für dieses Ticket werden ausschließlich aus der Definition erzeugt. Manuelles Nachtragen ist deaktiviert.</div>
</Alert>
) : (
<Card>
<CardHeader className="p-4">
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle>Session nachtragen</CardTitle>
<CardDescription>Neue Zeit direkt diesem Ticket zuordnen.</CardDescription>
</div>
<HelpLink anchor="session-nachtragen" label="Hilfe zum Nachtragen von Sessions" />
</div>
</CardHeader>
<CardContent className="px-4 pb-4">
<form className="space-y-4" onSubmit={submitTicketSession}>
{ticket?.organization_id && ticket.work_type ? (
<div className="grid gap-2 rounded-md border bg-muted/30 p-3 text-sm sm:grid-cols-[1fr_auto] sm:items-center">
<span className="font-medium">{ticket.organization_name ?? ticket.customer_name}</span>
<Badge variant="outline">{ticket.work_type === "support" ? "Support" : "Consulting"}</Badge>
</div>
) : (
<div className="grid gap-3 lg:grid-cols-[minmax(220px,1fr)_180px]">
<div className="space-y-2">
<label className="text-sm font-medium">Organisation</label>
{ticket?.customer_name && !ticket.organization_id ? (
<p className="text-xs text-muted-foreground">Bisheriger Freitext: {ticket.customer_name}</p>
) : null}
<OrganizationSelect
value={ticketSession.organizationId}
selectedName={ticketSession.organizationName}
onChange={(organization) =>
setTicketSession({
...ticketSession,
organizationId: organization.id,
organizationName: organization.name
})
}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-work-type">
Art
</label>
<select
id="ticket-session-work-type"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={ticketSession.workType}
onChange={(event) => setTicketSession({ ...ticketSession, workType: event.currentTarget.value as WorkType })}
>
<option value="support">Support</option>
<option value="consulting">Consulting</option>
</select>
</div>
</div>
)}
{requiresProjectTeamspaceEntry ? (
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-teamspace-entry">Teamspace-Eintrag</label>
<select
id="ticket-session-teamspace-entry"
className="h-9 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={ticketSession.projectTeamspaceEntryId}
onChange={(event) => setTicketSession({ ...ticketSession, projectTeamspaceEntryId: event.currentTarget.value })}
required
>
<option value="">Bitte wählen</option>
{projectEntries.map((entry) => (
<option key={entry.id} value={entry.id}>
{teamspaceEntryOptionLabel(entry)}
</option>
))}
</select>
</div>
) : null}
<div className="grid gap-3 lg:grid-cols-[150px_120px_120px_160px_minmax(220px,1fr)_auto] lg:items-end">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-day">
Datum
</label>
<Input
id="ticket-session-day"
type="date"
value={ticketSession.day}
onChange={(event) => setTicketSession({ ...ticketSession, day: event.currentTarget.value })}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-start">
Von
</label>
<Input
id="ticket-session-start"
type="time"
value={ticketSession.startTime}
onChange={(event) => setTicketSession({ ...ticketSession, startTime: event.currentTarget.value })}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-end">
Bis
</label>
<Input
id="ticket-session-end"
type="time"
value={ticketSession.endTime}
onChange={(event) => setTicketSession({ ...ticketSession, endTime: event.currentTarget.value })}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-billing-status">
Bewertung
</label>
<BillingCaptureSelect
id="ticket-session-billing-status"
value={ticketSession.billingStatus}
onChange={(billingStatus) => setTicketSession({ ...ticketSession, billingStatus })}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="ticket-session-activity">
Tätigkeit
</label>
<Textarea
id="ticket-session-activity"
className="min-h-20"
value={ticketSession.activity}
onChange={(event) => setTicketSession({ ...ticketSession, activity: event.currentTarget.value })}
required
/>
</div>
<Button type="submit" disabled={savingTicketSession}>
<Save className="size-4" />
{savingTicketSession ? "Speichert..." : "Nachtragen"}
</Button>
</div>
</form>
</CardContent>
</Card>
)}
{data && data.openCount > 0 ? (
<p className="text-sm text-muted-foreground">
Noch {data.openCount} Session(s) ohne Auswahl. Erst wenn im Monat keine Sessions mehr offen sind, kann der Monat abgeschlossen werden.
</p>
) : null}
<Dialog open={Boolean(teamspacePreparation)} onOpenChange={(open) => !open && setTeamspacePreparation(null)}>
<DialogContent className="max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] overflow-y-auto p-5 sm:max-w-2xl">
<DialogHeader className="pr-8">
<DialogTitle>TS Aufbereitung</DialogTitle>
<DialogDescription>{teamspacePreparation?.label ?? "Sessiontätigkeiten des Tages"}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<Textarea
className="min-h-80 resize-y font-mono text-sm"
value={teamspacePreparation?.text ?? ""}
onChange={(event) =>
setTeamspacePreparation((current) =>
current
? {
...current,
text: event.currentTarget.value
}
: current
)
}
/>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button type="button" variant="secondary" onClick={() => setTeamspacePreparation(null)}>
Schließen
</Button>
<Button type="button" disabled={!teamspacePreparation?.text.trim()} onClick={() => void copyTeamspacePreparation()}>
<Copy className="size-4" />
Kopieren
</Button>
</div>
</div>
</DialogContent>
</Dialog>
<Dialog open={Boolean(pendingProjectDelete)} onOpenChange={(open) => !open && void keepEmptyProject()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Keine Sessions mehr vorhanden</DialogTitle>
<DialogDescription>Projekt löschen?</DialogDescription>
</DialogHeader>
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button type="button" variant="secondary" disabled={deletingEmptyProject} onClick={() => void keepEmptyProject()}>
Projekt behalten
</Button>
<Button type="button" variant="destructive" disabled={deletingEmptyProject} onClick={() => void deleteEmptyProject()}>
<Trash2 className="size-4" />
{deletingEmptyProject ? "Löscht..." : "Projekt löschen"}
</Button>
</div>
</DialogContent>
</Dialog>
<Dialog open={Boolean(editingSession)} onOpenChange={(open) => !open && setEditingSession(null)}>
<DialogContent className="max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] overflow-y-auto p-5 sm:max-w-2xl">
<DialogHeader className="pr-8">
<DialogTitle>Session bearbeiten</DialogTitle>
<DialogDescription>Beginn, Ende, Tätigkeit und Stammdaten dieses Eintrags nachträglich korrigieren.</DialogDescription>
</DialogHeader>
<form className="space-y-4 overflow-x-hidden" onSubmit={saveSessionData}>
<div className="grid gap-3 sm:grid-cols-3">
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-day">Datum</label>
<Input
id="session-day"
type="date"
value={editSessionDay}
onChange={(event) => setEditSessionDay(event.currentTarget.value)}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-start-time">Von</label>
<Input
id="session-start-time"
type="time"
value={editSessionStartTime}
onChange={(event) => setEditSessionStartTime(event.currentTarget.value)}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-end-time">Bis</label>
<Input
id="session-end-time"
type="time"
value={editSessionEndTime}
onChange={(event) => setEditSessionEndTime(event.currentTarget.value)}
required
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-organization">Organisation</label>
{editingSession?.customer_name && !editingSession.organization_id ? (
<p className="text-xs text-muted-foreground">Bisheriger Freitext: {editingSession.customer_name}</p>
) : null}
<OrganizationSelect
value={editSessionOrganizationId}
selectedName={editSessionOrganizationName}
onChange={(organization) => {
setEditSessionOrganizationId(organization.id);
setEditSessionOrganizationName(organization.name);
}}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-activity">Tätigkeit</label>
<Textarea
id="session-activity"
className="min-h-24 resize-y"
value={editSessionActivity}
onChange={(event) => setEditSessionActivity(event.currentTarget.value)}
required
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-work-type">Art</label>
<select
id="session-work-type"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={editSessionWorkType}
disabled={Boolean(editingSession?.recurring_billing_id)}
onChange={(event) => setEditSessionWorkType(event.currentTarget.value as WorkType)}
>
<option value="support">Support</option>
<option value="consulting">Consulting</option>
</select>
</div>
{editSessionWorkType === "consulting" && requiresProjectTeamspaceEntry ? (
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="session-teamspace-entry">Teamspace-Eintrag</label>
<select
id="session-teamspace-entry"
className="h-8 w-full rounded-lg border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
value={editSessionProjectTeamspaceEntryId}
onChange={(event) => setEditSessionProjectTeamspaceEntryId(event.currentTarget.value)}
required
>
<option value="">Bitte wählen</option>
{projectEntries.map((entry) => (
<option key={entry.id} value={entry.id}>
{teamspaceEntryOptionLabel(entry)}
</option>
))}
</select>
</div>
) : null}
<div className="flex justify-end">
<Button type="submit" disabled={savingSessionDetails}>
<Save className="size-4" />
{savingSessionDetails ? "Speichert..." : "Session speichern"}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
);
}