feat(T06): Verkaufsmodul + Rechtsdokumente + DATEV-Export + Sales UI
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ContractPreview } from '@/components/sales/ContractPreview';
|
||||
import { getSale, deleteSale, verifyUstId, type SaleResponse } from '@/lib/sales';
|
||||
|
||||
export default function SaleDetailPage() {
|
||||
const params = useParams();
|
||||
const saleId = params.id as string;
|
||||
|
||||
const [sale, setSale] = useState<SaleResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [ustResult, setUstResult] = useState<string | null>(null);
|
||||
|
||||
const fetchSale = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await getSale(saleId);
|
||||
setSale(data);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to load sale');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [saleId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSale();
|
||||
}, [fetchSale]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!confirm('Verkauf wirklich stornieren?')) return;
|
||||
try {
|
||||
await deleteSale(saleId);
|
||||
fetchSale();
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to cancel sale');
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerifyUstId = async () => {
|
||||
try {
|
||||
const result = await verifyUstId(saleId);
|
||||
setUstResult(`${result.verified ? 'Verifiziert' : 'Nicht verifiziert'}: ${result.message}`);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to verify USt-IdNr.');
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div data-testid="sale-detail-loading">Wird geladen...</div>;
|
||||
if (error) return <div className="bg-red-50 text-red-600 p-3 rounded" data-testid="sale-detail-error">{error}</div>;
|
||||
if (!sale) return <div data-testid="sale-detail-not-found">Verkauf nicht gefunden</div>;
|
||||
|
||||
return (
|
||||
<div className="space-y-6" data-testid="sale-detail">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Verkauf #{sale.id.slice(0, 8)}</h1>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleVerifyUstId} data-testid="sale-verify-ust-btn">
|
||||
USt-IdNr. prüfen
|
||||
</Button>
|
||||
<Button onClick={handleDelete} variant="secondary" data-testid="sale-delete-btn">
|
||||
Stornieren
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{ustResult && (
|
||||
<div className="bg-blue-50 text-blue-600 p-3 rounded" data-testid="sale-ust-result">
|
||||
{ustResult}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="bg-gray-50 p-4 rounded">
|
||||
<h2 className="font-semibold mb-2">Fahrzeug</h2>
|
||||
{sale.vehicle ? (
|
||||
<div data-testid="sale-detail-vehicle">
|
||||
<p>{sale.vehicle.make} {sale.vehicle.model}</p>
|
||||
<p className="text-sm text-gray-600">FIN: {sale.vehicle.fin}</p>
|
||||
<p className="text-sm text-gray-600">Typ: {sale.vehicle.vehicle_type}</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">Nicht verfügbar</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-4 rounded">
|
||||
<h2 className="font-semibold mb-2">Käufer</h2>
|
||||
{sale.buyer ? (
|
||||
<div data-testid="sale-detail-buyer">
|
||||
<p>{sale.buyer.company_name}</p>
|
||||
<p className="text-sm text-gray-600">{sale.buyer.address_city}, {sale.buyer.address_country}</p>
|
||||
{sale.buyer.vat_id && <p className="text-sm text-gray-600">USt-IdNr.: {sale.buyer.vat_id}</p>}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">Nicht verfügbar</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 p-4 rounded">
|
||||
<h2 className="font-semibold mb-2">Verkaufsdetails</h2>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<span className="text-sm text-gray-500">Preis</span>
|
||||
<p className="font-medium" data-testid="sale-detail-price">
|
||||
{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sale.sale_price)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-gray-500">Datum</span>
|
||||
<p className="font-medium">{new Date(sale.sale_date).toLocaleDateString('de-DE')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-gray-500">Status</span>
|
||||
<p className="font-medium">{sale.status}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-sm text-gray-500">GwG</span>
|
||||
<p className="font-medium">{sale.is_gwg ? 'Ja' : 'Nein'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ContractPreview saleId={sale.id} contractPdfPath={sale.contract_pdf_path} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SaleForm } from '@/components/sales/SaleForm';
|
||||
|
||||
export default function NeuVerkaufPage() {
|
||||
return <SaleForm />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SaleList } from '@/components/sales/SaleList';
|
||||
|
||||
export default function VerkaufPage() {
|
||||
return <SaleList />;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { getContractDownloadUrl, regenerateContract } from '@/lib/sales';
|
||||
|
||||
interface ContractPreviewProps {
|
||||
saleId: string;
|
||||
contractPdfPath?: string | null;
|
||||
}
|
||||
|
||||
export function ContractPreview({ saleId, contractPdfPath }: ContractPreviewProps) {
|
||||
const [regenerating, setRegenerating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pdfPath, setPdfPath] = useState<string | null>(contractPdfPath || null);
|
||||
|
||||
const handleRegenerate = async () => {
|
||||
setRegenerating(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await regenerateContract(saleId);
|
||||
setPdfPath(result.contract_pdf_path);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to regenerate contract');
|
||||
} finally {
|
||||
setRegenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadUrl = getContractDownloadUrl(saleId);
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="contract-preview">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-bold">Vertrags-PDF</h2>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleRegenerate}
|
||||
disabled={regenerating}
|
||||
data-testid="contract-regenerate-btn"
|
||||
>
|
||||
{regenerating ? 'Wird erstellt...' : 'Vertrag neu generieren'}
|
||||
</Button>
|
||||
{pdfPath && (
|
||||
<a href={downloadUrl} target="_blank" rel="noopener noreferrer" data-testid="contract-download-link">
|
||||
<Button>Herunterladen</Button>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 text-red-600 p-3 rounded" data-testid="contract-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pdfPath ? (
|
||||
<iframe
|
||||
src={downloadUrl}
|
||||
className="w-full h-[600px] border rounded"
|
||||
data-testid="contract-iframe"
|
||||
title="Vertrags-PDF"
|
||||
/>
|
||||
) : (
|
||||
<div className="bg-gray-50 p-8 text-center rounded" data-testid="contract-empty">
|
||||
<p className="text-gray-500">Es wurde noch kein Vertrag generiert.</p>
|
||||
<p className="text-sm text-gray-400 mt-2">
|
||||
Klicken Sie auf "Vertrag neu generieren", um ein PDF zu erstellen.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Table } from '@/components/ui/Table';
|
||||
import {
|
||||
createDatevExport,
|
||||
listDatevExports,
|
||||
getDatevDownloadUrl,
|
||||
type DATEVExportResponse,
|
||||
} from '@/lib/datev';
|
||||
import type { PaginatedResponse } from '@/lib/api';
|
||||
|
||||
export function DatevExport() {
|
||||
const [exports, setExports] = useState<DATEVExportResponse[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [endDate, setEndDate] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
const fetchExports = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: PaginatedResponse<DATEVExportResponse> = await listDatevExports();
|
||||
setExports(data.items);
|
||||
setTotal(data.total);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to load exports');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchExports();
|
||||
}, [fetchExports]);
|
||||
|
||||
const handleCreateExport = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setCreating(true);
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
try {
|
||||
const result = await createDatevExport({ start_date: startDate, end_date: endDate });
|
||||
setSuccess(`Export erstellt: ${result.total_amount} EUR`);
|
||||
fetchExports();
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to create export');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
key: 'start_date',
|
||||
label: 'Von',
|
||||
render: (row: DATEVExportResponse) =>
|
||||
new Date(row.start_date).toLocaleDateString('de-DE'),
|
||||
},
|
||||
{
|
||||
key: 'end_date',
|
||||
label: 'Bis',
|
||||
render: (row: DATEVExportResponse) =>
|
||||
new Date(row.end_date).toLocaleDateString('de-DE'),
|
||||
},
|
||||
{
|
||||
key: 'total_amount',
|
||||
label: 'Gesamtbetrag',
|
||||
render: (row: DATEVExportResponse) =>
|
||||
new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(row.total_amount),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
label: 'Erstellt am',
|
||||
render: (row: DATEVExportResponse) =>
|
||||
row.created_at ? new Date(row.created_at).toLocaleString('de-DE') : 'N/A',
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Aktion',
|
||||
render: (row: DATEVExportResponse) => (
|
||||
<a
|
||||
href={getDatevDownloadUrl(row.id)}
|
||||
data-testid={`datev-download-${row.id}`}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
CSV herunterladen
|
||||
</a>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="datev-export">
|
||||
<h1 className="text-2xl font-bold">DATEV Export</h1>
|
||||
|
||||
{/* Create export form */}
|
||||
<form onSubmit={handleCreateExport} className="flex gap-4 items-end" data-testid="datev-export-form">
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium mb-1">Von Datum *</label>
|
||||
<Input
|
||||
data-testid="datev-start-date"
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={e => setStartDate(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium mb-1">Bis Datum *</label>
|
||||
<Input
|
||||
data-testid="datev-end-date"
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={e => setEndDate(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" disabled={creating} data-testid="datev-create-btn">
|
||||
{creating ? 'Wird erstellt...' : 'Export erstellen'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 text-red-600 p-3 rounded" data-testid="datev-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="bg-green-50 text-green-600 p-3 rounded" data-testid="datev-success">
|
||||
{success}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div data-testid="datev-loading">Wird geladen...</div>
|
||||
) : (
|
||||
<Table columns={columns} data={exports} rowKey={(row) => row.id} />
|
||||
)}
|
||||
|
||||
{total === 0 && !loading && (
|
||||
<p className="text-gray-500" data-testid="datev-empty">Noch keine Exporte vorhanden.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { createSale, type SaleCreateData } from '@/lib/sales';
|
||||
import { listVehicles, type VehicleResponse } from '@/lib/vehicles';
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import type { PaginatedResponse } from '@/lib/api';
|
||||
|
||||
export function SaleForm() {
|
||||
const router = useRouter();
|
||||
const [vehicles, setVehicles] = useState<VehicleResponse[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [formData, setFormData] = useState<SaleCreateData>({
|
||||
vehicle_id: '',
|
||||
buyer_contact_id: '',
|
||||
sale_price: 0,
|
||||
sale_date: new Date().toISOString().split('T')[0],
|
||||
status: 'draft',
|
||||
is_gwg: false,
|
||||
});
|
||||
|
||||
const fetchVehicles = useCallback(async () => {
|
||||
try {
|
||||
const data: PaginatedResponse<VehicleResponse> = await listVehicles({ page: 1, page_size: 100 });
|
||||
setVehicles(data.items.filter(v => v.availability === 'available'));
|
||||
} catch {
|
||||
// ignore - vehicles list is optional
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchVehicles();
|
||||
}, [fetchVehicles]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const sale = await createSale(formData);
|
||||
router.push(`/de/verkauf/${sale.id}`);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to create sale');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 max-w-2xl" data-testid="sale-form">
|
||||
<h1 className="text-2xl font-bold">Neuer Verkauf</h1>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 text-red-600 p-3 rounded" data-testid="sale-form-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Fahrzeug *</label>
|
||||
<select
|
||||
data-testid="sale-vehicle-select"
|
||||
className="w-full border rounded px-3 py-2"
|
||||
value={formData.vehicle_id}
|
||||
onChange={e => setFormData(prev => ({ ...prev, vehicle_id: e.target.value }))}
|
||||
required
|
||||
>
|
||||
<option value="">Fahrzeug auswählen</option>
|
||||
{vehicles.map(v => (
|
||||
<option key={v.id} value={v.id}>
|
||||
{v.make} {v.model} - {v.fin}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Käufer Kontakt ID *</label>
|
||||
<Input
|
||||
data-testid="sale-buyer-input"
|
||||
value={formData.buyer_contact_id}
|
||||
onChange={e => setFormData(prev => ({ ...prev, buyer_contact_id: e.target.value }))}
|
||||
placeholder="UUID des Käufer-Kontakts"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Verkaufspreis (EUR) *</label>
|
||||
<Input
|
||||
data-testid="sale-price-input"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.sale_price}
|
||||
onChange={e => setFormData(prev => ({ ...prev, sale_price: parseFloat(e.target.value) || 0 }))}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Verkaufsdatum</label>
|
||||
<Input
|
||||
data-testid="sale-date-input"
|
||||
type="date"
|
||||
value={formData.sale_date}
|
||||
onChange={e => setFormData(prev => ({ ...prev, sale_date: e.target.value }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Status</label>
|
||||
<select
|
||||
data-testid="sale-status-select"
|
||||
className="w-full border rounded px-3 py-2"
|
||||
value={formData.status}
|
||||
onChange={e => setFormData(prev => ({ ...prev, status: e.target.value }))}
|
||||
>
|
||||
<option value="draft">Entwurf</option>
|
||||
<option value="completed">Abgeschlossen</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
data-testid="sale-gwg-toggle"
|
||||
type="checkbox"
|
||||
id="is_gwg"
|
||||
checked={formData.is_gwg}
|
||||
onChange={e => setFormData(prev => ({ ...prev, is_gwg: e.target.checked }))}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<label htmlFor="is_gwg" className="text-sm font-medium">
|
||||
Geringwertiges Wirtschaftsgut (GwG) - §6 Abs. 2 EStG
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit" disabled={loading} data-testid="sale-submit-btn">
|
||||
{loading ? 'Wird gespeichert...' : 'Verkauf anlegen'}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => router.back()} variant="secondary">
|
||||
Abbrechen
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Table } from '@/components/ui/Table';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import {
|
||||
listSales,
|
||||
type SaleResponse,
|
||||
type SaleListParams,
|
||||
} from '@/lib/sales';
|
||||
import type { PaginatedResponse } from '@/lib/api';
|
||||
|
||||
const STATUS_OPTIONS = ['draft', 'completed', 'cancelled'];
|
||||
|
||||
export function SaleList() {
|
||||
const router = useRouter();
|
||||
const [sales, setSales] = useState<SaleResponse[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize] = useState(20);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [filters, setFilters] = useState<SaleListParams>({
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
const fetchSales = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data: PaginatedResponse<SaleResponse> = await listSales(filters);
|
||||
setSales(data.items);
|
||||
setTotal(data.total);
|
||||
setPage(data.page);
|
||||
} catch (err: unknown) {
|
||||
const apiErr = err as { error?: { message?: string } };
|
||||
setError(apiErr?.error?.message || 'Failed to load sales');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filters]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSales();
|
||||
}, [fetchSales]);
|
||||
|
||||
const handleFilterChange = (key: keyof SaleListParams, value: string) => {
|
||||
setFilters(prev => ({
|
||||
...prev,
|
||||
page: 1,
|
||||
[key]: value || undefined,
|
||||
}));
|
||||
};
|
||||
|
||||
const handlePageChange = (newPage: number) => {
|
||||
setFilters(prev => ({ ...prev, page: newPage }));
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
key: 'sale_date',
|
||||
label: 'Datum',
|
||||
render: (row: SaleResponse) =>
|
||||
new Date(row.sale_date).toLocaleDateString('de-DE'),
|
||||
},
|
||||
{
|
||||
key: 'vehicle',
|
||||
label: 'Fahrzeug',
|
||||
render: (row: SaleResponse) =>
|
||||
row.vehicle ? `${row.vehicle.make} ${row.vehicle.model}` : 'N/A',
|
||||
},
|
||||
{
|
||||
key: 'buyer',
|
||||
label: 'Käufer',
|
||||
render: (row: SaleResponse) =>
|
||||
row.buyer?.company_name || 'N/A',
|
||||
},
|
||||
{
|
||||
key: 'sale_price',
|
||||
label: 'Preis',
|
||||
render: (row: SaleResponse) =>
|
||||
new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(row.sale_price),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
label: 'Status',
|
||||
render: (row: SaleResponse) => (
|
||||
<span
|
||||
data-testid={`sale-status-${row.id}`}
|
||||
className={`px-2 py-1 rounded text-xs font-medium ${
|
||||
row.status === 'completed' ? 'bg-green-100 text-green-800' :
|
||||
row.status === 'cancelled' ? 'bg-red-100 text-red-800' :
|
||||
'bg-yellow-100 text-yellow-800'
|
||||
}`}
|
||||
>
|
||||
{row.status}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'is_gwg',
|
||||
label: 'GwG',
|
||||
render: (row: SaleResponse) =>
|
||||
row.is_gwg ? (
|
||||
<span data-testid={`sale-gwg-${row.id}`} className="text-blue-600 font-medium">Ja</span>
|
||||
) : 'Nein',
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
label: 'Aktionen',
|
||||
render: (row: SaleResponse) => (
|
||||
<button
|
||||
data-testid={`sale-row-${row.id}`}
|
||||
onClick={() => router.push(`/de/verkauf/${row.id}`)}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
Details
|
||||
</button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-testid="sale-list">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Verkäufe</h1>
|
||||
<Button onClick={() => router.push('/de/verkauf/neu')} data-testid="sale-create-btn">
|
||||
Neuer Verkauf
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<div className="flex gap-4 items-end" data-testid="sale-filters">
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium mb-1">Status</label>
|
||||
<select
|
||||
data-testid="sale-status-filter"
|
||||
className="w-full border rounded px-3 py-2"
|
||||
value={filters.status || ''}
|
||||
onChange={e => handleFilterChange('status', e.target.value)}
|
||||
>
|
||||
<option value="">Alle</option>
|
||||
{STATUS_OPTIONS.map(s => (
|
||||
<option key={s} value={s}>{s}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium mb-1">Von</label>
|
||||
<Input
|
||||
type="date"
|
||||
data-testid="sale-date-from"
|
||||
value={filters.date_from || ''}
|
||||
onChange={e => handleFilterChange('date_from', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium mb-1">Bis</label>
|
||||
<Input
|
||||
type="date"
|
||||
data-testid="sale-date-to"
|
||||
value={filters.date_to || ''}
|
||||
onChange={e => handleFilterChange('date_to', e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 text-red-600 p-3 rounded" data-testid="sale-error">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div data-testid="sale-loading">Wird geladen...</div>
|
||||
) : (
|
||||
<Table columns={columns} data={sales} rowKey={(row) => row.id} />
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between" data-testid="sale-pagination">
|
||||
<Button
|
||||
disabled={page <= 1}
|
||||
onClick={() => handlePageChange(page - 1)}
|
||||
>
|
||||
Zurück
|
||||
</Button>
|
||||
<span>Seite {page} von {totalPages}</span>
|
||||
<Button
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => handlePageChange(page + 1)}
|
||||
>
|
||||
Weiter
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { apiFetch, type PaginatedResponse } from './api';
|
||||
|
||||
export interface DATEVExportResponse {
|
||||
id: string;
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
file_path?: string | null;
|
||||
total_amount: number;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export interface DATEVExportCreate {
|
||||
start_date: string;
|
||||
end_date: string;
|
||||
}
|
||||
|
||||
export async function createDatevExport(data: DATEVExportCreate): Promise<DATEVExportResponse> {
|
||||
return apiFetch<DATEVExportResponse>('/datev/export', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function listDatevExports(page = 1, pageSize = 20): Promise<PaginatedResponse<DATEVExportResponse>> {
|
||||
return apiFetch<PaginatedResponse<DATEVExportResponse>>(`/datev/exports?page=${page}&page_size=${pageSize}`);
|
||||
}
|
||||
|
||||
export function getDatevDownloadUrl(id: string): string {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
|
||||
return `${baseUrl}/datev/exports/${id}/download`;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { apiFetch, type PaginatedResponse } from './api';
|
||||
|
||||
export interface VehicleNested {
|
||||
id: string;
|
||||
make: string;
|
||||
model: string;
|
||||
fin: string;
|
||||
vehicle_type: string;
|
||||
availability: string;
|
||||
price: number;
|
||||
}
|
||||
|
||||
export interface ContactNested {
|
||||
id: string;
|
||||
company_name: string;
|
||||
address_city?: string;
|
||||
address_country: string;
|
||||
vat_id?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
}
|
||||
|
||||
export interface SaleResponse {
|
||||
id: string;
|
||||
vehicle_id: string;
|
||||
buyer_contact_id: string;
|
||||
seller_contact_id?: string | null;
|
||||
sale_price: number;
|
||||
sale_date: string;
|
||||
status: string;
|
||||
is_gwg: boolean;
|
||||
contract_pdf_path?: string | null;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
vehicle?: VehicleNested;
|
||||
buyer?: ContactNested;
|
||||
seller?: ContactNested;
|
||||
}
|
||||
|
||||
export interface SaleCreateData {
|
||||
vehicle_id: string;
|
||||
buyer_contact_id: string;
|
||||
seller_contact_id?: string;
|
||||
sale_price: number;
|
||||
sale_date?: string;
|
||||
status?: string;
|
||||
is_gwg?: boolean;
|
||||
}
|
||||
|
||||
export interface SaleUpdateData {
|
||||
sale_price?: number;
|
||||
sale_date?: string;
|
||||
status?: string;
|
||||
is_gwg?: boolean;
|
||||
seller_contact_id?: string;
|
||||
}
|
||||
|
||||
export interface SaleListParams {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
status?: string;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
}
|
||||
|
||||
export interface ContractResponse {
|
||||
sale_id: string;
|
||||
contract_pdf_path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface UstIdVerifyResponse {
|
||||
verified: boolean;
|
||||
message: string;
|
||||
vat_id?: string | null;
|
||||
}
|
||||
|
||||
export async function listSales(params: SaleListParams = {}): Promise<PaginatedResponse<SaleResponse>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.page_size) query.set('page_size', String(params.page_size));
|
||||
if (params.status) query.set('status', params.status);
|
||||
if (params.date_from) query.set('date_from', params.date_from);
|
||||
if (params.date_to) query.set('date_to', params.date_to);
|
||||
return apiFetch<PaginatedResponse<SaleResponse>>(`/sales/?${query.toString()}`);
|
||||
}
|
||||
|
||||
export async function getSale(id: string): Promise<SaleResponse> {
|
||||
return apiFetch<SaleResponse>(`/sales/${id}`);
|
||||
}
|
||||
|
||||
export async function createSale(data: SaleCreateData): Promise<SaleResponse> {
|
||||
return apiFetch<SaleResponse>('/sales/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSale(id: string, data: SaleUpdateData): Promise<SaleResponse> {
|
||||
return apiFetch<SaleResponse>(`/sales/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteSale(id: string): Promise<SaleResponse> {
|
||||
return apiFetch<SaleResponse>(`/sales/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export async function regenerateContract(id: string): Promise<ContractResponse> {
|
||||
return apiFetch<ContractResponse>(`/sales/${id}/contract`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function verifyUstId(id: string): Promise<UstIdVerifyResponse> {
|
||||
return apiFetch<UstIdVerifyResponse>(`/sales/${id}/verify-ust-id`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function getContractDownloadUrl(id: string): string {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
|
||||
return `${baseUrl}/sales/${id}/contract`;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { DatevExport } from '@/components/sales/DatevExport';
|
||||
|
||||
// Mock the datev lib
|
||||
vi.mock('@/lib/datev', () => ({
|
||||
createDatevExport: vi.fn(),
|
||||
listDatevExports: vi.fn(),
|
||||
getDatevDownloadUrl: vi.fn().mockReturnValue('http://test/datev.csv'),
|
||||
}));
|
||||
|
||||
import { listDatevExports, createDatevExport } from '@/lib/datev';
|
||||
|
||||
describe('DatevExport', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders DATEV export page with title', async () => {
|
||||
vi.mocked(listDatevExports).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<DatevExport />);
|
||||
expect(screen.getByText('DATEV Export')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('datev-export')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has date range inputs', async () => {
|
||||
vi.mocked(listDatevExports).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<DatevExport />);
|
||||
expect(screen.getByTestId('datev-start-date')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('datev-end-date')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has create export button', async () => {
|
||||
vi.mocked(listDatevExports).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<DatevExport />);
|
||||
expect(screen.getByTestId('datev-create-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when no exports', async () => {
|
||||
vi.mocked(listDatevExports).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<DatevExport />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('datev-empty')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays exports in table', async () => {
|
||||
const mockExport = {
|
||||
id: 'test-export-id',
|
||||
start_date: '2025-01-01',
|
||||
end_date: '2025-01-31',
|
||||
total_amount: 95000,
|
||||
created_at: '2025-02-01T10:00:00Z',
|
||||
};
|
||||
vi.mocked(listDatevExports).mockResolvedValue({
|
||||
items: [mockExport],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<DatevExport />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('datev-download-test-export-id')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
|
||||
import { SaleList } from '@/components/sales/SaleList';
|
||||
import { SaleForm } from '@/components/sales/SaleForm';
|
||||
import { ContractPreview } from '@/components/sales/ContractPreview';
|
||||
|
||||
// Mock the sales lib
|
||||
vi.mock('@/lib/sales', () => ({
|
||||
listSales: vi.fn(),
|
||||
createSale: vi.fn(),
|
||||
getSale: vi.fn(),
|
||||
deleteSale: vi.fn(),
|
||||
regenerateContract: vi.fn(),
|
||||
verifyUstId: vi.fn(),
|
||||
getContractDownloadUrl: vi.fn().mockReturnValue('http://test/contract'),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/vehicles', () => ({
|
||||
listVehicles: vi.fn().mockResolvedValue({ items: [], total: 0, page: 1, page_size: 20 }),
|
||||
}));
|
||||
|
||||
import { listSales, createSale, regenerateContract } from '@/lib/sales';
|
||||
|
||||
describe('SaleList', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders sale list with title', async () => {
|
||||
vi.mocked(listSales).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<SaleList />);
|
||||
expect(screen.getByText('Verkäufe')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-list')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays sales in table', async () => {
|
||||
const mockSale = {
|
||||
id: 'test-sale-id',
|
||||
vehicle_id: 'v1',
|
||||
buyer_contact_id: 'b1',
|
||||
sale_price: 45000,
|
||||
sale_date: '2025-01-15',
|
||||
status: 'completed',
|
||||
is_gwg: false,
|
||||
vehicle: { id: 'v1', make: 'Mercedes', model: 'Actros', fin: 'WDB123', vehicle_type: 'lkw', availability: 'sold', price: 45000 },
|
||||
buyer: { id: 'b1', company_name: 'Test Buyer', address_country: 'DE' },
|
||||
};
|
||||
vi.mocked(listSales).mockResolvedValue({
|
||||
items: [mockSale],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<SaleList />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Mercedes Actros')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test Buyer')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows create button', async () => {
|
||||
vi.mocked(listSales).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<SaleList />);
|
||||
expect(screen.getByTestId('sale-create-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has status filter', async () => {
|
||||
vi.mocked(listSales).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<SaleList />);
|
||||
expect(screen.getByTestId('sale-status-filter')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has date range filters', async () => {
|
||||
vi.mocked(listSales).mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
|
||||
render(<SaleList />);
|
||||
expect(screen.getByTestId('sale-date-from')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-date-to')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SaleForm', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders form with required fields', async () => {
|
||||
render(<SaleForm />);
|
||||
expect(screen.getByTestId('sale-form')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-vehicle-select')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-buyer-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-price-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('sale-gwg-toggle')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has GwG toggle checkbox', async () => {
|
||||
render(<SaleForm />);
|
||||
const gwgToggle = screen.getByTestId('sale-gwg-toggle') as HTMLInputElement;
|
||||
expect(gwgToggle.type).toBe('checkbox');
|
||||
expect(gwgToggle.checked).toBe(false);
|
||||
});
|
||||
|
||||
it('has submit button', async () => {
|
||||
render(<SaleForm />);
|
||||
expect(screen.getByTestId('sale-submit-btn')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContractPreview', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('shows empty state when no PDF path', async () => {
|
||||
render(<ContractPreview saleId="test-id" contractPdfPath={null} />);
|
||||
expect(screen.getByTestId('contract-empty')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows regenerate button', async () => {
|
||||
render(<ContractPreview saleId="test-id" contractPdfPath={null} />);
|
||||
expect(screen.getByTestId('contract-regenerate-btn')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows iframe when PDF path exists', async () => {
|
||||
render(<ContractPreview saleId="test-id" contractPdfPath="/tmp/contract.pdf" />);
|
||||
expect(screen.getByTestId('contract-iframe')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user