feat: add receipt upload functionality for Einnahmen and Beleg routes
Build and Push Docker Image / build (push) Successful in 1m34s

- Implemented upload and retrieval of receipts (Belege) associated with Einnahmen entries.
- Added new API routes for uploading and deleting receipts.
- Updated the Einnahmen model to include a `belegUrl` field for storing receipt references.
- Enhanced the Einnahmen page to support file uploads and display existing receipts.
- Introduced drag-and-drop functionality for file uploads and improved user feedback during uploads.
- Added necessary validation for file types and sizes during uploads.
This commit is contained in:
hwinkel
2026-04-29 20:49:57 +02:00
parent f93eb0480a
commit fab53fc76e
12 changed files with 731 additions and 9 deletions
+130
View File
@@ -0,0 +1,130 @@
# Copilot Instructions — Annas Rechnungsmanager
German accounting & invoice management system for tax consultants (Steuerberater), built with React Router v7 (SSR), Prisma, MariaDB, and Tailwind CSS v4.
---
## Commands
```bash
npm run dev # Dev server at http://localhost:5173
npm run build # Production build
npm run typecheck # react-router typegen + tsc (run before every commit)
npm run lint # ESLint
npm run db:migrate # prisma migrate dev (create + apply migration)
npm run db:seed # Seed database with sample data
npm run db:studio # Prisma Studio GUI
npm run setup-admin # Create initial admin user
npm run reset-password
```
**Required `.env` variables:**
```env
DATABASE_URL="mysql://root:password@localhost:3306/annas_rechnungsmanager"
AUTH_SECRET="<random 32-byte hex>" # NOT SESSION_SECRET
NODE_ENV="development"
```
---
## Architecture
### Route Layout
Routes are **explicitly configured** in `app/routes.ts` (not auto-discovered by file name). Two layout wrappers exist:
- `dashboard-layout.tsx` — wraps all authenticated company/user routes
- `admin-layout.tsx` — wraps `/admin/*` (requires ADMIN role)
**UI routes** (`app/routes/companies.*.tsx`, etc.) export `loader` + default component.
**API routes** (`app/routes/api.*.ts`) export only `action` (no default export, no loader).
### Path Alias
`@/` resolves to `app/`. Use it everywhere: `import prisma from "@/lib/prisma.server"`.
### Data Flow Pattern
```
UI Route (loader/action)
→ app/lib/ (business logic + Prisma queries)
→ prisma.server.ts (single Prisma Client instance)
→ AuditLog (mandatory on every write)
```
Auth helpers live in `app/session.server.ts`:
- `requireUser(request)` — throws redirect to `/login` if not authenticated
- `requireAdmin(request)` — throws redirect to `/` if not ADMIN
- `getApiUser(request)` — returns user or null (for API routes)
---
## Key Conventions
### Input Validation
All Zod schemas live in `app/lib/schemas.ts`. Reusable validators (`currencySchema`, `taxRateSchema`, `ibanSchema`, `vatIdSchema`) are defined there — import and extend them, don't redefine.
API routes must `safeParse` the request body before any DB access:
```ts
const parsed = mySchema.safeParse(await request.json());
if (!parsed.success) return Response.json({ error: parsed.error.issues }, { status: 400 });
```
### Tax Calculations (Never Trust the Client)
Always **recalculate amounts server-side** using `app/lib/tax.ts`:
- `calcItemAmounts(quantity, unitPrice, taxRate)` — standard MwSt.
- `calcItemAmountsKleinunternehmer(quantity, unitPrice)` — §19 UStG, no VAT
- `calcInvoiceTotals(items)` — sums net/tax/gross
Valid tax rates: `0`, `7`, `19` (enforced by `taxRateSchema`).
The `Company.kleinunternehmer` flag controls which calculation is used — always read it from the DB, not from the request body.
### Audit Logging (Mandatory on Every Write)
Every mutation must call `log()` from `app/lib/logger.server.ts`. The `action` parameter must use the `LogAction` union type defined in that file:
```ts
await log({ userId: user.id, action: "CREATE_INVOICE", entity: "Invoice", entityId: invoice.id, metadata: {...}, request });
```
Logging failures are swallowed intentionally — never let them break the main operation.
### Database Rules
- All Prisma queries belong in `app/lib/`, not in routes or components.
- Use `prisma.$transaction()` for multi-step operations (e.g., creating an invoice + a Buchung entry).
- Invoice amounts are stored as both net/tax/gross (`Decimal(10,2)`) — always persist all three.
- Soft-delete pattern: invoices use `deletedAt` field; companies use `archived`/`archivedAt`.
- When an invoice is marked PAID, a linked `Buchung` record is created automatically.
### Domain Vocabulary (German ↔ Code)
| German | Code / Table |
|--------|--------------|
| Mandant | `Company` model |
| Buchung | `Buchung` model (transaction/ledger entry) |
| Anlagegut | `Anlagegut` model (fixed asset) |
| Ausgabe | expense (type `ENTNAHME` in `Buchung`) |
| Einnahme | revenue (type `EINLAGE` in `Buchung`) |
| Kleinunternehmer | §19 UStG — no VAT on invoices |
| AFA | Absetzung für Abnutzung — depreciation, computed in `app/lib/afa.ts` |
### Sessions
Session cookie name: `__session`, expires after **4 hours**, stored via `createCookieSessionStorage`. Keys stored in session: `userId`, `userName`, `userRole`.
---
## High-Impact Files
Changes to these files have wide blast radius — check dependents carefully:
| File | Why it matters |
|------|----------------|
| `app/session.server.ts` | Auth used by every protected route |
| `app/lib/tax.ts` | Tax calculations used in invoices, reports, exports |
| `app/lib/afa.ts` | Depreciation logic used in reports and asset management |
| `prisma/schema.prisma` | Any change requires a migration |
| `app/routes.ts` | Route config — adding routes here is required, not automatic |
+8
View File
@@ -0,0 +1,8 @@
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--browser", "chromium"]
}
}
}
+33
View File
@@ -0,0 +1,33 @@
name: "Copilot Setup Steps"
on:
workflow_dispatch:
push:
paths:
- .github/workflows/copilot-setup-steps.yml
pull_request:
paths:
- .github/workflows/copilot-setup-steps.yml
jobs:
copilot-setup-steps:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
+3
View File
@@ -47,3 +47,6 @@ next-env.d.ts
/db/data /db/data
/graphify-out /graphify-out
# Uploaded Belege (persistent volume in production)
data/documents/
+3 -1
View File
@@ -21,7 +21,9 @@ export type LogAction =
| "DELETE_CUSTOMER" | "DELETE_CUSTOMER"
| "CREATE_SERVICE" | "CREATE_SERVICE"
| "UPDATE_SERVICE" | "UPDATE_SERVICE"
| "DELETE_SERVICE"; | "DELETE_SERVICE"
| "UPLOAD_BELEG"
| "DELETE_BELEG";
export async function log({ export async function log({
userId, userId,
+2
View File
@@ -59,6 +59,8 @@ export default [
route("api/ausgaben/:id", "routes/api.ausgaben.$id.ts"), route("api/ausgaben/:id", "routes/api.ausgaben.$id.ts"),
route("api/einnahmen", "routes/api.einnahmen.ts"), route("api/einnahmen", "routes/api.einnahmen.ts"),
route("api/einnahmen/:id", "routes/api.einnahmen.$id.ts"), route("api/einnahmen/:id", "routes/api.einnahmen.$id.ts"),
route("api/einnahmen/:id/upload", "routes/api.einnahmen.$id.upload.ts"),
route("api/beleg/:userId/:filename", "routes/api.beleg.$userId.$filename.ts"),
route("api/companies/:id/buchungkategorien", "routes/api.companies.$id.buchungkategorien.ts"), route("api/companies/:id/buchungkategorien", "routes/api.companies.$id.buchungkategorien.ts"),
route("api/companies/:id/buchungkategorien/:katId", "routes/api.companies.$id.buchungkategorien.$katId.ts"), route("api/companies/:id/buchungkategorien/:katId", "routes/api.companies.$id.buchungkategorien.$katId.ts"),
route("api/anlagevermoegen", "routes/api.anlagevermoegen.ts"), route("api/anlagevermoegen", "routes/api.anlagevermoegen.ts"),
+57
View File
@@ -0,0 +1,57 @@
import { readFile } from "node:fs/promises";
import { join, resolve, extname } from "node:path";
import { requireUser } from "@/session.server";
const MIME: Record<string, string> = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".gif": "image/gif",
".pdf": "application/pdf",
};
function storageRoot(): string {
return resolve(process.env.BELEG_STORAGE_PATH ?? "data/documents");
}
export async function loader({
request,
params,
}: {
request: Request;
params: { userId: string; filename: string };
}) {
const user = await requireUser(request);
// Users may only access their own documents
if (params.userId !== user.id) {
throw new Response("Forbidden", { status: 403 });
}
// Prevent path traversal
const root = storageRoot();
const filePath = join(root, params.userId, params.filename);
if (!filePath.startsWith(root)) {
throw new Response("Forbidden", { status: 403 });
}
let data: Buffer;
try {
data = await readFile(filePath);
} catch {
throw new Response("Not Found", { status: 404 });
}
const ext = extname(params.filename).toLowerCase();
const contentType = MIME[ext] ?? "application/octet-stream";
const disposition = contentType === "application/pdf" ? "inline" : "inline";
return new Response(new Uint8Array(data), {
headers: {
"Content-Type": contentType,
"Content-Disposition": `${disposition}; filename="${params.filename}"`,
"Cache-Control": "private, max-age=3600",
},
});
}
+2
View File
@@ -9,6 +9,7 @@ const updateSchema = z.object({
zahlungsart: z.enum(["KASSE", "BANK"]).default("BANK"), zahlungsart: z.enum(["KASSE", "BANK"]).default("BANK"),
datum: z.string().min(1), datum: z.string().min(1),
beschreibung: z.string().optional(), beschreibung: z.string().optional(),
belegUrl: z.string().optional(),
}); });
/** /**
@@ -48,6 +49,7 @@ export async function action({ request, params }: { request: Request; params: {
account: parsed.data.zahlungsart === "KASSE" ? "KASSE" : "BANK", account: parsed.data.zahlungsart === "KASSE" ? "KASSE" : "BANK",
date: new Date(parsed.data.datum), date: new Date(parsed.data.datum),
description: parsed.data.beschreibung, description: parsed.data.beschreibung,
belegUrl: parsed.data.belegUrl || null,
}, },
}); });
+118
View File
@@ -0,0 +1,118 @@
import { getApiUser } from "@/session.server";
import prisma from "@/lib/prisma.server";
import { log } from "@/lib/logger.server";
import { writeFile, mkdir, unlink } from "node:fs/promises";
import { join, resolve } from "node:path";
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
const ALLOWED_MIME: Record<string, string> = {
"image/jpeg": "jpg",
"image/png": "png",
"image/webp": "webp",
"image/gif": "gif",
"application/pdf": "pdf",
};
/** Absolute path to the document storage root (configurable via env). */
function storageRoot(): string {
return resolve(process.env.BELEG_STORAGE_PATH ?? "data/documents");
}
/** belegUrl format stored in DB: "beleg:{userId}/{filename}" */
function parseBelegPath(belegUrl: string | null): string | null {
if (!belegUrl?.startsWith("beleg:")) return null;
return belegUrl.slice("beleg:".length); // "{userId}/{filename}"
}
async function removeUploadedFile(belegUrl: string | null) {
const rel = parseBelegPath(belegUrl);
if (!rel) return;
try {
await unlink(join(storageRoot(), rel));
} catch {
// File may already be gone
}
}
export async function action({
request,
params,
}: {
request: Request;
params: { id: string };
}) {
const user = await getApiUser(request);
if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });
const buchung = await prisma.buchung.findFirst({
where: { id: params.id, company: { userId: user.id }, isBusinessRecord: true },
select: { id: true, companyId: true, belegUrl: true },
});
if (!buchung) return Response.json({ error: "Not found" }, { status: 404 });
// DELETE — remove beleg
if (request.method === "DELETE") {
await removeUploadedFile(buchung.belegUrl);
await prisma.buchung.update({ where: { id: params.id }, data: { belegUrl: null } });
await log({
userId: user.id,
action: "DELETE_BELEG",
entity: "Buchung",
entityId: params.id,
request,
});
return Response.json({ ok: true });
}
if (request.method !== "POST") {
return Response.json({ error: "Method not allowed" }, { status: 405 });
}
// POST — upload new beleg
let formData: FormData;
try {
formData = await request.formData();
} catch {
return Response.json({ error: "Ungültige Formulardaten" }, { status: 400 });
}
const file = formData.get("file");
if (!(file instanceof File) || file.size === 0) {
return Response.json({ error: "Keine Datei angegeben" }, { status: 400 });
}
if (file.size > MAX_SIZE_BYTES) {
return Response.json({ error: "Datei zu groß (max. 10 MB)" }, { status: 413 });
}
const ext = ALLOWED_MIME[file.type];
if (!ext) {
return Response.json(
{ error: "Dateityp nicht erlaubt (erlaubt: PDF, JPG, PNG, WebP, GIF)" },
{ status: 415 }
);
}
// Replace old file if present
await removeUploadedFile(buchung.belegUrl);
const safeName = `${buchung.id}-${Date.now()}.${ext}`;
const userDir = join(storageRoot(), user.id);
await mkdir(userDir, { recursive: true });
await writeFile(join(userDir, safeName), Buffer.from(await file.arrayBuffer()));
// Store as "beleg:{userId}/{storedName}|{originalName}"
// storedName is used for serving; originalName is preserved for display
const originalName = file.name;
const belegUrl = `beleg:${user.id}/${safeName}|${originalName}`;
await prisma.buchung.update({ where: { id: params.id }, data: { belegUrl } });
await log({
userId: user.id,
action: "UPLOAD_BELEG",
entity: "Buchung",
entityId: params.id,
metadata: { filename: file.name, size: file.size, type: file.type },
request,
});
return Response.json({ belegUrl, originalName: file.name, size: file.size });
}
+2
View File
@@ -10,6 +10,7 @@ const createSchema = z.object({
zahlungsart: z.enum(["KASSE", "BANK"]).default("BANK"), zahlungsart: z.enum(["KASSE", "BANK"]).default("BANK"),
datum: z.string().min(1), datum: z.string().min(1),
beschreibung: z.string().optional(), beschreibung: z.string().optional(),
belegUrl: z.string().optional(),
}); });
/** /**
@@ -105,6 +106,7 @@ export async function action({ request }: { request: Request }) {
steuersatz: parsed.data.steuersatz, steuersatz: parsed.data.steuersatz,
zahlungsart: parsed.data.zahlungsart, zahlungsart: parsed.data.zahlungsart,
isBusinessRecord: true, isBusinessRecord: true,
belegUrl: parsed.data.belegUrl || null,
}, },
}); });
@@ -1,4 +1,4 @@
import { useState, useMemo } from "react"; import { useState, useMemo, useRef, useCallback } from "react";
import { Link, useLoaderData, useRevalidator } from "react-router"; import { Link, useLoaderData, useRevalidator } from "react-router";
import { requireUser } from "@/session.server"; import { requireUser } from "@/session.server";
import prisma from "@/lib/prisma.server"; import prisma from "@/lib/prisma.server";
@@ -6,10 +6,32 @@ import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { ChevronLeft, Plus, Pencil, Trash2, Loader2, Banknote, Landmark } from "lucide-react"; import { ChevronLeft, Plus, Pencil, Trash2, Loader2, Banknote, Landmark, List, LayoutGrid, Paperclip, Upload, X, FileText } from "lucide-react";
import { formatCurrency } from "@/lib/tax"; import { formatCurrency } from "@/lib/tax";
import { DEFAULT_EINNAHME_KATEGORIEN } from "@/lib/kategorie-defaults"; import { DEFAULT_EINNAHME_KATEGORIEN } from "@/lib/kategorie-defaults";
/** Converts stored belegUrl ("beleg:{userId}/{storedName}|{originalName}") to a viewable href. */
function belegHref(belegUrl: string | null): string | null {
if (!belegUrl) return null;
if (belegUrl.startsWith("beleg:")) {
const rel = belegUrl.slice("beleg:".length); // "userId/storedName|originalName"
const [userId, rest] = rel.split("/");
const storedName = rest?.split("|")[0]; // strip "|originalName" if present
return `/api/beleg/${userId}/${storedName}`;
}
return belegUrl; // fallback for legacy http(s) URLs
}
/** Extracts a human-readable display name from a stored belegUrl. */
function belegDisplayName(belegUrl: string): string {
if (belegUrl.startsWith("beleg:")) {
const rest = belegUrl.split("/").pop() ?? "Beleg"; // "storedName|originalName" or just "storedName"
const parts = rest.split("|");
return parts.length > 1 ? parts.slice(1).join("|") : parts[0]; // prefer originalName
}
return belegUrl.split("/").pop() ?? "Beleg";
}
export const handle = { export const handle = {
breadcrumbs: (data: { companyId: string; companyName: string }) => [ breadcrumbs: (data: { companyId: string; companyName: string }) => [
{ label: "Mandanten", href: "/companies" }, { label: "Mandanten", href: "/companies" },
@@ -35,6 +57,7 @@ interface Einnahme {
zahlungsart: "KASSE" | "BANK"; zahlungsart: "KASSE" | "BANK";
datum: string; datum: string;
beschreibung: string | null; beschreibung: string | null;
belegUrl: string | null;
} }
const emptyForm = { const emptyForm = {
@@ -44,6 +67,7 @@ const emptyForm = {
zahlungsart: "BANK" as "KASSE" | "BANK", zahlungsart: "BANK" as "KASSE" | "BANK",
datum: new Date().toISOString().slice(0, 10), datum: new Date().toISOString().slice(0, 10),
beschreibung: "", beschreibung: "",
belegUrl: "",
}; };
export async function loader({ request, params }: { request: Request; params: { id: string } }) { export async function loader({ request, params }: { request: Request; params: { id: string } }) {
@@ -99,6 +123,7 @@ export async function loader({ request, params }: { request: Request; params: {
zahlungsart: (e.zahlungsart as "KASSE" | "BANK") || "BANK", zahlungsart: (e.zahlungsart as "KASSE" | "BANK") || "BANK",
datum: e.date.toISOString(), datum: e.date.toISOString(),
beschreibung: e.description, beschreibung: e.description,
belegUrl: e.belegUrl ?? null,
})), })),
}; };
} }
@@ -113,6 +138,47 @@ export default function EinnahmenPage() {
const [loadingYear, setLoadingYear] = useState(false); const [loadingYear, setLoadingYear] = useState(false);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null); const [deleting, setDeleting] = useState<string | null>(null);
const [view, setView] = useState<"pivot" | "liste">("liste");
// File upload state
const [pendingFile, setPendingFile] = useState<File | null>(null);
const [uploadingBeleg, setUploadingBeleg] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [dragOver, setDragOver] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Quick-upload from list view (without opening dialog)
const [quickUploadId, setQuickUploadId] = useState<string | null>(null);
const handleFileDrop = useCallback((file: File) => {
const allowed = ["image/jpeg", "image/png", "image/webp", "image/gif", "application/pdf"];
if (!allowed.includes(file.type)) {
setUploadError("Nur PDF, JPG, PNG, WebP oder GIF erlaubt.");
return;
}
if (file.size > 10 * 1024 * 1024) {
setUploadError("Datei zu groß (max. 10 MB).");
return;
}
setUploadError(null);
setPendingFile(file);
}, []);
async function handleQuickUpload(buchungId: string, file: File) {
const allowed = ["image/jpeg", "image/png", "image/webp", "image/gif", "application/pdf"];
if (!allowed.includes(file.type) || file.size > 10 * 1024 * 1024) return;
setQuickUploadId(buchungId);
try {
const fd = new FormData();
fd.append("file", file);
const res = await fetch(`/api/einnahmen/${buchungId}/upload`, { method: "POST", body: fd });
if (res.ok) {
await loadYear(year);
revalidate();
}
} finally {
setQuickUploadId(null);
}
}
const [dialogOpen, setDialogOpen] = useState(false); const [dialogOpen, setDialogOpen] = useState(false);
const [editingId, setEditingId] = useState<string | null>(null); const [editingId, setEditingId] = useState<string | null>(null);
@@ -134,18 +200,23 @@ export default function EinnahmenPage() {
zahlungsart: ((e.zahlungsart as string) || "BANK") as "KASSE" | "BANK", zahlungsart: ((e.zahlungsart as string) || "BANK") as "KASSE" | "BANK",
datum: e.date as string, datum: e.date as string,
beschreibung: (e.description as string | null) ?? null, beschreibung: (e.description as string | null) ?? null,
belegUrl: (e.belegUrl as string | null) ?? null,
}))); })));
setLoadingYear(false); setLoadingYear(false);
} }
function openCreate() { function openCreate() {
setEditingId(null); setEditingId(null);
setPendingFile(null);
setUploadError(null);
setForm({ ...emptyForm, datum: `${year}-01-01`, kategorie: kategorien[0] ?? "" }); setForm({ ...emptyForm, datum: `${year}-01-01`, kategorie: kategorien[0] ?? "" });
setDialogOpen(true); setDialogOpen(true);
} }
function openEdit(e: Einnahme) { function openEdit(e: Einnahme) {
setEditingId(e.id); setEditingId(e.id);
setPendingFile(null);
setUploadError(null);
setForm({ setForm({
kategorie: e.kategorie, kategorie: e.kategorie,
betrag: String(e.betrag), betrag: String(e.betrag),
@@ -153,12 +224,14 @@ export default function EinnahmenPage() {
zahlungsart: e.zahlungsart, zahlungsart: e.zahlungsart,
datum: e.datum.slice(0, 10), datum: e.datum.slice(0, 10),
beschreibung: e.beschreibung ?? "", beschreibung: e.beschreibung ?? "",
belegUrl: e.belegUrl ?? "",
}); });
setDialogOpen(true); setDialogOpen(true);
} }
async function handleSave() { async function handleSave() {
setSaving(true); setSaving(true);
setUploadError(null);
const payload = { const payload = {
kategorie: form.kategorie, kategorie: form.kategorie,
betrag: parseFloat(form.betrag), betrag: parseFloat(form.betrag),
@@ -166,29 +239,59 @@ export default function EinnahmenPage() {
zahlungsart: form.zahlungsart, zahlungsart: form.zahlungsart,
datum: form.datum, datum: form.datum,
beschreibung: form.beschreibung || undefined, beschreibung: form.beschreibung || undefined,
belegUrl: form.belegUrl || undefined,
}; };
try { try {
let savedId: string;
if (editingId) { if (editingId) {
await fetch(`/api/einnahmen/${editingId}`, { const res = await fetch(`/api/einnahmen/${editingId}`, {
method: "PUT", method: "PUT",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
if (!res.ok) throw new Error("Speichern fehlgeschlagen.");
savedId = editingId;
} else { } else {
await fetch("/api/einnahmen", { const res = await fetch("/api/einnahmen", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ...payload, companyId }), body: JSON.stringify({ ...payload, companyId }),
}); });
if (!res.ok) throw new Error("Erstellen fehlgeschlagen.");
const created = await res.json() as { id?: string };
savedId = created.id ?? "";
} }
// Upload pending file after entry is saved
if (pendingFile && savedId) {
setUploadingBeleg(true);
const fd = new FormData();
fd.append("file", pendingFile);
const upRes = await fetch(`/api/einnahmen/${savedId}/upload`, { method: "POST", body: fd });
if (!upRes.ok) {
const err = await upRes.json().catch(() => ({ error: "Upload fehlgeschlagen." })) as { error?: string };
throw new Error(err.error ?? "Upload fehlgeschlagen.");
}
setPendingFile(null);
}
setDialogOpen(false); setDialogOpen(false);
await loadYear(year); await loadYear(year);
revalidate(); revalidate();
} catch (e) {
setUploadError(e instanceof Error ? e.message : "Unbekannter Fehler.");
} finally { } finally {
setSaving(false); setSaving(false);
setUploadingBeleg(false);
} }
} }
async function handleDeleteBeleg(id: string) {
await fetch(`/api/einnahmen/${id}/upload`, { method: "DELETE" });
await loadYear(year);
revalidate();
}
async function handleDelete(id: string) { async function handleDelete(id: string) {
if (!confirm("Eintrag wirklich löschen?")) return; if (!confirm("Eintrag wirklich löschen?")) return;
setDeleting(id); setDeleting(id);
@@ -243,6 +346,33 @@ export default function EinnahmenPage() {
<p className="text-gray-500 mt-1">{companyName} · {year}</p> <p className="text-gray-500 mt-1">{companyName} · {year}</p>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{/* View toggle */}
<div className="flex rounded-lg border border-gray-200 overflow-hidden">
<button
onClick={() => setView("liste")}
className={`flex items-center gap-1.5 px-3 py-2 text-sm font-medium transition-colors ${
view === "liste"
? "bg-emerald-600 text-white"
: "bg-white text-gray-500 hover:bg-gray-50"
}`}
title="Listenansicht"
>
<List className="h-4 w-4" />
Liste
</button>
<button
onClick={() => setView("pivot")}
className={`flex items-center gap-1.5 px-3 py-2 text-sm font-medium transition-colors border-l border-gray-200 ${
view === "pivot"
? "bg-emerald-600 text-white"
: "bg-white text-gray-500 hover:bg-gray-50"
}`}
title="Übersicht"
>
<LayoutGrid className="h-4 w-4" />
Übersicht
</button>
</div>
<select <select
value={year} value={year}
onChange={(e) => loadYear(Number(e.target.value))} onChange={(e) => loadYear(Number(e.target.value))}
@@ -297,7 +427,7 @@ export default function EinnahmenPage() {
</Card> </Card>
</div> </div>
{/* Pivottabelle */} {/* Pivottabelle / Listenansicht */}
{loadingYear ? ( {loadingYear ? (
<div className="flex items-center justify-center py-16 text-gray-400"> <div className="flex items-center justify-center py-16 text-gray-400">
<Loader2 className="h-6 w-6 animate-spin mr-2" /> <Loader2 className="h-6 w-6 animate-spin mr-2" />
@@ -313,6 +443,147 @@ export default function EinnahmenPage() {
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
) : view === "liste" ? (
/* ── LISTENANSICHT ─────────────────────────────────────── */
<Card>
<div className="overflow-x-auto">
<table className="w-full text-sm border-collapse">
<thead>
<tr className="border-b border-slate-200 bg-slate-50">
<th className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Datum</th>
<th className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Kategorie</th>
<th className="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wide">Notiz</th>
<th className="px-3 py-2.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wide">Brutto</th>
<th className="px-3 py-2.5 text-center text-xs font-semibold text-slate-500 uppercase tracking-wide">MwSt.</th>
<th className="px-3 py-2.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wide">Netto</th>
<th className="px-3 py-2.5 text-center text-xs font-semibold text-slate-500 uppercase tracking-wide">Zahlung</th>
<th className="px-3 py-2.5 text-center text-xs font-semibold text-slate-500 uppercase tracking-wide">
<span className="inline-flex items-center gap-1"><Paperclip className="h-3 w-3" />Beleg</span>
</th>
<th className="px-3 py-2.5 w-20" />
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{[...einnahmen].sort((a, b) => b.datum.localeCompare(a.datum)).map((e) => {
const rate = e.steuersatz / 100;
const netto = rate > 0 ? Math.round((e.betrag / (1 + rate)) * 100) / 100 : e.betrag;
return (
<tr key={e.id} className="hover:bg-slate-50/60 group">
<td className="px-4 py-2.5 text-slate-600 whitespace-nowrap">
{new Date(e.datum).toLocaleDateString("de-DE")}
</td>
<td className="px-4 py-2.5 text-slate-700 font-medium whitespace-nowrap">
{e.kategorie}
</td>
<td className="px-4 py-2.5 text-slate-400 text-xs truncate max-w-[14rem]">
{e.beschreibung ?? <span className="text-slate-300"></span>}
</td>
<td className="px-3 py-2.5 text-right font-medium text-emerald-700 whitespace-nowrap">
{formatCurrency(e.betrag)}
</td>
<td className="px-3 py-2.5 text-center">
{e.steuersatz > 0 ? (
<Badge variant="secondary">{e.steuersatz} %</Badge>
) : (
<span className="text-slate-300 text-xs"></span>
)}
</td>
<td className="px-3 py-2.5 text-right text-slate-600 whitespace-nowrap">
{formatCurrency(netto)}
</td>
<td className="px-3 py-2.5 text-center">
{e.zahlungsart === "BANK" ? (
<span className="inline-flex items-center gap-1 text-xs text-blue-600 font-medium">
<Landmark className="h-3 w-3" /> Bank
</span>
) : (
<span className="inline-flex items-center gap-1 text-xs text-amber-600 font-medium">
<Banknote className="h-3 w-3" /> Kasse
</span>
)}
</td>
<td className="px-3 py-2.5 text-center">
{e.belegUrl ? (
<div className="inline-flex items-center gap-1">
<a
href={belegHref(e.belegUrl) ?? "#"}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs text-emerald-600 hover:text-emerald-800 font-medium max-w-[8rem] truncate"
title={e.belegUrl}
>
<FileText className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">{belegDisplayName(e.belegUrl)}</span>
</a>
</div>
) : quickUploadId === e.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin text-emerald-500 mx-auto" />
) : (
<label
htmlFor={`quick-upload-${e.id}`}
className="inline-flex items-center gap-1 text-xs text-slate-300 hover:text-emerald-600 transition-colors cursor-pointer"
title="Beleg hochladen"
>
<Paperclip className="h-3.5 w-3.5" />
<input
id={`quick-upload-${e.id}`}
type="file"
accept=".pdf,.jpg,.jpeg,.png,.webp,.gif,application/pdf,image/*"
className="hidden"
onChange={(ev) => {
const file = ev.target.files?.[0];
if (file) handleQuickUpload(e.id, file);
ev.target.value = "";
}}
/>
</label>
)}
</td>
<td className="px-3 py-2.5">
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity justify-end">
<button
onClick={() => openEdit(e)}
className="p-1 rounded hover:bg-slate-100 text-slate-500 hover:text-slate-700"
title="Bearbeiten"
>
<Pencil className="h-3.5 w-3.5" />
</button>
<button
onClick={() => handleDelete(e.id)}
disabled={deleting === e.id}
className="p-1 rounded hover:bg-red-50 text-slate-400 hover:text-red-600"
title="Löschen"
>
{deleting === e.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</button>
</div>
</td>
</tr>
);
})}
</tbody>
<tfoot>
<tr className="border-t-2 border-slate-300 bg-slate-50">
<td colSpan={3} className="px-4 py-2.5 text-xs font-bold text-slate-700">
Gesamt ({einnahmen.length} Einträge)
</td>
<td className="px-3 py-2.5 text-right text-xs font-bold text-emerald-600 whitespace-nowrap">
{formatCurrency(gesamt)}
</td>
<td />
<td className="px-3 py-2.5 text-right text-xs font-bold text-slate-600 whitespace-nowrap">
{formatCurrency(gesamt - ustGesamt)}
</td>
<td colSpan={3} />
</tr>
</tfoot>
</table>
</div>
</Card>
) : ( ) : (
<Card> <Card>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
@@ -600,17 +871,110 @@ export default function EinnahmenPage() {
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500" className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500"
/> />
</div> </div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
<span className="inline-flex items-center gap-1.5">
<Paperclip className="h-3.5 w-3.5" />
Beleg
</span>
</label>
{/* Pending file preview */}
{pendingFile ? (
<div className="flex items-center gap-3 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2.5 text-sm">
<FileText className="h-5 w-5 text-emerald-600 shrink-0" />
<div className="flex-1 min-w-0">
<p className="font-medium text-emerald-800 truncate">{pendingFile.name}</p>
<p className="text-xs text-emerald-600">{(pendingFile.size / 1024).toFixed(0)} KB</p>
</div>
<button
type="button"
onClick={() => setPendingFile(null)}
className="shrink-0 rounded-full p-0.5 hover:bg-emerald-100 text-emerald-500 hover:text-emerald-700"
title="Entfernen"
>
<X className="h-4 w-4" />
</button>
</div>
) : form.belegUrl ? (
/* Existing uploaded beleg */
<div className="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2.5 text-sm">
<FileText className="h-5 w-5 text-gray-500 shrink-0" />
<div className="flex-1 min-w-0">
<a
href={belegHref(form.belegUrl) ?? "#"}
target="_blank"
rel="noopener noreferrer"
className="font-medium text-emerald-600 hover:text-emerald-800 truncate block"
title={form.belegUrl}
>
{belegDisplayName(form.belegUrl)}
</a>
<p className="text-xs text-gray-400">Vorhandener Beleg · neuen hochladen zum Ersetzen</p>
</div>
<button
type="button"
onClick={() => setForm((f) => ({ ...f, belegUrl: "" }))}
className="shrink-0 rounded-full p-0.5 hover:bg-gray-100 text-gray-400 hover:text-red-500"
title="Beleg entfernen"
>
<X className="h-4 w-4" />
</button>
</div>
) : null}
{/* Drag & drop zone — always shown so user can replace/add */}
{!pendingFile && (
<label
htmlFor="beleg-file-input"
onDragOver={(ev) => { ev.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={(ev) => {
ev.preventDefault();
setDragOver(false);
const file = ev.dataTransfer.files[0];
if (file) handleFileDrop(file);
}}
className={`flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed px-4 py-6 cursor-pointer transition-colors select-none mt-2
${dragOver ? "border-emerald-400 bg-emerald-50 text-emerald-700" : "border-gray-200 hover:border-emerald-300 hover:bg-gray-50 text-gray-400"}`}
>
<Upload className="h-6 w-6" />
<p className="text-sm font-medium">
{form.belegUrl ? "Anderen Beleg hochladen" : "Datei hier ablegen oder klicken"}
</p>
<p className="text-xs">PDF, JPG, PNG, WebP, GIF · max. 10 MB</p>
</label>
)}
{uploadError && (
<p className="mt-1.5 text-xs text-red-600 font-medium">{uploadError}</p>
)}
<input
id="beleg-file-input"
ref={fileInputRef}
type="file"
accept=".pdf,.jpg,.jpeg,.png,.webp,.gif,application/pdf,image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileDrop(file);
e.target.value = "";
}}
/>
</div>
</div> </div>
<div className="flex justify-end gap-2 pt-2"> <div className="flex justify-end gap-2 pt-2">
<Button variant="outline" onClick={() => setDialogOpen(false)}>Abbrechen</Button> <Button variant="outline" onClick={() => setDialogOpen(false)}>Abbrechen</Button>
<Button <Button
onClick={handleSave} onClick={handleSave}
disabled={saving || !formValid} disabled={saving || uploadingBeleg || !formValid}
className="bg-emerald-600 hover:bg-emerald-700" className="bg-emerald-600 hover:bg-emerald-700"
> >
{saving && <Loader2 className="h-4 w-4 animate-spin" />} {(saving || uploadingBeleg) && <Loader2 className="h-4 w-4 animate-spin" />}
{editingId ? "Speichern" : "Hinzufügen"} {uploadingBeleg ? "Beleg wird hochgeladen…" : editingId ? "Speichern" : "Hinzufügen"}
</Button> </Button>
</div> </div>
</DialogContent> </DialogContent>
+1
View File
@@ -115,6 +115,7 @@ model Buchung {
steuersatz Int? // Tax rate: 0, 7, 19 (nullable for non-business records) steuersatz Int? // Tax rate: 0, 7, 19 (nullable for non-business records)
zahlungsart Zahlungsart? // KASSE or BANK zahlungsart Zahlungsart? // KASSE or BANK
isBusinessRecord Boolean @default(false) // True if this is from Einnahme/Ausgabe isBusinessRecord Boolean @default(false) // True if this is from Einnahme/Ausgabe
belegUrl String? @db.Text // Optional receipt/document reference URL
linkedBuchungId String? linkedBuchungId String?
linkedBuchung Buchung? @relation("BuchungLink", fields: [linkedBuchungId], references: [id], onDelete: SetNull) linkedBuchung Buchung? @relation("BuchungLink", fields: [linkedBuchungId], references: [id], onDelete: SetNull)
linkedFrom Buchung[] @relation("BuchungLink") linkedFrom Buchung[] @relation("BuchungLink")