feat: full CRUD support — companies, deals, projects, expenses, tickets, licenses

API routes (new + modified):
- POST /api/aos/crm/companies (create company)
- PATCH/DELETE /api/aos/crm/companies/[id] (edit/delete with dependency check)
- PATCH/DELETE /api/aos/crm/deals/[id] (edit/delete deal)
- POST /api/aos/projects (create project)
- PATCH/DELETE /api/aos/projects/[id] (edit/delete with dependency check)
- POST /api/aos/expenses (create expense)
- PATCH/DELETE /api/aos/expenses/[id] (edit/delete with GoBD lock)
- PATCH/DELETE /api/aos/tickets/[id] (edit/delete with message check)
- DELETE /api/aos/licenses/[id] (delete only if cancelled + no deps)
- NO invoice delete endpoint (GoBD retention — storno only)

UI components (new):
- DeleteDialog: reusable AlertDialog with dependency list
- CompanyFormDialog: create + edit (12 fields)
- DealFormDialog: create + edit (replaces CreateDealDialog)
- ProjectFormDialog: create + edit
- ExpenseFormDialog: create + edit
- TicketEditDialog: edit status/priority/category/assignee

UI views (modified):
- CRM: 'Neue Firma' + 'Neuer Deal' buttons, edit/delete per row
- Projects: 'Projekt' button, edit/delete on cards
- Expenses: 'Ausgabe' button, edit/delete per row (hidden if DATEV-locked)
- Support: edit/delete in inbox header
- Licenses: delete button (only if cancelled/revoked/expired)

Cascade policy:
- Every DELETE counts FK relations, returns 409 with dependency list
- Hard delete only when no dependencies exist
- GoBD: expenses locked if DATEV-exported or invoiced
- Audit log on every create/update/delete
This commit is contained in:
Z User committed 2026-10-29 13:32:17 +00:00
1 parent 27669adc21
commit aa075762b2
21 files changed
+2618 -40

No files matched your search

@@ -0,0 +1,182 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react'
// Shape shared between the table row and the edit form. Optional fields
// are stringified so the form has a single value type.
export interface CompanyFormValue {
id?: string
name: string
legalForm: string
vatId: string
registerCourt: string
registerNumber: string
website: string
email: string
phone: string
city: string
zip: string
street: string
tags: string
}
export const EMPTY_COMPANY: CompanyFormValue = {
name: '',
legalForm: '',
vatId: '',
registerCourt: '',
registerNumber: '',
website: '',
email: '',
phone: '',
city: '',
zip: '',
street: '',
tags: '',
}
interface Props {
open: boolean
onOpenChange: (o: boolean) => void
// When `company` is null, the dialog is in "create" mode.
company?: CompanyFormValue | null
onSaved: () => void
}
// Single dialog for create + edit of a CRM Company.
// - create mode → POST /api/aos/crm/companies
// - edit mode → PATCH /api/aos/crm/companies/[id]
// Both write an audit entry on the server side (GoBD).
export function CompanyFormDialog({ open, onOpenChange, company, onSaved }: Props) {
const [form, setForm] = useState<CompanyFormValue>(EMPTY_COMPANY)
const [saving, setSaving] = useState(false)
const isEdit = !!company?.id
useEffect(() => {
if (open) {
setForm(company ?? EMPTY_COMPANY)
}
}, [open, company])
const update = (k: keyof CompanyFormValue, v: string) =>
setForm((f) => ({ ...f, [k]: v }))
const submit = async () => {
if (!form.name.trim()) { toast.error('Firmenname ist Pflicht'); return }
setSaving(true)
const t = toast.loading(isEdit ? 'Firma wird gespeichert…' : 'Firma wird angelegt…')
try {
// Normalise empty strings → null on the server side (Prisma schema is
// nullable; the PATCH handler accepts strings or null).
const payload: Record<string, string | null> = {
name: form.name.trim(),
legalForm: form.legalForm.trim() || null,
vatId: form.vatId.trim() || null,
registerCourt: form.registerCourt.trim() || null,
registerNumber: form.registerNumber.trim() || null,
website: form.website.trim() || null,
email: form.email.trim() || null,
phone: form.phone.trim() || null,
city: form.city.trim() || null,
zip: form.zip.trim() || null,
street: form.street.trim() || null,
tags: form.tags.trim() || null,
}
const url = isEdit ? `/api/aos/crm/companies/${company!.id}` : '/api/aos/crm/companies'
const method = isEdit ? 'PATCH' : 'POST'
const r = await fetch(url, {
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
})
if (!r.ok) {
const err = await r.json().catch(() => ({}))
throw new Error(err.error || `${method} failed`)
}
toast.success(isEdit ? 'Firma aktualisiert' : 'Firma angelegt', { id: t })
onOpenChange(false)
onSaved()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Speichern fehlgeschlagen', { id: t })
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{isEdit ? 'Firma bearbeiten' : 'Neue Firma'}</DialogTitle>
<DialogDescription>
{isEdit
? 'Stammdaten aktualisieren. Änderungen werden im Audit-Log protokolliert (GoBD).'
: 'Erfasse eine neue Firma im CRM. Audit-Log wird automatisch geschrieben.'}
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-2 gap-3">
<Field label="Firmenname *" value={form.name} onChange={(v) => update('name', v)} className="col-span-2" />
<Field label="Rechtsform" value={form.legalForm} onChange={(v) => update('legalForm', v)} placeholder="GmbH, UG, e.K." />
<Field label="USt-IdNr." value={form.vatId} onChange={(v) => update('vatId', v)} placeholder="DE123456789" mono />
<Field label="Registergericht" value={form.registerCourt} onChange={(v) => update('registerCourt', v)} placeholder="Amtsgericht Hamburg" />
<Field label="HRB-Nummer" value={form.registerNumber} onChange={(v) => update('registerNumber', v)} mono />
<Field label="Website" value={form.website} onChange={(v) => update('website', v)} placeholder="mueller.de" />
<Field label="E-Mail" value={form.email} onChange={(v) => update('email', v)} placeholder="info@firma.de" />
<Field label="Telefon" value={form.phone} onChange={(v) => update('phone', v)} placeholder="+49 40 …" />
<Field label="Straße" value={form.street} onChange={(v) => update('street', v)} />
<Field label="PLZ" value={form.zip} onChange={(v) => update('zip', v)} />
<Field label="Ort" value={form.city} onChange={(v) => update('city', v)} className="col-span-2" />
<Field label="Tags (kommasepariert)" value={form.tags} onChange={(v) => update('tags', v)} placeholder="kunde, agency, vip" className="col-span-2" />
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Abbrechen</Button>
<Button onClick={submit} disabled={saving} className="gap-1.5">
{saving && <Loader2 className="size-3.5 animate-spin" />}
{isEdit ? 'Speichern' : 'Anlegen'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
function Field({
label,
value,
onChange,
placeholder,
mono,
className,
}: {
label: string
value: string
onChange: (v: string) => void
placeholder?: string
mono?: boolean
className?: string
}) {
return (
<div className={`space-y-1.5 ${className ?? ''}`}>
<Label className="text-xs">{label}</Label>
<Input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
className={`h-9 text-xs ${mono ? 'font-mono' : ''}`}
/>
</div>
)
}
@@ -0,0 +1,197 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react'
export interface DealFormValue {
id?: string
companyId: string
title: string
valueEuro: string
stage: string
probability: string
expectedClose: string
lossReason: string
}
interface Props {
open: boolean
onOpenChange: (o: boolean) => void
companies: { id: string; name: string }[]
// When `deal` is null the dialog is in "create" mode.
deal?: DealFormValue | null
onSaved: () => void
}
const STAGES = [
{ value: 'lead', label: 'Lead' },
{ value: 'qualified', label: 'Qualifiziert' },
{ value: 'proposal', label: 'Angebot' },
{ value: 'negotiation', label: 'Verhandlung' },
{ value: 'won', label: 'Gewonnen' },
{ value: 'lost', label: 'Verloren' },
]
const EMPTY: DealFormValue = {
companyId: '',
title: '',
valueEuro: '',
stage: 'lead',
probability: '10',
expectedClose: '',
lossReason: '',
}
// Single dialog for create + edit of a CRM Deal.
// - create mode → POST /api/aos/crm/deals
// - edit mode → PATCH /api/aos/crm/deals/[id]
export function DealFormDialog({ open, onOpenChange, companies, deal, onSaved }: Props) {
const [form, setForm] = useState<DealFormValue>(EMPTY)
const [saving, setSaving] = useState(false)
const isEdit = !!deal?.id
useEffect(() => {
if (open) {
setForm(deal ?? EMPTY)
}
}, [open, deal])
// Auto-pick the first company for create mode if none selected.
useEffect(() => {
if (open && !isEdit && !form.companyId && companies[0]) {
setForm((f) => ({ ...f, companyId: companies[0].id }))
}
}, [open, isEdit, form.companyId, companies])
const submit = async () => {
if (!form.companyId) { toast.error('Firma auswählen'); return }
if (!form.title.trim()) { toast.error('Titel eingeben'); return }
const valueCents = Math.round((parseFloat(form.valueEuro.replace(',', '.')) || 0) * 100)
const probability = Math.min(100, Math.max(0, parseInt(form.probability, 10) || 0))
const payload: Record<string, unknown> = {
companyId: form.companyId,
title: form.title.trim(),
valueCents,
stage: form.stage,
probability,
expectedClose: form.expectedClose || null,
}
if (form.stage === 'lost' && form.lossReason.trim()) {
payload.lossReason = form.lossReason.trim()
}
setSaving(true)
const t = toast.loading(isEdit ? 'Deal wird gespeichert…' : 'Deal wird angelegt…')
try {
const url = isEdit ? `/api/aos/crm/deals/${deal!.id}` : '/api/aos/crm/deals'
const method = isEdit ? 'PATCH' : 'POST'
const r = await fetch(url, {
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
})
if (!r.ok) {
const err = await r.json().catch(() => ({}))
throw new Error(err.error || `${method} failed`)
}
toast.success(isEdit ? 'Deal aktualisiert' : 'Deal angelegt', { id: t })
onOpenChange(false)
onSaved()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Speichern fehlgeschlagen', { id: t })
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{isEdit ? 'Deal bearbeiten' : 'Neuer Deal'}</DialogTitle>
<DialogDescription>
{isEdit
? 'Deal-Daten aktualisieren. Änderungen werden im Audit-Log protokolliert (GoBD).'
: 'Legt einen Deal in der Pipeline an. Audit-Log wird automatisch geschrieben.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1.5">
<Label className="text-xs">Firma</Label>
<Select value={form.companyId} onValueChange={(v) => setForm((f) => ({ ...f, companyId: v }))}>
<SelectTrigger className="w-full"><SelectValue placeholder="Firma wählen" /></SelectTrigger>
<SelectContent>
{companies.map((c) => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Titel</Label>
<Input value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} placeholder="z.B. Website-Relaunch" />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Wert (€)</Label>
<Input value={form.valueEuro} onChange={(e) => setForm((f) => ({ ...f, valueEuro: e.target.value }))} placeholder="9.800" inputMode="decimal" />
</div>
<div className="space-y-1.5">
<Label className="text-xs">Wahrscheinlichkeit (%)</Label>
<Input value={form.probability} onChange={(e) => setForm((f) => ({ ...f, probability: e.target.value }))} placeholder="50" inputMode="numeric" />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Phase</Label>
<Select value={form.stage} onValueChange={(v) => setForm((f) => ({ ...f, stage: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{STAGES.map((s) => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Erwarteter Abschluss</Label>
<Input
type="date"
value={form.expectedClose ? form.expectedClose.slice(0, 10) : ''}
onChange={(e) => setForm((f) => ({ ...f, expectedClose: e.target.value }))}
/>
</div>
</div>
{form.stage === 'lost' && (
<div className="space-y-1.5">
<Label className="text-xs">Verlustgrund</Label>
<Input value={form.lossReason} onChange={(e) => setForm((f) => ({ ...f, lossReason: e.target.value }))} placeholder="z.B. Preis, Konkurrenz, Timing" />
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Abbrechen</Button>
<Button onClick={submit} disabled={saving} className="gap-1.5">
{saving && <Loader2 className="size-3.5 animate-spin" />}
{isEdit ? 'Speichern' : 'Anlegen'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+169
View File
@@ -0,0 +1,169 @@
'use client'
import { useState } from 'react'
import { Loader2, Trash2, AlertTriangle } from 'lucide-react'
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Badge } from '@/components/ui/badge'
import { toast } from 'sonner'
interface DeleteDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
// Human label for the entity, e.g. "Firma", "Deal".
entityLabel: string
// Display name shown in the body, e.g. "Müller GmbH".
entityName: string
// DELETE endpoint URL.
endpoint: string
// Called after a successful delete (usually refetch).
onDeleted?: () => void
// Optional description override. Default explains that this is irreversible.
description?: string
}
// Reusable confirmation dialog for delete actions.
//
// Talks to the standardised DELETE endpoints in /api/aos/.../[id]/route.ts.
// Those endpoints return 409 with a `dependencies` object when the entity
// still has related records that block deletion — we render that list
// inside the dialog so the user knows exactly what to clean up first.
//
// GoBD: callers must NOT use this for invoices (no DELETE endpoint exists).
export function DeleteDialog({
open,
onOpenChange,
entityLabel,
entityName,
endpoint,
onDeleted,
description,
}: DeleteDialogProps) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [dependencies, setDependencies] = useState<Record<string, number> | null>(null)
const reset = () => {
setError(null)
setDependencies(null)
}
const confirm = async () => {
setBusy(true)
setError(null)
setDependencies(null)
const t = toast.loading(`${entityLabel} wird gelöscht…`)
try {
const r = await fetch(endpoint, { method: 'DELETE' })
const data = await r.json().catch(() => ({}))
if (!r.ok) {
// Surface dependency info if the API gave us any.
if (data.dependencies) setDependencies(data.dependencies as Record<string, number>)
throw new Error(data.error || `HTTP ${r.status}`)
}
toast.success(`${entityLabel} gelöscht`, { id: t })
onOpenChange(false)
reset()
onDeleted?.()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Löschen fehlgeschlagen', { id: t })
setError(err instanceof Error ? err.message : 'Löschen fehlgeschlagen')
} finally {
setBusy(false)
}
}
const depEntries = dependencies ? Object.entries(dependencies).filter(([, n]) => n > 0) : []
return (
<AlertDialog
open={open}
onOpenChange={(o) => {
if (!o) reset()
onOpenChange(o)
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<Trash2 className="size-4 text-muted-foreground" />
{entityLabel} löschen
</AlertDialogTitle>
<AlertDialogDescription>
{description ?? `Möchtest du „${entityName}" wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.`}
</AlertDialogDescription>
</AlertDialogHeader>
{error && (
<div className="rounded-md border border-foreground/30 bg-foreground/5 p-3 text-xs">
<div className="flex items-start gap-2">
<AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-foreground" />
<div className="space-y-1.5">
<p className="font-medium">Löschen nicht möglich</p>
<p className="text-muted-foreground">{error}</p>
{depEntries.length > 0 && (
<div className="space-y-1.5">
<p className="text-[10px] uppercase tracking-wide text-muted-foreground">Abhängigkeiten:</p>
<div className="flex flex-wrap gap-1.5">
{depEntries.map(([k, n]) => (
<Badge key={k} variant="outline" className="text-[10px]">
{DEP_LABELS[k] ?? k}: {n}
</Badge>
))}
</div>
<p className="text-[11px] text-muted-foreground">
Lösche oder ordne diese Datensätze zuerst zu, bevor du die {entityLabel.toLowerCase()} löschst.
</p>
</div>
)}
</div>
</div>
</div>
)}
<AlertDialogFooter>
<AlertDialogCancel disabled={busy}>Abbrechen</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault()
void confirm()
}}
disabled={busy}
className="gap-1.5 bg-foreground text-background hover:bg-foreground/90"
>
{busy ? <Loader2 className="size-3.5 animate-spin" /> : <Trash2 className="size-3.5" />}
Löschen
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
// German labels for the dependency keys returned by the DELETE endpoints.
const DEP_LABELS: Record<string, string> = {
invoices: 'Rechnungen',
licenses: 'Lizenzen',
deals: 'Deals',
projects: 'Projekte',
contracts: 'Verträge',
expenses: 'Ausgaben',
tickets: 'Tickets',
instances: 'Instanzen',
leads: 'Leads',
persons: 'Ansprechpartner',
agencyClients: 'Agentur-Kunden',
tasks: 'Aufgaben',
timeEntries: 'Zeiteinträge',
approvals: 'Freigaben',
activations: 'Aktivierungen',
modules: 'Module',
}
@@ -0,0 +1,273 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react'
export interface ExpenseFormValue {
id?: string
categoryId: string
vendor: string
description: string
amountEuro: string
taxBp: string
date: string
companyId: string
projectId: string
billable: boolean
markupPct: string
recurring: boolean
recurringInterval: string
}
interface Props {
open: boolean
onOpenChange: (o: boolean) => void
companies: { id: string; name: string }[]
projects: { id: string; name: string }[]
// When `expense` is null the dialog is in "create" mode.
expense?: ExpenseFormValue | null
onSaved: () => void
}
const CATEGORIES = [
{ value: 'reise', label: 'Reise' },
{ value: 'software', label: 'Software' },
{ value: 'hardware', label: 'Hardware' },
{ value: 'fremdleistung', label: 'Fremdleistung' },
{ value: 'buero', label: 'Büro' },
{ value: 'marketing', label: 'Marketing' },
]
const TAX_RATES = [
{ value: '0', label: '0% (steuerfrei)' },
{ value: '700', label: '7% (ermäßigt)' },
{ value: '1900', label: '19% (Regelsatz)' },
]
const RECURRING_INTERVALS = [
{ value: 'monthly', label: 'Monatlich' },
{ value: 'quarterly', label: 'Quartalsweise' },
{ value: 'yearly', label: 'Jährlich' },
]
const EMPTY: ExpenseFormValue = {
categoryId: 'software',
vendor: '',
description: '',
amountEuro: '',
taxBp: '1900',
date: '',
companyId: '',
projectId: '',
billable: false,
markupPct: '0',
recurring: false,
recurringInterval: 'monthly',
}
// Single dialog for create + edit of an Expense.
// - create mode → POST /api/aos/expenses
// - edit mode → PATCH /api/aos/expenses/[id]
//
// Server computes grossCents = amountCents * (1 + taxBp/10000); the UI does
// not need to send grossCents. On edit, if amount or tax changes the server
// recomputes; otherwise the existing grossCents is preserved.
export function ExpenseFormDialog({ open, onOpenChange, companies, projects, expense, onSaved }: Props) {
const [form, setForm] = useState<ExpenseFormValue>(EMPTY)
const [saving, setSaving] = useState(false)
const isEdit = !!expense?.id
useEffect(() => {
if (open) {
setForm(expense ?? EMPTY)
}
}, [open, expense])
const submit = async () => {
if (!form.description.trim()) { toast.error('Beschreibung eingeben'); return }
if (!form.amountEuro.trim()) { toast.error('Betrag eingeben'); return }
const amountCents = Math.round((parseFloat(form.amountEuro.replace(',', '.')) || 0) * 100)
if (amountCents <= 0) { toast.error('Betrag muss größer als 0 sein'); return }
const payload: Record<string, unknown> = {
categoryId: form.categoryId,
vendor: form.vendor.trim() || null,
description: form.description.trim(),
amountCents,
taxBp: parseInt(form.taxBp, 10) || 1900,
date: form.date || undefined,
companyId: form.companyId || null,
projectId: form.projectId || null,
billable: form.billable,
markupPct: parseInt(form.markupPct, 10) || 0,
recurring: form.recurring,
recurringInterval: form.recurring ? form.recurringInterval : null,
}
setSaving(true)
const t = toast.loading(isEdit ? 'Ausgabe wird gespeichert…' : 'Ausgabe wird erfasst…')
try {
const url = isEdit ? `/api/aos/expenses/${expense!.id}` : '/api/aos/expenses'
const method = isEdit ? 'PATCH' : 'POST'
const r = await fetch(url, {
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
})
if (!r.ok) {
const err = await r.json().catch(() => ({}))
throw new Error(err.error || `${method} failed`)
}
toast.success(isEdit ? 'Ausgabe aktualisiert' : 'Ausgabe erfasst', { id: t })
onOpenChange(false)
onSaved()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Speichern fehlgeschlagen', { id: t })
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{isEdit ? 'Ausgabe bearbeiten' : 'Neue Ausgabe'}</DialogTitle>
<DialogDescription>
{isEdit
? 'Ausgaben-Daten aktualisieren. Bei Betrags- oder Steueränderung wird der Bruttobetrag neu berechnet. Audit-Log wird automatisch geschrieben (GoBD).'
: 'Erfasse eine neue Ausgabe. Der Bruttobetrag wird aus Nettobetrag und Steuersatz berechnet. Audit-Log wird automatisch geschrieben.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Kategorie</Label>
<Select value={form.categoryId} onValueChange={(v) => setForm((f) => ({ ...f, categoryId: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{CATEGORIES.map((c) => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Lieferant</Label>
<Input value={form.vendor} onChange={(e) => setForm((f) => ({ ...f, vendor: e.target.value }))} placeholder="z.B. Amazon, O2, …" />
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Beschreibung *</Label>
<Textarea value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} placeholder="z.B. Adobe Creative Cloud — Jahresabo" className="min-h-[60px] text-xs" />
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Netto (€) *</Label>
<Input value={form.amountEuro} onChange={(e) => setForm((f) => ({ ...f, amountEuro: e.target.value }))} placeholder="59,40" inputMode="decimal" />
</div>
<div className="space-y-1.5">
<Label className="text-xs">Steuer</Label>
<Select value={form.taxBp} onValueChange={(v) => setForm((f) => ({ ...f, taxBp: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{TAX_RATES.map((r) => <SelectItem key={r.value} value={r.value}>{r.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Datum</Label>
<Input type="date" value={form.date} onChange={(e) => setForm((f) => ({ ...f, date: e.target.value }))} />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Kunde (belastbar)</Label>
<Select value={form.companyId || 'none'} onValueChange={(v) => setForm((f) => ({ ...f, companyId: v === 'none' ? '' : v }))}>
<SelectTrigger className="w-full"><SelectValue placeholder="— Eigenbeleg —" /></SelectTrigger>
<SelectContent>
<SelectItem value="none">— Eigenbeleg —</SelectItem>
{companies.map((c) => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Projekt</Label>
<Select value={form.projectId || 'none'} onValueChange={(v) => setForm((f) => ({ ...f, projectId: v === 'none' ? '' : v }))}>
<SelectTrigger className="w-full"><SelectValue placeholder="—" /></SelectTrigger>
<SelectContent>
<SelectItem value="none">—</SelectItem>
{projects.map((p) => <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Markup %</Label>
<Input value={form.markupPct} onChange={(e) => setForm((f) => ({ ...f, markupPct: e.target.value }))} placeholder="0" inputMode="numeric" />
</div>
<div className="space-y-1.5">
<Label className="text-xs">Wiederkehrend?</Label>
<Select
value={form.recurring ? 'yes' : 'no'}
onValueChange={(v) => setForm((f) => ({ ...f, recurring: v === 'yes' }))}
>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="no">Nein</SelectItem>
<SelectItem value="yes">Ja</SelectItem>
</SelectContent>
</Select>
</div>
{form.recurring && (
<div className="space-y-1.5">
<Label className="text-xs">Intervall</Label>
<Select value={form.recurringInterval} onValueChange={(v) => setForm((f) => ({ ...f, recurringInterval: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{RECURRING_INTERVALS.map((r) => <SelectItem key={r.value} value={r.value}>{r.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
)}
</div>
<label className="flex items-center gap-2 text-xs">
<input
type="checkbox"
checked={form.billable}
onChange={(e) => setForm((f) => ({ ...f, billable: e.target.checked }))}
className="size-3.5"
/>
<span>Belastbar (an Kunde weiterberechnen)</span>
</label>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Abbrechen</Button>
<Button onClick={submit} disabled={saving} className="gap-1.5">
{saving && <Loader2 className="size-3.5 animate-spin" />}
{isEdit ? 'Speichern' : 'Erfassen'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,208 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react'
export interface ProjectFormValue {
id?: string
companyId: string
name: string
type: string
budgetType: string
budgetHours: string
fixedPriceEuro: string
startDate: string
dueDate: string
}
interface Props {
open: boolean
onOpenChange: (o: boolean) => void
companies: { id: string; name: string }[]
// When `project` is null the dialog is in "create" mode.
project?: ProjectFormValue | null
onSaved: () => void
}
const TYPES = [
{ value: 'website', label: 'Website' },
{ value: 'shop', label: 'Shop' },
{ value: 'app', label: 'App' },
{ value: 'retainer', label: 'Retainer' },
]
const BUDGET_TYPES = [
{ value: 'fixed', label: 'Fixpreis' },
{ value: 'time-materials', label: 'Time & Materials' },
{ value: 'retainer', label: 'Retainer' },
]
const EMPTY: ProjectFormValue = {
companyId: '',
name: '',
type: 'website',
budgetType: 'fixed',
budgetHours: '',
fixedPriceEuro: '',
startDate: '',
dueDate: '',
}
// Single dialog for create + edit of a Project.
// - create mode → POST /api/aos/projects
// - edit mode → PATCH /api/aos/projects/[id]
export function ProjectFormDialog({ open, onOpenChange, companies, project, onSaved }: Props) {
const [form, setForm] = useState<ProjectFormValue>(EMPTY)
const [saving, setSaving] = useState(false)
const isEdit = !!project?.id
useEffect(() => {
if (open) {
setForm(project ?? EMPTY)
}
}, [open, project])
useEffect(() => {
if (open && !isEdit && !form.companyId && companies[0]) {
setForm((f) => ({ ...f, companyId: companies[0].id }))
}
}, [open, isEdit, form.companyId, companies])
const submit = async () => {
if (!form.companyId) { toast.error('Firma auswählen'); return }
if (!form.name.trim()) { toast.error('Projektname eingeben'); return }
const fixedPriceCents = form.fixedPriceEuro
? Math.round((parseFloat(form.fixedPriceEuro.replace(',', '.')) || 0) * 100)
: null
const budgetHours = form.budgetHours ? parseInt(form.budgetHours, 10) || null : null
const payload: Record<string, unknown> = {
companyId: form.companyId,
name: form.name.trim(),
type: form.type,
budgetType: form.budgetType,
budgetHours,
fixedPriceCents,
startDate: form.startDate || null,
dueDate: form.dueDate || null,
}
setSaving(true)
const t = toast.loading(isEdit ? 'Projekt wird gespeichert…' : 'Projekt wird angelegt…')
try {
const url = isEdit ? `/api/aos/projects/${project!.id}` : '/api/aos/projects'
const method = isEdit ? 'PATCH' : 'POST'
const r = await fetch(url, {
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
})
if (!r.ok) {
const err = await r.json().catch(() => ({}))
throw new Error(err.error || `${method} failed`)
}
toast.success(isEdit ? 'Projekt aktualisiert' : 'Projekt angelegt', { id: t })
onOpenChange(false)
onSaved()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Speichern fehlgeschlagen', { id: t })
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{isEdit ? 'Projekt bearbeiten' : 'Neues Projekt'}</DialogTitle>
<DialogDescription>
{isEdit
? 'Projekt-Stammdaten aktualisieren. Audit-Log wird automatisch geschrieben (GoBD).'
: 'Legt ein neues Projekt an. Audit-Log wird automatisch geschrieben.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1.5">
<Label className="text-xs">Firma</Label>
<Select value={form.companyId} onValueChange={(v) => setForm((f) => ({ ...f, companyId: v }))}>
<SelectTrigger className="w-full"><SelectValue placeholder="Firma wählen" /></SelectTrigger>
<SelectContent>
{companies.map((c) => <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Projektname</Label>
<Input value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="z.B. Website-Relaunch" />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Typ</Label>
<Select value={form.type} onValueChange={(v) => setForm((f) => ({ ...f, type: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{TYPES.map((s) => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Budget-Typ</Label>
<Select value={form.budgetType} onValueChange={(v) => setForm((f) => ({ ...f, budgetType: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{BUDGET_TYPES.map((s) => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Fixpreis (€)</Label>
<Input value={form.fixedPriceEuro} onChange={(e) => setForm((f) => ({ ...f, fixedPriceEuro: e.target.value }))} placeholder="9.800" inputMode="decimal" />
</div>
<div className="space-y-1.5">
<Label className="text-xs">Budget-Stunden</Label>
<Input value={form.budgetHours} onChange={(e) => setForm((f) => ({ ...f, budgetHours: e.target.value }))} placeholder="120" inputMode="numeric" />
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Startdatum</Label>
<Input type="date" value={form.startDate} onChange={(e) => setForm((f) => ({ ...f, startDate: e.target.value }))} />
</div>
<div className="space-y-1.5">
<Label className="text-xs">Fälligkeit</Label>
<Input type="date" value={form.dueDate} onChange={(e) => setForm((f) => ({ ...f, dueDate: e.target.value }))} />
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Abbrechen</Button>
<Button onClick={submit} disabled={saving} className="gap-1.5">
{saving && <Loader2 className="size-3.5 animate-spin" />}
{isEdit ? 'Speichern' : 'Anlegen'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,182 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { toast } from 'sonner'
import { Loader2 } from 'lucide-react'
export interface TicketFormValue {
id?: string
subject: string
status: string
priority: string
categoryId: string
assignee: string
}
interface Props {
open: boolean
onOpenChange: (o: boolean) => void
ticket?: TicketFormValue | null
onSaved: () => void
}
const STATUSES = [
{ value: 'open', label: 'Offen' },
{ value: 'pending', label: 'Wartend' },
{ value: 'resolved', label: 'Gelöst' },
{ value: 'closed', label: 'Geschlossen' },
]
const PRIORITIES = [
{ value: 'low', label: 'Niedrig' },
{ value: 'normal', label: 'Normal' },
{ value: 'high', label: 'Hoch' },
{ value: 'urgent', label: 'Dringend' },
]
const CATEGORIES = [
{ value: 'bug', label: 'Bug' },
{ value: 'anfrage', label: 'Anfrage' },
{ value: 'aenderung', label: 'Änderung' },
{ value: 'konto', label: 'Konto' },
{ value: 'rechnung', label: 'Rechnung' },
{ value: 'hosting', label: 'Hosting' },
]
const EMPTY: TicketFormValue = {
subject: '',
status: 'open',
priority: 'normal',
categoryId: 'anfrage',
assignee: '',
}
// Edit-only dialog (creation is done via the public ticket creation flow).
// Patches via /api/aos/tickets/[id]. Audit-logged (GoBD).
//
// Side effects handled on the server:
// - status='resolved'|'closed' → slaResolvedAt set
// - first non-empty assignee → slaRespondedAt set
export function TicketEditDialog({ open, onOpenChange, ticket, onSaved }: Props) {
const [form, setForm] = useState<TicketFormValue>(EMPTY)
const [saving, setSaving] = useState(false)
useEffect(() => {
if (open) {
setForm(ticket ?? EMPTY)
}
}, [open, ticket])
const submit = async () => {
if (!form.subject.trim()) { toast.error('Betreff eingeben'); return }
if (!ticket?.id) { toast.error('Ticket-ID fehlt'); return }
const payload: Record<string, unknown> = {
subject: form.subject.trim(),
status: form.status,
priority: form.priority,
categoryId: form.categoryId,
assignee: form.assignee.trim() || null,
}
setSaving(true)
const t = toast.loading('Ticket wird aktualisiert…')
try {
const r = await fetch(`/api/aos/tickets/${ticket.id}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
})
if (!r.ok) {
const err = await r.json().catch(() => ({}))
throw new Error(err.error || 'PATCH failed')
}
toast.success('Ticket aktualisiert', { id: t })
onOpenChange(false)
onSaved()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Speichern fehlgeschlagen', { id: t })
} finally {
setSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Ticket bearbeiten</DialogTitle>
<DialogDescription>
Betreff, Status, Priorität, Kategorie und Assignee. Audit-Log wird automatisch geschrieben (GoBD).
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1.5">
<Label className="text-xs">Betreff</Label>
<Input value={form.subject} onChange={(e) => setForm((f) => ({ ...f, subject: e.target.value }))} />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Status</Label>
<Select value={form.status} onValueChange={(v) => setForm((f) => ({ ...f, status: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{STATUSES.map((s) => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Priorität</Label>
<Select value={form.priority} onValueChange={(v) => setForm((f) => ({ ...f, priority: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{PRIORITIES.map((p) => <SelectItem key={p.value} value={p.value}>{p.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<Label className="text-xs">Kategorie</Label>
<Select value={form.categoryId} onValueChange={(v) => setForm((f) => ({ ...f, categoryId: v }))}>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{CATEGORIES.map((c) => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Assignee</Label>
<Input value={form.assignee} onChange={(e) => setForm((f) => ({ ...f, assignee: e.target.value }))} placeholder="z.B. Aylin" />
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Abbrechen</Button>
<Button onClick={submit} disabled={saving} className="gap-1.5">
{saving && <Loader2 className="size-3.5 animate-spin" />}
Speichern
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+160 -15
View File
@@ -1,7 +1,7 @@
'use client'
import { useState } from 'react'
import { Plus, Building2, Mail, Phone, Globe, MapPin, Users as UsersIcon, Upload, Loader2, Check, FileText } from 'lucide-react'
import { Plus, Building2, Mail, Phone, Globe, MapPin, Users as UsersIcon, Upload, Loader2, Check, FileText, Pencil, Trash2 } from 'lucide-react'
import { useFetch } from '@/hooks/use-fetch'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
@@ -9,7 +9,9 @@ import { Button } from '@/components/ui/button'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton'
import { PageHeader } from '../primitives'
import { CreateDealDialog } from '../create-deal-dialog'
import { DealFormDialog, type DealFormValue } from '../crud/deal-form-dialog'
import { CompanyFormDialog, type CompanyFormValue } from '../crud/company-form-dialog'
import { DeleteDialog } from '../crud/delete-dialog'
import {
Dialog,
DialogContent,
@@ -45,7 +47,12 @@ const STAGE_COLORS: Record<string, string> = {
export function CrmView() {
const { data, loading, refetch } = useFetch<CrmData>('/api/aos/crm')
const setSelectedCompany = useAos((s) => s.setSelectedCompany)
const [createOpen, setCreateOpen] = useState(false)
const [dealDialogOpen, setDealDialogOpen] = useState(false)
const [editingDeal, setEditingDeal] = useState<DealFormValue | null>(null)
const [companyDialogOpen, setCompanyDialogOpen] = useState(false)
const [editingCompany, setEditingCompany] = useState<CompanyFormValue | null>(null)
const [deleteCompany, setDeleteCompany] = useState<Company & { persons: Person[]; deals: Deal[] } | null>(null)
const [deleteDeal, setDeleteDeal] = useState<Deal & { company: Company } | null>(null)
const [importOpen, setImportOpen] = useState(false)
const [importStep, setImportStep] = useState<'upload' | 'map' | 'result'>('upload')
const [csvText, setCsvText] = useState('')
@@ -81,7 +88,11 @@ export function CrmView() {
<Upload className="size-4" />
CSV Import
</Button>
<Button size="sm" onClick={() => setCreateOpen(true)}>
<Button size="sm" variant="outline" onClick={() => { setEditingCompany(null); setCompanyDialogOpen(true) }}>
<Plus className="size-4" />
Firma
</Button>
<Button size="sm" onClick={() => { setEditingDeal(null); setDealDialogOpen(true) }}>
<Plus className="size-4" />
Deal
</Button>
@@ -116,11 +127,20 @@ export function CrmView() {
</TabsList>
<TabsContent value="pipeline" className="mt-4">
<PipelineBoard pipeline={data.pipeline} />
<PipelineBoard
pipeline={data.pipeline}
onEditDeal={(d) => { setEditingDeal(dealToForm(d)); setDealDialogOpen(true) }}
onDeleteDeal={(d) => setDeleteDeal(d)}
/>
</TabsContent>
<TabsContent value="companies" className="mt-4">
<CompaniesTable companies={data.companies} onSelectCompany={setSelectedCompany} />
<CompaniesTable
companies={data.companies}
onSelectCompany={setSelectedCompany}
onEdit={(c) => { setEditingCompany(companyToForm(c)); setCompanyDialogOpen(true) }}
onDelete={(c) => setDeleteCompany(c)}
/>
</TabsContent>
<TabsContent value="persons" className="mt-4">
@@ -128,13 +148,43 @@ export function CrmView() {
</TabsContent>
</Tabs>
<CreateDealDialog
open={createOpen}
onOpenChange={setCreateOpen}
<DealFormDialog
open={dealDialogOpen}
onOpenChange={setDealDialogOpen}
companies={data.companies.map((c) => ({ id: c.id, name: c.name }))}
onCreated={refetch}
deal={editingDeal}
onSaved={refetch}
/>
<CompanyFormDialog
open={companyDialogOpen}
onOpenChange={setCompanyDialogOpen}
company={editingCompany}
onSaved={refetch}
/>
{deleteCompany && (
<DeleteDialog
open={!!deleteCompany}
onOpenChange={(o) => !o && setDeleteCompany(null)}
entityLabel="Firma"
entityName={deleteCompany.name}
endpoint={`/api/aos/crm/companies/${deleteCompany.id}`}
onDeleted={refetch}
/>
)}
{deleteDeal && (
<DeleteDialog
open={!!deleteDeal}
onOpenChange={(o) => !o && setDeleteDeal(null)}
entityLabel="Deal"
entityName={deleteDeal.title}
endpoint={`/api/aos/crm/deals/${deleteDeal.id}`}
onDeleted={refetch}
/>
)}
{/* CSV Import Dialog */}
<Dialog open={importOpen} onOpenChange={(o) => { setImportOpen(o); if (!o) { setCsvText(''); setCsvHeaders([]); setMapping({ name: -1 }); setImportResult(null) } }}>
<DialogContent className="sm:max-w-2xl">
@@ -295,7 +345,15 @@ export function CrmView() {
)
}
function PipelineBoard({ pipeline }: { pipeline: CrmData['pipeline'] }) {
function PipelineBoard({
pipeline,
onEditDeal,
onDeleteDeal,
}: {
pipeline: CrmData['pipeline']
onEditDeal: (d: Deal & { company: Company }) => void
onDeleteDeal: (d: Deal & { company: Company }) => void
}) {
return (
<div className="flex gap-3 overflow-x-auto pb-4 [scrollbar-width:thin]">
{pipeline.map((col) => {
@@ -316,8 +374,28 @@ function PipelineBoard({ pipeline }: { pipeline: CrmData['pipeline'] }) {
)}
<div className="flex-1 space-y-2 overflow-y-auto p-2 [scrollbar-width:thin]" style={{ maxHeight: '60vh' }}>
{col.deals.map((d) => (
<Card key={d.id} className="cursor-pointer p-3 transition hover:border-foreground/30 hover:shadow-sm">
<p className="text-xs font-medium leading-snug">{d.title}</p>
<Card key={d.id} className="group p-3 transition hover:border-foreground/30 hover:shadow-sm">
<div className="flex items-start justify-between gap-1.5">
<p className="min-w-0 flex-1 text-xs font-medium leading-snug">{d.title}</p>
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition group-hover:opacity-100">
<button
type="button"
onClick={(e) => { e.stopPropagation(); onEditDeal(d) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Bearbeiten"
>
<Pencil className="size-3" />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); onDeleteDeal(d) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Löschen"
>
<Trash2 className="size-3" />
</button>
</div>
</div>
<p className="mt-1 truncate text-[11px] text-muted-foreground">{d.company.name}</p>
<div className="mt-2 flex items-center justify-between">
<span className="text-xs font-semibold tabular-nums">{formatEuro(d.valueCents)}</span>
@@ -348,7 +426,17 @@ function PipelineBoard({ pipeline }: { pipeline: CrmData['pipeline'] }) {
)
}
function CompaniesTable({ companies, onSelectCompany }: { companies: CrmData['companies']; onSelectCompany: (id: string) => void }) {
function CompaniesTable({
companies,
onSelectCompany,
onEdit,
onDelete,
}: {
companies: CrmData['companies']
onSelectCompany: (id: string) => void
onEdit: (c: Company & { persons: Person[]; deals: Deal[] }) => void
onDelete: (c: Company & { persons: Person[]; deals: Deal[] }) => void
}) {
const [q, setQ] = useState('')
const filtered = companies.filter(
(c) => c.name.toLowerCase().includes(q.toLowerCase()) || (c.city ?? '').toLowerCase().includes(q.toLowerCase())
@@ -376,11 +464,12 @@ function CompaniesTable({ companies, onSelectCompany }: { companies: CrmData['co
<th className="px-4 py-2 font-medium">Kontakte</th>
<th className="px-4 py-2 font-medium">Deals</th>
<th className="px-4 py-2 font-medium">Tags</th>
<th className="w-20 px-4 py-2 font-medium text-right">Aktionen</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{filtered.map((c) => (
<tr key={c.id} className="cursor-pointer transition hover:bg-muted/40" onClick={() => onSelectCompany(c.id)}>
<tr key={c.id} className="group cursor-pointer transition hover:bg-muted/40" onClick={() => onSelectCompany(c.id)}>
<td className="px-4 py-2.5">
<div className="flex items-center gap-2">
<Building2 className="size-3.5 text-muted-foreground" />
@@ -418,6 +507,26 @@ function CompaniesTable({ companies, onSelectCompany }: { companies: CrmData['co
))}
</div>
</td>
<td className="px-4 py-2.5">
<div className="flex items-center justify-end gap-0.5 opacity-0 transition group-hover:opacity-100">
<button
type="button"
onClick={(e) => { e.stopPropagation(); onEdit(c) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Bearbeiten"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); onDelete(c) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Löschen"
>
<Trash2 className="size-3.5" />
</button>
</div>
</td>
</tr>
))}
</tbody>
@@ -488,3 +597,39 @@ function parseCSVLine(line: string): string[] {
fields.push(current)
return fields
}
// Convert a Deal (CRM view shape) into the form's value shape.
function dealToForm(d: Deal & { company: Company }): DealFormValue {
const dateStr = d.expectedClose
? (typeof d.expectedClose === 'string' ? d.expectedClose : d.expectedClose.toISOString()).slice(0, 10)
: ''
return {
id: d.id,
companyId: d.company.id,
title: d.title,
valueEuro: (d.valueCents / 100).toString().replace('.', ','),
stage: d.stage,
probability: String(d.probability),
expectedClose: dateStr,
lossReason: d.lossReason ?? '',
}
}
// Convert a Company (CRM view shape) into the form's value shape.
function companyToForm(c: Company): CompanyFormValue {
return {
id: c.id,
name: c.name,
legalForm: c.legalForm ?? '',
vatId: c.vatId ?? '',
registerCourt: '',
registerNumber: '',
website: c.website ?? '',
email: c.email ?? '',
phone: c.phone ?? '',
city: c.city ?? '',
zip: c.zip ?? '',
street: c.street ?? '',
tags: c.tags ?? '',
}
}
+96 -20
View File
@@ -10,6 +10,8 @@ import {
Loader2,
Receipt,
TrendingUp,
Pencil,
Trash2,
} from 'lucide-react'
import { useFetch } from '@/hooks/use-fetch'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -22,6 +24,8 @@ import { formatEuro, formatEuroCompact, formatDate, daysUntil } from '@/lib/form
import { cn } from '@/lib/utils'
import { toast } from 'sonner'
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis, YAxis, Cell } from 'recharts'
import { ExpenseFormDialog, type ExpenseFormValue } from '../crud/expense-form-dialog'
import { DeleteDialog } from '../crud/delete-dialog'
interface Expense {
id: string
@@ -33,6 +37,8 @@ interface Expense {
taxBp: number
grossCents: number
date: string
companyId: string | null
projectId: string | null
billable: boolean
markupPct: number
recurring: boolean
@@ -79,6 +85,15 @@ const STATUS_META: Record<string, { label: string; cls: string }> = {
export function ExpensesView() {
const { data, loading, refetch } = useFetch<ExpensesData>('/api/aos/expenses')
const [converting, setConverting] = useState<string | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [editTarget, setEditTarget] = useState<ExpenseFormValue | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Expense | null>(null)
// Companies + projects needed for the create/edit dialog (project linking).
const { data: crmData } = useFetch<{ companies: { id: string; name: string }[] } | null>('/api/aos/crm')
const { data: projectsData } = useFetch<{ projects: { id: string; name: string }[] } | null>('/api/aos/projects')
const companies = crmData?.companies ?? []
const projectOptions = projectsData?.projects ?? []
if (loading || !data) {
return (
@@ -121,7 +136,7 @@ export function ExpensesView() {
title="Ausgaben"
description="Agentur-Ausgaben mit Projekt-/Kundenbezug, belastbare Posten (billable), Wiederkehrendes und Umwandlung in Rechnungen. DATEV-Export für den Steuerberater."
actions={
<Button size="sm">
<Button size="sm" onClick={() => { setEditTarget(null); setDialogOpen(true) }}>
<Plus className="size-4" />
Ausgabe
</Button>
@@ -191,8 +206,10 @@ export function ExpensesView() {
{expenses.map((e) => {
const st = STATUS_META[e.status] ?? STATUS_META.recorded
const canConvert = e.billable && e.status !== 'invoiced' && e.companyName
const canEdit = !e.datevExported && e.status !== 'invoiced'
const canDelete = !e.datevExported && e.status !== 'invoiced'
return (
<tr key={e.id} className="transition hover:bg-muted/40">
<tr key={e.id} className="group transition hover:bg-muted/40">
<td className="px-4 py-2.5"><code className="font-mono text-[11px]">{e.number}</code></td>
<td className="px-4 py-2.5">
<Badge variant="secondary" className="text-[10px]">{CATEGORY_LABELS[e.categoryId] ?? e.categoryId}</Badge>
@@ -214,24 +231,44 @@ export function ExpensesView() {
<Badge variant="outline" className={cn('text-[10px]', st.cls)}>{st.label}</Badge>
</td>
<td className="px-4 py-2.5">
{canConvert ? (
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-[11px]"
onClick={() => convert(e)}
disabled={converting === e.id}
>
{converting === e.id ? <Loader2 className="size-3 animate-spin" /> : <ArrowRight className="size-3" />}
Zur Rechnung
</Button>
) : e.status === 'invoiced' ? (
<Badge variant="outline" className="gap-1 text-[9px]">
<Receipt className="size-2.5" />Berechnet
</Badge>
) : (
<span className="text-[10px] text-muted-foreground">—</span>
)}
<div className="flex items-center gap-1">
{canConvert ? (
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-[11px]"
onClick={() => convert(e)}
disabled={converting === e.id}
>
{converting === e.id ? <Loader2 className="size-3 animate-spin" /> : <ArrowRight className="size-3" />}
Zur Rechnung
</Button>
) : e.status === 'invoiced' ? (
<Badge variant="outline" className="gap-1 text-[9px]">
<Receipt className="size-2.5" />Berechnet
</Badge>
) : null}
{canEdit && (
<button
type="button"
onClick={() => { setEditTarget(expenseToForm(e)); setDialogOpen(true) }}
className="rounded p-1 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:bg-muted hover:text-foreground"
title="Bearbeiten"
>
<Pencil className="size-3.5" />
</button>
)}
{canDelete && (
<button
type="button"
onClick={() => setDeleteTarget(e)}
className="rounded p-1 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:bg-muted hover:text-foreground"
title="Löschen"
>
<Trash2 className="size-3.5" />
</button>
)}
</div>
</td>
</tr>
)
@@ -323,6 +360,45 @@ export function ExpensesView() {
</Card>
</TabsContent>
</Tabs>
<ExpenseFormDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
companies={companies}
projects={projectOptions}
expense={editTarget}
onSaved={refetch}
/>
{deleteTarget && (
<DeleteDialog
open={!!deleteTarget}
onOpenChange={(o) => !o && setDeleteTarget(null)}
entityLabel="Ausgabe"
entityName={deleteTarget.description}
endpoint={`/api/aos/expenses/${deleteTarget.id}`}
onDeleted={refetch}
/>
)}
</div>
)
}
// Convert an Expense (view shape) into the form's value shape.
function expenseToForm(e: Expense): ExpenseFormValue {
return {
id: e.id,
categoryId: e.categoryId,
vendor: e.vendor ?? '',
description: e.description,
amountEuro: (e.amountCents / 100).toString().replace('.', ','),
taxBp: String(e.taxBp),
date: e.date ? e.date.slice(0, 10) : '',
companyId: e.companyId ?? '',
projectId: e.projectId ?? '',
billable: e.billable,
markupPct: String(e.markupPct),
recurring: e.recurring,
recurringInterval: e.recurringInterval ?? 'monthly',
}
}
+22
View File
@@ -19,6 +19,7 @@ import {
FlaskConical,
Loader2,
CircleDollarSign,
Trash2,
} from 'lucide-react'
import { useFetch } from '@/hooks/use-fetch'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -50,6 +51,7 @@ import { PageHeader } from '../primitives'
import { formatEuro, formatEuroCompact, formatDate, formatRelative, daysUntil } from '@/lib/format'
import { cn } from '@/lib/utils'
import { toast } from 'sonner'
import { DeleteDialog } from '../crud/delete-dialog'
// ---------------------------------------------------------------------------
// Types
@@ -197,6 +199,7 @@ export function LicensesView() {
const [createOpen, setCreateOpen] = useState(false)
const [suspendTarget, setSuspendTarget] = useState<License | null>(null)
const [cancelTarget, setCancelTarget] = useState<License | null>(null)
const [deleteTarget, setDeleteTarget] = useState<License | null>(null)
const [filter, setFilter] = useState<FilterKey>('all')
if (loading || !data) {
@@ -350,6 +353,7 @@ export function LicensesView() {
onSuspend={(lic) => setSuspendTarget(lic)}
onCancel={(lic) => setCancelTarget(lic)}
onPromote={handlePromote}
onDelete={(lic) => setDeleteTarget(lic)}
/>
))
)}
@@ -471,6 +475,17 @@ export function LicensesView() {
onOpenChange={(o) => !o && setCancelTarget(null)}
onDone={refetch}
/>
{deleteTarget && (
<DeleteDialog
open={!!deleteTarget}
onOpenChange={(o) => !o && setDeleteTarget(null)}
entityLabel="Lizenz"
entityName={deleteTarget.key}
endpoint={`/api/aos/licenses/${deleteTarget.id}`}
description="Gekündigte Lizenzen ohne Aktivierungen, Instanzen oder Module können gelöscht werden. Audit-Log wird geschrieben (GoBD)."
onDeleted={refetch}
/>
)}
</div>
)
}
@@ -484,11 +499,13 @@ function LicenseRow({
onSuspend,
onCancel,
onPromote,
onDelete,
}: {
license: License
onSuspend: (l: License) => void
onCancel: (l: License) => void
onPromote: (l: License) => void
onDelete: (l: License) => void
}) {
const [open, setOpen] = useState(false)
const st = LIC_STATUS[license.status] ?? LIC_STATUS.active
@@ -621,6 +638,11 @@ function LicenseRow({
<Play className="size-3" />
</Button>
)}
{cancelled && (
<Button size="sm" variant="ghost" className="h-7 px-2 text-[10px]" onClick={() => onDelete(license)} title="Löschen">
<Trash2 className="size-3" />
</Button>
)}
</div>
</td>
</tr>
+72 -3
View File
@@ -13,6 +13,8 @@ import {
Timer,
Play,
Pause,
Pencil,
Trash2,
} from 'lucide-react'
import { useFetch } from '@/hooks/use-fetch'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -31,6 +33,8 @@ import { toast } from 'sonner'
import { PageHeader } from '../primitives'
import { formatEuro, formatDate, daysUntil, formatMinutes } from '@/lib/format'
import { cn } from '@/lib/utils'
import { ProjectFormDialog, type ProjectFormValue } from '../crud/project-form-dialog'
import { DeleteDialog } from '../crud/delete-dialog'
interface Project {
id: string
@@ -81,6 +85,13 @@ const TASK_ICON = {
export function ProjectsView() {
const { data, loading, refetch } = useFetch<ProjectsData>('/api/aos/projects')
const [selectedId, setSelectedId] = useState<string | null>(null)
const [createOpen, setCreateOpen] = useState(false)
const [editTarget, setEditTarget] = useState<ProjectFormValue | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Project | null>(null)
// Fetch companies for the create/edit dialog (CRM endpoint already returns them).
const { data: crmData } = useFetch<{ companies: { id: string; name: string }[] } | null>('/api/aos/crm')
const companies = crmData?.companies ?? []
if (loading || !data) {
return (
@@ -104,7 +115,7 @@ export function ProjectsView() {
title="Projekte"
description="Projekte, Aufgaben, Zeitverfolgung, Budgets und Change Requests. Mit Client-Portal-Freigaben."
actions={
<Button size="sm">
<Button size="sm" onClick={() => { setEditTarget(null); setCreateOpen(true) }}>
<Plus className="size-4" />
Projekt
</Button>
@@ -139,7 +150,7 @@ export function ProjectsView() {
return (
<Card
key={p.id}
className={cn('cursor-pointer p-4 transition hover:border-foreground/40', selected?.id === p.id && 'border-foreground/40 ring-1 ring-foreground/20')}
className={cn('group cursor-pointer p-4 transition hover:border-foreground/40', selected?.id === p.id && 'border-foreground/40 ring-1 ring-foreground/20')}
onClick={() => setSelectedId(p.id)}
>
<div className="flex items-start justify-between gap-2">
@@ -147,7 +158,27 @@ export function ProjectsView() {
<p className="truncate text-sm font-semibold">{p.name}</p>
<p className="mt-0.5 truncate text-[11px] text-muted-foreground">{p.company.name}</p>
</div>
<Badge variant="outline" className="shrink-0 text-[10px]">{STATUS_LABELS[p.status] ?? p.status}</Badge>
<div className="flex items-center gap-2">
<Badge variant="outline" className="shrink-0 text-[10px]">{STATUS_LABELS[p.status] ?? p.status}</Badge>
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition group-hover:opacity-100">
<button
type="button"
onClick={(e) => { e.stopPropagation(); setEditTarget(projectToForm(p)); setCreateOpen(true) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Bearbeiten"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); setDeleteTarget(p) }}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Löschen"
>
<Trash2 className="size-3.5" />
</button>
</div>
</div>
</div>
<div className="mt-3 flex flex-wrap items-center gap-1.5">
@@ -193,6 +224,29 @@ export function ProjectsView() {
)}
</div>
</div>
<ProjectFormDialog
open={createOpen}
onOpenChange={setCreateOpen}
companies={companies}
project={editTarget}
onSaved={refetch}
/>
{deleteTarget && (
<DeleteDialog
open={!!deleteTarget}
onOpenChange={(o) => !o && setDeleteTarget(null)}
entityLabel="Projekt"
entityName={deleteTarget.name}
endpoint={`/api/aos/projects/${deleteTarget.id}`}
onDeleted={() => {
if (selectedId === deleteTarget.id) setSelectedId(null)
setDeleteTarget(null)
refetch()
}}
/>
)}
</div>
)
}
@@ -423,6 +477,21 @@ function ProjectDetail({ project, onUpdated }: { project: Project; onUpdated?: (
)
}
// Convert a Project (view shape) into the form's value shape.
function projectToForm(p: Project): ProjectFormValue {
return {
id: p.id,
companyId: p.company.id,
name: p.name,
type: p.type,
budgetType: p.budgetType,
budgetHours: p.budgetHours ? String(p.budgetHours) : '',
fixedPriceEuro: p.fixedPriceCents ? (p.fixedPriceCents / 100).toString().replace('.', ',') : '',
startDate: p.startDate ? p.startDate.slice(0, 10) : '',
dueDate: p.dueDate ? p.dueDate.slice(0, 10) : '',
}
}
function TaskColumn({ label, tasks, muted, onTaskClick }: { label: string; tasks: Task[]; muted?: boolean; onTaskClick?: (task: Task) => void }) {
return (
<div>
+66 -1
View File
@@ -11,6 +11,8 @@ import {
Loader2,
Send,
MessageSquare,
Pencil,
Trash2,
} from 'lucide-react'
import { useFetch } from '@/hooks/use-fetch'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -23,6 +25,8 @@ import { PageHeader } from '../primitives'
import { formatRelative, formatDateTime } from '@/lib/format'
import { cn } from '@/lib/utils'
import { toast } from 'sonner'
import { TicketEditDialog, type TicketFormValue } from '../crud/ticket-edit-dialog'
import { DeleteDialog } from '../crud/delete-dialog'
interface TicketMsg { id: string; fromType: string; fromName: string; body: string; createdAt: string }
interface Ticket {
@@ -89,6 +93,8 @@ export function SupportView() {
const [selectedId, setSelectedId] = useState<string | null>(null)
const [aiBusy, setAiBusy] = useState<'summary' | 'reply' | null>(null)
const [replyDraft, setReplyDraft] = useState('')
const [editTarget, setEditTarget] = useState<TicketFormValue | null>(null)
const [deleteTarget, setDeleteTarget] = useState<Ticket | null>(null)
if (loading || !data) {
return (
@@ -185,7 +191,31 @@ export function SupportView() {
{/* Ticket list */}
<Card className="lg:col-span-2 overflow-hidden">
<CardHeader className="pb-2">
<CardTitle className="text-sm">Inbox ({tickets.length})</CardTitle>
<CardTitle className="flex items-center justify-between text-sm">
<span>Inbox ({tickets.length})</span>
<div className="flex items-center gap-0.5">
{selected && (
<>
<button
type="button"
onClick={() => setEditTarget(ticketToForm(selected))}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Bearbeiten"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
onClick={() => setDeleteTarget(selected)}
className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
title="Löschen"
>
<Trash2 className="size-3.5" />
</button>
</>
)}
</div>
</CardTitle>
</CardHeader>
<ScrollArea className="h-[72vh]">
<div className="space-y-1.5 p-2">
@@ -356,6 +386,41 @@ export function SupportView() {
)}
</div>
</div>
<TicketEditDialog
open={!!editTarget}
onOpenChange={(o) => !o && setEditTarget(null)}
ticket={editTarget}
onSaved={refetch}
/>
{deleteTarget && (
<DeleteDialog
open={!!deleteTarget}
onOpenChange={(o) => !o && setDeleteTarget(null)}
entityLabel="Ticket"
entityName={deleteTarget.subject}
endpoint={`/api/aos/tickets/${deleteTarget.id}`}
description="Tickets mit Nachrichten können nicht gelöscht werden — schließe das Ticket stattdessen. Audit-Log wird geschrieben (GoBD)."
onDeleted={() => {
if (selectedId === deleteTarget.id) setSelectedId(null)
setDeleteTarget(null)
refetch()
}}
/>
)}
</div>
)
}
// Convert a Ticket (view shape) into the form's value shape.
function ticketToForm(t: Ticket): TicketFormValue {
return {
id: t.id,
subject: t.subject,
status: t.status,
priority: t.priority,
categoryId: t.categoryId,
assignee: t.assignee ?? '',
}
}