added invoices and status in cockpit, created info button for contract status types

This commit is contained in:
2026-02-08 01:18:12 +01:00
parent 1ad4fe0819
commit aee48a8ccb
45 changed files with 4543 additions and 863 deletions
@@ -0,0 +1,393 @@
import { useState, useRef } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Edit, Trash2, ChevronDown, ChevronUp, FileText, Download, AlertTriangle, Check, Eye } from 'lucide-react';
import Modal from '../ui/Modal';
import Button from '../ui/Button';
import Input from '../ui/Input';
import Select from '../ui/Select';
import Badge from '../ui/Badge';
import { invoiceApi } from '../../services/api';
import type { Invoice, InvoiceType } from '../../types';
const invoiceTypeLabels: Record<InvoiceType, string> = {
INTERIM: 'Zwischenrechnung',
FINAL: 'Schlussrechnung',
NOT_AVAILABLE: 'Nicht verfügbar',
};
interface InvoicesSectionProps {
ecdId: number; // energyContractDetailsId
invoices: Invoice[];
contractId: number;
canEdit: boolean;
}
export default function InvoicesSection({
ecdId,
invoices,
contractId,
canEdit,
}: InvoicesSectionProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [showAddModal, setShowAddModal] = useState(false);
const [editingInvoice, setEditingInvoice] = useState<Invoice | null>(null);
const queryClient = useQueryClient();
const deleteInvoiceMutation = useMutation({
mutationFn: (invoiceId: number) => invoiceApi.deleteInvoice(ecdId, invoiceId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['contract', contractId.toString()] });
},
});
// Sort invoices by date (newest first)
const sortedInvoices = [...invoices].sort(
(a, b) => new Date(b.invoiceDate).getTime() - new Date(a.invoiceDate).getTime()
);
const hasFinalInvoice = invoices.some(i => i.invoiceType === 'FINAL');
const hasNotAvailable = invoices.some(i => i.invoiceType === 'NOT_AVAILABLE');
return (
<div className="mt-4 pt-4 border-t">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-gray-500" />
<h4 className="text-sm font-medium text-gray-700">Rechnungen</h4>
<Badge variant="default">{invoices.length}</Badge>
{/* Status-Indicator */}
{hasFinalInvoice ? (
<span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-green-100 text-green-800">
<Check className="w-3 h-3" />
Schlussrechnung
</span>
) : hasNotAvailable ? (
<span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-yellow-100 text-yellow-800">
<AlertTriangle className="w-3 h-3" />
Nicht verfügbar
</span>
) : invoices.length > 0 ? (
<span className="flex items-center gap-1 px-2 py-0.5 text-xs rounded-full bg-orange-100 text-orange-800">
<AlertTriangle className="w-3 h-3" />
Schlussrechnung fehlt
</span>
) : null}
</div>
<div className="flex items-center gap-2">
{canEdit && (
<Button variant="ghost" size="sm" onClick={() => setShowAddModal(true)}>
<Plus className="w-4 h-4" />
</Button>
)}
{invoices.length > 0 && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="text-gray-500 hover:text-gray-700"
>
{isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
</button>
)}
</div>
</div>
{/* Collapsed view - show latest invoice */}
{!isExpanded && sortedInvoices.length > 0 && (
<div className="text-sm text-gray-600">
Letzte: {new Date(sortedInvoices[0].invoiceDate).toLocaleDateString('de-DE')} - {invoiceTypeLabels[sortedInvoices[0].invoiceType]}
</div>
)}
{/* Expanded view */}
{isExpanded && sortedInvoices.length > 0 && (
<div className="space-y-2">
{sortedInvoices.map((invoice) => (
<div
key={invoice.id}
className="flex items-center justify-between p-3 bg-gray-50 rounded-lg group"
>
<div className="flex items-center gap-4">
<div>
<div className="text-sm font-medium">
{new Date(invoice.invoiceDate).toLocaleDateString('de-DE')}
</div>
<div className="text-xs text-gray-500">
{invoiceTypeLabels[invoice.invoiceType]}
</div>
</div>
{invoice.documentPath && (
<div className="flex items-center gap-2">
<a
href={`/api${invoice.documentPath}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm"
title="Anzeigen"
>
<Eye className="w-4 h-4" />
</a>
<a
href={`/api${invoice.documentPath}`}
download
className="flex items-center gap-1 text-blue-600 hover:text-blue-800 text-sm"
title="Download"
>
<Download className="w-4 h-4" />
</a>
</div>
)}
{invoice.notes && (
<span className="text-xs text-gray-400 italic">{invoice.notes}</span>
)}
</div>
{canEdit && (
<div className="flex items-center gap-2 opacity-0 group-hover:opacity-100">
<button
onClick={() => setEditingInvoice(invoice)}
className="text-gray-500 hover:text-blue-600"
title="Bearbeiten"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={() => {
if (confirm('Rechnung wirklich löschen?')) {
deleteInvoiceMutation.mutate(invoice.id);
}
}}
className="text-gray-500 hover:text-red-600"
title="Löschen"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
)}
</div>
))}
</div>
)}
{isExpanded && sortedInvoices.length === 0 && (
<p className="text-sm text-gray-500 italic">Keine Rechnungen vorhanden.</p>
)}
{/* Add/Edit Invoice Modal */}
{(showAddModal || editingInvoice) && (
<InvoiceModal
isOpen={true}
onClose={() => {
setShowAddModal(false);
setEditingInvoice(null);
}}
ecdId={ecdId}
contractId={contractId}
invoice={editingInvoice}
/>
)}
</div>
);
}
// Invoice Modal Component
function InvoiceModal({
isOpen,
onClose,
ecdId,
contractId,
invoice,
}: {
isOpen: boolean;
onClose: () => void;
ecdId: number;
contractId: number;
invoice?: Invoice | null;
}) {
const queryClient = useQueryClient();
const isEditing = !!invoice;
const fileInputRef = useRef<HTMLInputElement>(null);
const [formData, setFormData] = useState({
invoiceDate: invoice?.invoiceDate
? new Date(invoice.invoiceDate).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0],
invoiceType: invoice?.invoiceType || 'INTERIM' as InvoiceType,
notes: invoice?.notes || '',
});
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [error, setError] = useState<string | null>(null);
const createMutation = useMutation({
mutationFn: async () => {
// Validierung: Dokument ist Pflicht, außer bei NOT_AVAILABLE
if (formData.invoiceType !== 'NOT_AVAILABLE' && !selectedFile) {
throw new Error('Bitte laden Sie ein Dokument hoch');
}
// 1. Invoice erstellen
const result = await invoiceApi.addInvoice(ecdId, {
invoiceDate: formData.invoiceDate,
invoiceType: formData.invoiceType,
notes: formData.notes || undefined,
});
// 2. Upload file if selected
if (selectedFile && result.data?.id) {
await invoiceApi.uploadDocument(result.data.id, selectedFile);
}
return result;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['contract', contractId.toString()] });
onClose();
},
onError: (err: Error) => {
setError(err.message);
},
});
const updateMutation = useMutation({
mutationFn: async () => {
// Validierung: Dokument ist Pflicht, außer bei NOT_AVAILABLE
if (formData.invoiceType !== 'NOT_AVAILABLE' && !invoice?.documentPath && !selectedFile) {
throw new Error('Bitte laden Sie ein Dokument hoch');
}
// 1. Invoice aktualisieren
const result = await invoiceApi.updateInvoice(ecdId, invoice!.id, {
invoiceDate: formData.invoiceDate,
invoiceType: formData.invoiceType,
notes: formData.notes || undefined,
});
// 2. Upload file if selected
if (selectedFile) {
await invoiceApi.uploadDocument(invoice!.id, selectedFile);
}
return result;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['contract', contractId.toString()] });
onClose();
},
onError: (err: Error) => {
setError(err.message);
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
setError(null);
if (isEditing) {
updateMutation.mutate();
} else {
createMutation.mutate();
}
};
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
if (file.type !== 'application/pdf') {
setError('Nur PDF-Dateien sind erlaubt');
return;
}
if (file.size > 10 * 1024 * 1024) {
setError('Datei ist zu groß (max. 10 MB)');
return;
}
setSelectedFile(file);
setError(null);
}
};
const isPending = createMutation.isPending || updateMutation.isPending;
return (
<Modal isOpen={isOpen} onClose={onClose} title={isEditing ? 'Rechnung bearbeiten' : 'Rechnung hinzufügen'}>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
{error}
</div>
)}
<Input
label="Rechnungsdatum"
type="date"
value={formData.invoiceDate}
onChange={(e) => setFormData({ ...formData, invoiceDate: e.target.value })}
required
/>
<Select
label="Rechnungstyp"
value={formData.invoiceType}
onChange={(e) => setFormData({ ...formData, invoiceType: e.target.value as InvoiceType })}
options={[
{ value: 'INTERIM', label: 'Zwischenrechnung' },
{ value: 'FINAL', label: 'Schlussrechnung' },
{ value: 'NOT_AVAILABLE', label: 'Nicht verfügbar' },
]}
/>
{formData.invoiceType !== 'NOT_AVAILABLE' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Dokument (PDF) *
</label>
{invoice?.documentPath && !selectedFile && (
<div className="mb-2 text-sm text-green-600 flex items-center gap-1">
<Check className="w-4 h-4" />
Dokument vorhanden
</div>
)}
{selectedFile && (
<div className="mb-2 text-sm text-blue-600 flex items-center gap-1">
<FileText className="w-4 h-4" />
{selectedFile.name}
</div>
)}
<input
type="file"
ref={fileInputRef}
accept=".pdf"
onChange={handleFileSelect}
className="hidden"
/>
<Button
type="button"
variant="secondary"
onClick={() => fileInputRef.current?.click()}
>
{invoice?.documentPath || selectedFile ? 'Ersetzen' : 'PDF hochladen'}
</Button>
</div>
)}
{formData.invoiceType === 'NOT_AVAILABLE' && (
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800 text-sm">
Bei diesem Typ wird kein Dokument benötigt. Die Rechnung wird als "nicht mehr zu bekommen" markiert.
</div>
)}
<Input
label="Notizen (optional)"
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
placeholder="Optionale Anmerkungen..."
/>
<div className="flex justify-end gap-3 pt-4">
<Button type="button" variant="secondary" onClick={onClose}>
Abbrechen
</Button>
<Button type="submit" disabled={isPending}>
{isPending ? 'Wird gespeichert...' : isEditing ? 'Speichern' : 'Hinzufügen'}
</Button>
</div>
</form>
</Modal>
);
}
@@ -1,10 +1,13 @@
import { useState } from 'react';
import { FileText, User, CreditCard, IdCard, AlertTriangle, Check, ChevronDown, ChevronRight } from 'lucide-react';
import { FileText, User, CreditCard, IdCard, AlertTriangle, Check, ChevronDown, ChevronRight, Receipt } from 'lucide-react';
import Modal from '../ui/Modal';
import Button from '../ui/Button';
import Input from '../ui/Input';
import Select from '../ui/Select';
import { cachedEmailApi, AttachmentTargetSlot, AttachmentEntityWithSlots } from '../../services/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import type { InvoiceType } from '../../types';
interface SaveAttachmentModalProps {
isOpen: boolean;
@@ -22,6 +25,8 @@ type SelectedTarget = {
label: string;
};
type SaveMode = 'document' | 'invoice';
export default function SaveAttachmentModal({
isOpen,
onClose,
@@ -31,6 +36,12 @@ export default function SaveAttachmentModal({
}: SaveAttachmentModalProps) {
const [selectedTarget, setSelectedTarget] = useState<SelectedTarget | null>(null);
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['customer']));
const [saveMode, setSaveMode] = useState<SaveMode>('document');
const [invoiceData, setInvoiceData] = useState({
invoiceDate: new Date().toISOString().split('T')[0],
invoiceType: 'INTERIM' as InvoiceType,
notes: '',
});
const queryClient = useQueryClient();
// Ziele laden
@@ -42,6 +53,9 @@ export default function SaveAttachmentModal({
const targets = targetsData?.data;
// Prüfen ob es ein Energievertrag ist
const isEnergyContract = targets?.contract?.type === 'ELECTRICITY' || targets?.contract?.type === 'GAS';
const saveMutation = useMutation({
mutationFn: () => {
if (!selectedTarget) throw new Error('Kein Ziel ausgewählt');
@@ -73,8 +87,40 @@ export default function SaveAttachmentModal({
},
});
const saveInvoiceMutation = useMutation({
mutationFn: () => {
return cachedEmailApi.saveAttachmentAsInvoice(emailId, attachmentFilename, {
invoiceDate: invoiceData.invoiceDate,
invoiceType: invoiceData.invoiceType,
notes: invoiceData.notes || undefined,
});
},
onSuccess: () => {
toast.success('Anhang als Rechnung gespeichert');
queryClient.invalidateQueries({ queryKey: ['attachment-targets', emailId] });
queryClient.invalidateQueries({ queryKey: ['customers'] });
queryClient.invalidateQueries({ queryKey: ['contracts'] });
if (targets?.contract?.id) {
queryClient.invalidateQueries({ queryKey: ['contract', targets.contract.id.toString()] });
}
onSuccess?.();
handleClose();
},
onError: (error: Error) => {
toast.error(error.message || 'Fehler beim Speichern der Rechnung');
},
});
const handleClose = () => {
setSelectedTarget(null);
setSaveMode('document');
setInvoiceData({
invoiceDate: new Date().toISOString().split('T')[0],
invoiceType: 'INTERIM',
notes: '',
});
onClose();
};
@@ -215,59 +261,127 @@ export default function SaveAttachmentModal({
</div>
)}
{/* Targets */}
{targets && (
<div className="space-y-3 max-h-96 overflow-auto">
{/* Kunde */}
{renderSection(
`Kunde: ${targets.customer.name}`,
'customer',
<User className="w-4 h-4 text-blue-600" />,
renderSlots(targets.customer.slots, 'customer'),
targets.customer.slots.length === 0
)}
{/* Ausweise */}
{renderSection(
'Ausweisdokumente',
'identityDocuments',
<IdCard className="w-4 h-4 text-green-600" />,
targets.identityDocuments.map((doc) =>
renderEntityWithSlots(doc, 'identityDocument')
),
targets.identityDocuments.length === 0
)}
{/* Bankkarten */}
{renderSection(
'Bankkarten',
'bankCards',
<CreditCard className="w-4 h-4 text-purple-600" />,
targets.bankCards.map((card) => renderEntityWithSlots(card, 'bankCard')),
targets.bankCards.length === 0
)}
{/* Vertrag */}
{targets.contract && renderSection(
`Vertrag: ${targets.contract.contractNumber}`,
'contract',
<FileText className="w-4 h-4 text-orange-600" />,
renderSlots(targets.contract.slots, 'contract'),
targets.contract.slots.length === 0
)}
{!targets.contract && (
<div className="p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
<FileText className="w-4 h-4 inline-block mr-2 text-gray-400" />
E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um
Vertragsdokumente als Ziel auswählen zu können.
<>
{/* Mode Toggle für Energieverträge */}
{isEnergyContract && (
<div className="flex gap-2 p-1 bg-gray-100 rounded-lg">
<button
onClick={() => setSaveMode('document')}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
saveMode === 'document'
? 'bg-white text-blue-600 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
<FileText className="w-4 h-4" />
Als Dokument
</button>
<button
onClick={() => setSaveMode('invoice')}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
saveMode === 'invoice'
? 'bg-white text-green-600 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
<Receipt className="w-4 h-4" />
Als Rechnung
</button>
</div>
)}
</div>
{/* Document Mode */}
{saveMode === 'document' && (
<div className="space-y-3 max-h-96 overflow-auto">
{/* Kunde */}
{renderSection(
`Kunde: ${targets.customer.name}`,
'customer',
<User className="w-4 h-4 text-blue-600" />,
renderSlots(targets.customer.slots, 'customer'),
targets.customer.slots.length === 0
)}
{/* Ausweise */}
{renderSection(
'Ausweisdokumente',
'identityDocuments',
<IdCard className="w-4 h-4 text-green-600" />,
targets.identityDocuments.map((doc) =>
renderEntityWithSlots(doc, 'identityDocument')
),
targets.identityDocuments.length === 0
)}
{/* Bankkarten */}
{renderSection(
'Bankkarten',
'bankCards',
<CreditCard className="w-4 h-4 text-purple-600" />,
targets.bankCards.map((card) => renderEntityWithSlots(card, 'bankCard')),
targets.bankCards.length === 0
)}
{/* Vertrag */}
{targets.contract && renderSection(
`Vertrag: ${targets.contract.contractNumber}`,
'contract',
<FileText className="w-4 h-4 text-orange-600" />,
renderSlots(targets.contract.slots, 'contract'),
targets.contract.slots.length === 0
)}
{!targets.contract && (
<div className="p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
<FileText className="w-4 h-4 inline-block mr-2 text-gray-400" />
E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um
Vertragsdokumente als Ziel auswählen zu können.
</div>
)}
</div>
)}
{/* Invoice Mode */}
{saveMode === 'invoice' && isEnergyContract && (
<div className="space-y-4">
<div className="p-3 bg-green-50 rounded-lg">
<p className="text-sm text-green-700">
Der Anhang wird als Rechnung für den Vertrag <strong>{targets.contract?.contractNumber}</strong> gespeichert.
</p>
</div>
<Input
label="Rechnungsdatum"
type="date"
value={invoiceData.invoiceDate}
onChange={(e) => setInvoiceData({ ...invoiceData, invoiceDate: e.target.value })}
required
/>
<Select
label="Rechnungstyp"
value={invoiceData.invoiceType}
onChange={(e) => setInvoiceData({ ...invoiceData, invoiceType: e.target.value as InvoiceType })}
options={[
{ value: 'INTERIM', label: 'Zwischenrechnung' },
{ value: 'FINAL', label: 'Schlussrechnung' },
]}
/>
<Input
label="Notizen (optional)"
value={invoiceData.notes}
onChange={(e) => setInvoiceData({ ...invoiceData, notes: e.target.value })}
placeholder="Optionale Anmerkungen..."
/>
</div>
)}
</>
)}
{/* Warning if replacing */}
{selectedTarget?.hasDocument && (
{saveMode === 'document' && selectedTarget?.hasDocument && (
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
<AlertTriangle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
<div className="text-sm text-yellow-800">
@@ -282,12 +396,21 @@ export default function SaveAttachmentModal({
<Button variant="secondary" onClick={handleClose}>
Abbrechen
</Button>
<Button
onClick={() => saveMutation.mutate()}
disabled={!selectedTarget || saveMutation.isPending}
>
{saveMutation.isPending ? 'Wird gespeichert...' : 'Speichern'}
</Button>
{saveMode === 'document' ? (
<Button
onClick={() => saveMutation.mutate()}
disabled={!selectedTarget || saveMutation.isPending || saveInvoiceMutation.isPending}
>
{saveMutation.isPending ? 'Wird gespeichert...' : 'Speichern'}
</Button>
) : (
<Button
onClick={() => saveInvoiceMutation.mutate()}
disabled={!invoiceData.invoiceDate || saveMutation.isPending || saveInvoiceMutation.isPending}
>
{saveInvoiceMutation.isPending ? 'Wird gespeichert...' : 'Als Rechnung speichern'}
</Button>
)}
</div>
</div>
</Modal>
@@ -1,10 +1,13 @@
import { useState } from 'react';
import { FileText, User, CreditCard, IdCard, AlertTriangle, Check, ChevronDown, ChevronRight } from 'lucide-react';
import { FileText, User, CreditCard, IdCard, AlertTriangle, Check, ChevronDown, ChevronRight, Receipt } from 'lucide-react';
import Modal from '../ui/Modal';
import Button from '../ui/Button';
import Input from '../ui/Input';
import Select from '../ui/Select';
import { cachedEmailApi, AttachmentTargetSlot, AttachmentEntityWithSlots } from '../../services/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import type { InvoiceType } from '../../types';
interface SaveEmailAsPdfModalProps {
isOpen: boolean;
@@ -21,6 +24,8 @@ type SelectedTarget = {
label: string;
};
type SaveMode = 'document' | 'invoice';
export default function SaveEmailAsPdfModal({
isOpen,
onClose,
@@ -29,6 +34,12 @@ export default function SaveEmailAsPdfModal({
}: SaveEmailAsPdfModalProps) {
const [selectedTarget, setSelectedTarget] = useState<SelectedTarget | null>(null);
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['customer']));
const [saveMode, setSaveMode] = useState<SaveMode>('document');
const [invoiceData, setInvoiceData] = useState({
invoiceDate: new Date().toISOString().split('T')[0],
invoiceType: 'INTERIM' as InvoiceType,
notes: '',
});
const queryClient = useQueryClient();
// Ziele laden (gleiche wie bei Anhängen)
@@ -40,6 +51,9 @@ export default function SaveEmailAsPdfModal({
const targets = targetsData?.data;
// Prüfen ob es ein Energievertrag ist
const isEnergyContract = targets?.contract?.type === 'ELECTRICITY' || targets?.contract?.type === 'GAS';
const saveMutation = useMutation({
mutationFn: () => {
if (!selectedTarget) throw new Error('Kein Ziel ausgewählt');
@@ -71,8 +85,40 @@ export default function SaveEmailAsPdfModal({
},
});
const saveInvoiceMutation = useMutation({
mutationFn: () => {
return cachedEmailApi.saveEmailAsInvoice(emailId, {
invoiceDate: invoiceData.invoiceDate,
invoiceType: invoiceData.invoiceType,
notes: invoiceData.notes || undefined,
});
},
onSuccess: () => {
toast.success('E-Mail als Rechnung gespeichert');
queryClient.invalidateQueries({ queryKey: ['attachment-targets', emailId] });
queryClient.invalidateQueries({ queryKey: ['customers'] });
queryClient.invalidateQueries({ queryKey: ['contracts'] });
if (targets?.contract?.id) {
queryClient.invalidateQueries({ queryKey: ['contract', targets.contract.id.toString()] });
}
onSuccess?.();
handleClose();
},
onError: (error: Error) => {
toast.error(error.message || 'Fehler beim Speichern der Rechnung');
},
});
const handleClose = () => {
setSelectedTarget(null);
setSaveMode('document');
setInvoiceData({
invoiceDate: new Date().toISOString().split('T')[0],
invoiceType: 'INTERIM',
notes: '',
});
onClose();
};
@@ -189,6 +235,8 @@ export default function SaveEmailAsPdfModal({
);
};
const isPending = saveMutation.isPending || saveInvoiceMutation.isPending;
return (
<Modal isOpen={isOpen} onClose={handleClose} title="E-Mail als PDF speichern" size="lg">
<div className="space-y-4">
@@ -213,59 +261,127 @@ export default function SaveEmailAsPdfModal({
</div>
)}
{/* Targets */}
{targets && (
<div className="space-y-3 max-h-96 overflow-auto">
{/* Kunde */}
{renderSection(
`Kunde: ${targets.customer.name}`,
'customer',
<User className="w-4 h-4 text-blue-600" />,
renderSlots(targets.customer.slots, 'customer'),
targets.customer.slots.length === 0
)}
{/* Ausweise */}
{renderSection(
'Ausweisdokumente',
'identityDocuments',
<IdCard className="w-4 h-4 text-green-600" />,
targets.identityDocuments.map((doc) =>
renderEntityWithSlots(doc, 'identityDocument')
),
targets.identityDocuments.length === 0
)}
{/* Bankkarten */}
{renderSection(
'Bankkarten',
'bankCards',
<CreditCard className="w-4 h-4 text-purple-600" />,
targets.bankCards.map((card) => renderEntityWithSlots(card, 'bankCard')),
targets.bankCards.length === 0
)}
{/* Vertrag */}
{targets.contract && renderSection(
`Vertrag: ${targets.contract.contractNumber}`,
'contract',
<FileText className="w-4 h-4 text-orange-600" />,
renderSlots(targets.contract.slots, 'contract'),
targets.contract.slots.length === 0
)}
{!targets.contract && (
<div className="p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
<FileText className="w-4 h-4 inline-block mr-2 text-gray-400" />
E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um
Vertragsdokumente als Ziel auswählen zu können.
<>
{/* Mode Toggle für Energieverträge */}
{isEnergyContract && (
<div className="flex gap-2 p-1 bg-gray-100 rounded-lg">
<button
onClick={() => setSaveMode('document')}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
saveMode === 'document'
? 'bg-white text-blue-600 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
<FileText className="w-4 h-4" />
Als Dokument
</button>
<button
onClick={() => setSaveMode('invoice')}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
saveMode === 'invoice'
? 'bg-white text-green-600 shadow-sm'
: 'text-gray-600 hover:text-gray-900'
}`}
>
<Receipt className="w-4 h-4" />
Als Rechnung
</button>
</div>
)}
</div>
{/* Document Mode */}
{saveMode === 'document' && (
<div className="space-y-3 max-h-96 overflow-auto">
{/* Kunde */}
{renderSection(
`Kunde: ${targets.customer.name}`,
'customer',
<User className="w-4 h-4 text-blue-600" />,
renderSlots(targets.customer.slots, 'customer'),
targets.customer.slots.length === 0
)}
{/* Ausweise */}
{renderSection(
'Ausweisdokumente',
'identityDocuments',
<IdCard className="w-4 h-4 text-green-600" />,
targets.identityDocuments.map((doc) =>
renderEntityWithSlots(doc, 'identityDocument')
),
targets.identityDocuments.length === 0
)}
{/* Bankkarten */}
{renderSection(
'Bankkarten',
'bankCards',
<CreditCard className="w-4 h-4 text-purple-600" />,
targets.bankCards.map((card) => renderEntityWithSlots(card, 'bankCard')),
targets.bankCards.length === 0
)}
{/* Vertrag */}
{targets.contract && renderSection(
`Vertrag: ${targets.contract.contractNumber}`,
'contract',
<FileText className="w-4 h-4 text-orange-600" />,
renderSlots(targets.contract.slots, 'contract'),
targets.contract.slots.length === 0
)}
{!targets.contract && (
<div className="p-3 bg-gray-50 rounded-lg text-sm text-gray-600">
<FileText className="w-4 h-4 inline-block mr-2 text-gray-400" />
E-Mail ist keinem Vertrag zugeordnet. Ordnen Sie die E-Mail einem Vertrag zu, um
Vertragsdokumente als Ziel auswählen zu können.
</div>
)}
</div>
)}
{/* Invoice Mode */}
{saveMode === 'invoice' && isEnergyContract && (
<div className="space-y-4">
<div className="p-3 bg-green-50 rounded-lg">
<p className="text-sm text-green-700">
Die E-Mail wird als Rechnung für den Vertrag <strong>{targets.contract?.contractNumber}</strong> gespeichert.
</p>
</div>
<Input
label="Rechnungsdatum"
type="date"
value={invoiceData.invoiceDate}
onChange={(e) => setInvoiceData({ ...invoiceData, invoiceDate: e.target.value })}
required
/>
<Select
label="Rechnungstyp"
value={invoiceData.invoiceType}
onChange={(e) => setInvoiceData({ ...invoiceData, invoiceType: e.target.value as InvoiceType })}
options={[
{ value: 'INTERIM', label: 'Zwischenrechnung' },
{ value: 'FINAL', label: 'Schlussrechnung' },
]}
/>
<Input
label="Notizen (optional)"
value={invoiceData.notes}
onChange={(e) => setInvoiceData({ ...invoiceData, notes: e.target.value })}
placeholder="Optionale Anmerkungen..."
/>
</div>
)}
</>
)}
{/* Warning if replacing */}
{selectedTarget?.hasDocument && (
{saveMode === 'document' && selectedTarget?.hasDocument && (
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-2">
<AlertTriangle className="w-5 h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
<div className="text-sm text-yellow-800">
@@ -280,12 +396,21 @@ export default function SaveEmailAsPdfModal({
<Button variant="secondary" onClick={handleClose}>
Abbrechen
</Button>
<Button
onClick={() => saveMutation.mutate()}
disabled={!selectedTarget || saveMutation.isPending}
>
{saveMutation.isPending ? 'Wird erstellt...' : 'Als PDF speichern'}
</Button>
{saveMode === 'document' ? (
<Button
onClick={() => saveMutation.mutate()}
disabled={!selectedTarget || isPending}
>
{isPending ? 'Wird erstellt...' : 'Als PDF speichern'}
</Button>
) : (
<Button
onClick={() => saveInvoiceMutation.mutate()}
disabled={!invoiceData.invoiceDate || isPending}
>
{isPending ? 'Wird erstellt...' : 'Als Rechnung speichern'}
</Button>
)}
</div>
</div>
</Modal>