initial commit
This commit is contained in:
145
src/components/import/ComdirectSyncPanel.tsx
Normal file
145
src/components/import/ComdirectSyncPanel.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
import { useState } from "react";
|
||||
import { useAction } from "convex/react";
|
||||
import { api } from "../../../convex/_generated/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { toast } from "sonner";
|
||||
import { subDays, format } from "date-fns";
|
||||
|
||||
export function ComdirectSyncPanel() {
|
||||
const startAuth = useAction(api.comdirect.auth.start);
|
||||
const confirmAuth = useAction(api.comdirect.auth.confirm);
|
||||
const runSync = useAction(api.comdirect.sync.run);
|
||||
|
||||
const [zugangsnummer, setZugangsnummer] = useState("");
|
||||
const [pin, setPin] = useState("");
|
||||
const [tan, setTan] = useState("");
|
||||
const [challengeType, setChallengeType] = useState<string | null>(null);
|
||||
const [photoTan, setPhotoTan] = useState<string | null>(null);
|
||||
const [step, setStep] = useState<"login" | "confirm" | "sync">("login");
|
||||
const [from, setFrom] = useState(format(subDays(new Date(), 90), "yyyy-MM-dd"));
|
||||
const [to, setTo] = useState(format(new Date(), "yyyy-MM-dd"));
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleStart = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await startAuth({ zugangsnummer, pin });
|
||||
setPin("");
|
||||
setChallengeType(result.challengeType);
|
||||
setPhotoTan(result.photoTanPngBase64 ?? null);
|
||||
setStep("confirm");
|
||||
if (result.challengeType === "P_TAN_PUSH") {
|
||||
toast.message("Bitte Freigabe in der photoTAN-App bestätigen");
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Anmeldung fehlgeschlagen");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirm = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await confirmAuth({ tan: tan || undefined });
|
||||
setTan("");
|
||||
setStep("sync");
|
||||
toast.success("comdirect-Session aktiv");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "TAN-Bestätigung fehlgeschlagen");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSync = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await runSync({ from, to });
|
||||
toast.success(`${result.importedCount} importiert, ${result.skippedCount} übersprungen`);
|
||||
setStep("login");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Sync fehlgeschlagen");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>comdirect-Sync</CardTitle>
|
||||
<CardDescription>
|
||||
Halbautomatischer Abruf über Convex Actions. PIN wird nicht gespeichert. Nach dem Sync werden
|
||||
Tokens gelöscht. Achtung: 3× falsche TAN sperrt den Zugang.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
Nur lesende Endpoints. Client-ID/Secret müssen in Convex-Env gesetzt sein (
|
||||
COMDIRECT_CLIENT_ID, COMDIRECT_CLIENT_SECRET).
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{step === "login" && (
|
||||
<>
|
||||
<div>
|
||||
<Label>Zugangsnummer</Label>
|
||||
<Input value={zugangsnummer} onChange={(e) => setZugangsnummer(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Online-Banking-PIN</Label>
|
||||
<Input type="password" value={pin} onChange={(e) => setPin(e.target.value)} />
|
||||
</div>
|
||||
<Button onClick={handleStart} disabled={loading}>
|
||||
Anmelden & TAN anfordern
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === "confirm" && (
|
||||
<>
|
||||
{challengeType === "P_TAN_PUSH" && (
|
||||
<p className="text-sm">Bitte die Push-TAN in der comdirect-App freigeben, dann bestätigen.</p>
|
||||
)}
|
||||
{photoTan && (
|
||||
<img src={`data:image/png;base64,${photoTan}`} alt="photoTAN" className="mx-auto max-w-xs" />
|
||||
)}
|
||||
{(challengeType === "M_TAN" || challengeType === "P_TAN") && (
|
||||
<div>
|
||||
<Label>TAN</Label>
|
||||
<Input value={tan} onChange={(e) => setTan(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={handleConfirm} disabled={loading}>
|
||||
Session aktivieren
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === "sync" && (
|
||||
<>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<Label>Von</Label>
|
||||
<Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Bis</Label>
|
||||
<Input type="date" value={to} onChange={(e) => setTo(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={handleSync} disabled={loading}>
|
||||
Jetzt synchronisieren
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
225
src/components/import/CsvImportWizard.tsx
Normal file
225
src/components/import/CsvImportWizard.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { parse, type ParseResult } from "papaparse";
|
||||
import { format, parse as parseDate } from "date-fns";
|
||||
import { useMutation, useQuery } from "convex/react";
|
||||
import { api } from "../../../convex/_generated/api";
|
||||
import type { Id } from "../../../convex/_generated/dataModel";
|
||||
import { categorize, parseCounterpartyFromBuchungstext, parseGermanAmount } from "@convex-lib/categorize";
|
||||
import { resolveAssignedAndEffective } from "@convex-lib/month";
|
||||
import { computeDedupHash } from "@convex-lib/comdirectMap";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { ImportPreviewTable, type PreviewRow } from "./ImportPreviewTable";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const HEADER = "Buchungstag;Wertstellung (Valuta);Vorgang;Buchungstext;Umsatz in EUR";
|
||||
|
||||
function parseComdirectCsv(text: string): Array<Record<string, string>> {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const rows: Array<Record<string, string>> = [];
|
||||
let inBlock = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.trim() === HEADER) {
|
||||
inBlock = true;
|
||||
continue;
|
||||
}
|
||||
if (!inBlock) continue;
|
||||
if (
|
||||
!line.trim() ||
|
||||
line.startsWith("Alter Kontostand") ||
|
||||
line.startsWith("Neuer Kontostand") ||
|
||||
line.startsWith("Umsätze") ||
|
||||
line.startsWith("Keine Umsätze")
|
||||
) {
|
||||
inBlock = false;
|
||||
continue;
|
||||
}
|
||||
const parsed: ParseResult<string[]> = parse(line, { delimiter: ";", quoteChar: '"' });
|
||||
const fields = parsed.data[0];
|
||||
if (!fields || fields.length < 5) continue;
|
||||
rows.push({
|
||||
buchungstag: fields[0],
|
||||
valuta: fields[1],
|
||||
vorgang: fields[2],
|
||||
buchungstext: fields[3],
|
||||
betrag: fields[4],
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function CsvImportWizard() {
|
||||
const accounts = useQuery(api.accounts.list);
|
||||
const settings = useQuery(api.settings.get);
|
||||
const categories = useQuery(api.categories.list);
|
||||
const commitRows = useMutation(api.imports.commitRows);
|
||||
|
||||
const [step, setStep] = useState<"upload" | "preview" | "done">("upload");
|
||||
const [filename, setFilename] = useState("");
|
||||
const [accountId, setAccountId] = useState<string>();
|
||||
const [rows, setRows] = useState<PreviewRow[]>([]);
|
||||
const [result, setResult] = useState<{ imported: number; skipped: number } | null>(null);
|
||||
|
||||
const processFile = useCallback(
|
||||
async (file: File) => {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const text = new TextDecoder("iso-8859-1").decode(buffer);
|
||||
const parsed = parseComdirectCsv(text);
|
||||
const ownNames = settings?.ownNames ?? [];
|
||||
const salaryShift = settings?.salaryShift ?? {
|
||||
enabled: true,
|
||||
categoryNames: ["Gehalt & Besoldung"],
|
||||
dayThreshold: 25,
|
||||
};
|
||||
|
||||
const preview: PreviewRow[] = [];
|
||||
for (const row of parsed) {
|
||||
const isPending = row.buchungstag.trim().toLowerCase() === "offen";
|
||||
let bookingDate: string | undefined;
|
||||
if (!isPending) {
|
||||
const d = parseDate(row.buchungstag, "dd.MM.yyyy", new Date());
|
||||
bookingDate = format(d, "yyyy-MM-dd");
|
||||
}
|
||||
const amount = parseGermanAmount(row.betrag);
|
||||
const { counterparty, description, rawText } = parseCounterpartyFromBuchungstext(row.buchungstext);
|
||||
const categoryName = categorize(rawText, amount, row.vorgang, ownNames);
|
||||
const { assignedMonth, effectiveMonth } = resolveAssignedAndEffective(
|
||||
bookingDate,
|
||||
amount,
|
||||
categoryName,
|
||||
salaryShift,
|
||||
);
|
||||
const dedupHash = await computeDedupHash({
|
||||
accountId,
|
||||
bookingDate,
|
||||
amount,
|
||||
description,
|
||||
vorgang: row.vorgang,
|
||||
});
|
||||
preview.push({
|
||||
bookingDate,
|
||||
valueDate: row.valuta
|
||||
? format(parseDate(row.valuta, "dd.MM.yyyy", new Date()), "yyyy-MM-dd")
|
||||
: undefined,
|
||||
description,
|
||||
counterparty,
|
||||
amount,
|
||||
vorgang: row.vorgang,
|
||||
isPending,
|
||||
rawText,
|
||||
categoryName,
|
||||
assignedMonth,
|
||||
effectiveMonth,
|
||||
dedupHash,
|
||||
});
|
||||
}
|
||||
setRows(preview);
|
||||
setFilename(file.name);
|
||||
setStep("preview");
|
||||
},
|
||||
[settings, accountId],
|
||||
);
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) void processFile(file);
|
||||
};
|
||||
|
||||
const handleCommit = async () => {
|
||||
if (!accountId) {
|
||||
toast.error("Bitte Konto wählen");
|
||||
return;
|
||||
}
|
||||
const res = await commitRows({
|
||||
filename,
|
||||
source: "comdirect-csv",
|
||||
accountId: accountId as Id<"accounts">,
|
||||
rows: rows.map((r) => ({
|
||||
bookingDate: r.bookingDate,
|
||||
valueDate: r.valueDate,
|
||||
description: r.description,
|
||||
counterparty: r.counterparty,
|
||||
amount: r.amount,
|
||||
vorgang: r.vorgang,
|
||||
isPending: r.isPending,
|
||||
rawText: r.rawText,
|
||||
categoryName: r.categoryName,
|
||||
assignedMonth: r.assignedMonth,
|
||||
effectiveMonth: r.effectiveMonth,
|
||||
dedupHash: r.dedupHash,
|
||||
categoryId: categories?.find((c) => c.name === r.categoryName)?._id,
|
||||
})),
|
||||
});
|
||||
setResult({ imported: res.importedCount, skipped: res.skippedCount });
|
||||
setStep("done");
|
||||
toast.success(`${res.importedCount} importiert, ${res.skippedCount} übersprungen`);
|
||||
};
|
||||
|
||||
if (step === "upload") {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>CSV-Import (comdirect)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div
|
||||
className="flex min-h-40 cursor-pointer flex-col items-center justify-center rounded-lg border border-dashed p-8 text-center"
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<p className="mb-2 text-sm text-muted-foreground">
|
||||
comdirect-CSV hier ablegen (ISO-8859-1, Semikolon)
|
||||
</p>
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,.CSV"
|
||||
onChange={(e) => e.target.files?.[0] && void processFile(e.target.files[0])}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (step === "preview") {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Select value={accountId} onValueChange={setAccountId}>
|
||||
<SelectTrigger className="w-[220px]">
|
||||
<SelectValue placeholder="Konto wählen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{accounts?.map((a) => (
|
||||
<SelectItem key={a._id} value={a._id}>
|
||||
{a.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button onClick={handleCommit}>Import starten</Button>
|
||||
<Button variant="outline" onClick={() => setStep("upload")}>
|
||||
Zurück
|
||||
</Button>
|
||||
</div>
|
||||
<ImportPreviewTable rows={rows} onRowsChange={setRows} categories={categories ?? []} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<p>
|
||||
Import abgeschlossen: {result?.imported} Buchungen importiert, {result?.skipped} übersprungen.
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => setStep("upload")}>
|
||||
Weiteren Import starten
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
82
src/components/import/ImportPreviewTable.tsx
Normal file
82
src/components/import/ImportPreviewTable.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { amountClass, formatAmount, formatDate, formatMonth } from "@/lib/format";
|
||||
import type { Doc } from "../../../convex/_generated/dataModel";
|
||||
|
||||
export type PreviewRow = {
|
||||
bookingDate?: string;
|
||||
valueDate?: string;
|
||||
description: string;
|
||||
counterparty?: string;
|
||||
amount: number;
|
||||
vorgang?: string;
|
||||
isPending: boolean;
|
||||
rawText?: string;
|
||||
categoryName: string;
|
||||
assignedMonth?: string;
|
||||
effectiveMonth?: string;
|
||||
dedupHash?: string;
|
||||
isDuplicate?: boolean;
|
||||
};
|
||||
|
||||
export function ImportPreviewTable({
|
||||
rows,
|
||||
onRowsChange,
|
||||
categories,
|
||||
}: {
|
||||
rows: PreviewRow[];
|
||||
onRowsChange: (rows: PreviewRow[]) => void;
|
||||
categories: Doc<"categories">[];
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Datum</TableHead>
|
||||
<TableHead>Beschreibung</TableHead>
|
||||
<TableHead>Betrag</TableHead>
|
||||
<TableHead>Kategorie</TableHead>
|
||||
<TableHead>Monat</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.map((row, idx) => (
|
||||
<TableRow key={idx}>
|
||||
<TableCell>{row.isPending ? "offen" : formatDate(row.bookingDate)}</TableCell>
|
||||
<TableCell>{row.description}</TableCell>
|
||||
<TableCell className={amountClass(row.amount)}>{formatAmount(row.amount)}</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={row.categoryName}
|
||||
onValueChange={(name) => {
|
||||
const next = [...rows];
|
||||
next[idx] = { ...row, categoryName: name };
|
||||
onRowsChange(next);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-[200px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{categories.map((c) => (
|
||||
<SelectItem key={c._id} value={c.name}>
|
||||
{c.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{row.assignedMonth && row.assignedMonth !== row.bookingDate?.slice(0, 7) && (
|
||||
<Badge variant="outline">{formatMonth(row.assignedMonth)}</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user