ADD: fixed e rechnung

This commit is contained in:
hwinkel
2026-03-15 20:58:24 +01:00
parent 5ac9e269e3
commit c6dc22c859
14 changed files with 153 additions and 26 deletions
+21
View File
@@ -0,0 +1,21 @@
import { RateLimiterMemory } from "rate-limiter-flexible";
// Max. 5 Loginversuche pro IP innerhalb von 15 Minuten
const loginLimiter = new RateLimiterMemory({
points: 5,
duration: 60 * 15,
});
export async function checkLoginRateLimit(request: Request): Promise<string | null> {
const ip =
request.headers.get("x-forwarded-for")?.split(",")[0].trim() ??
request.headers.get("x-real-ip") ??
"unknown";
try {
await loginLimiter.consume(ip);
return null;
} catch {
return "Zu viele Loginversuche. Bitte 15 Minuten warten.";
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ export function ErrorBoundary() {
<body style={{ fontFamily: "monospace", padding: "2rem", background: "#fff1f2", color: "#9f1239" }}>
<h1 style={{ fontSize: "1.5rem", fontWeight: 700, marginBottom: "1rem" }}>Fehler</h1>
<pre style={{ whiteSpace: "pre-wrap", wordBreak: "break-word", background: "#ffe4e6", padding: "1rem", borderRadius: "0.5rem" }}>{message}</pre>
{stack && <pre style={{ marginTop: "1rem", fontSize: "0.75rem", color: "#64748b", whiteSpace: "pre-wrap" }}>{stack}</pre>}
{import.meta.env.DEV && stack && <pre style={{ marginTop: "1rem", fontSize: "0.75rem", color: "#64748b", whiteSpace: "pre-wrap" }}>{stack}</pre>}
<Scripts />
</body>
</html>
+3 -1
View File
@@ -1,5 +1,6 @@
import { getApiUser } from "@/session.server";
import prisma from "@/lib/prisma.server";
import { log } from "@/lib/logger.server";
import { z } from "zod";
const companySchema = z.object({
@@ -39,7 +40,8 @@ export async function action({ request, params }: { request: Request; params: {
if (!company) return Response.json({ error: "Not found" }, { status: 404 });
if (request.method === "DELETE") {
await prisma.company.delete({ where: { id: params.id } });
await prisma.company.delete({ where: { id: params.id, userId: user.id } });
await log({ userId: user.id, action: "DELETE_COMPANY", entity: "Company", entityId: params.id, request });
return Response.json({ ok: true });
}
+1 -1
View File
@@ -35,7 +35,7 @@ export async function action({ request, params }: { request: Request; params: {
if (!customer) return Response.json({ error: "Not found" }, { status: 404 });
if (request.method === "DELETE") {
await prisma.customer.delete({ where: { id: params.id } });
await prisma.customer.delete({ where: { id: params.id, company: { userId: user.id } } });
return Response.json({ ok: true });
}
+5 -3
View File
@@ -1,6 +1,7 @@
import { getApiUser } from "@/session.server";
import prisma from "@/lib/prisma.server";
import { generateInvoiceNumber } from "@/lib/invoice-number.server";
import { log } from "@/lib/logger.server";
import { InvoiceStatus } from "@prisma/client";
import { z } from "zod";
@@ -43,9 +44,9 @@ const updateSchema = z.object({
notes: z.string().optional(),
kleinunternehmer: z.boolean().optional().default(false),
items: z.array(itemSchema).min(1),
netTotal: z.number(),
taxTotal: z.number(),
grossTotal: z.number(),
netTotal: z.number().nonnegative(),
taxTotal: z.number().nonnegative(),
grossTotal: z.number().nonnegative(),
});
export async function action({ request, params }: { request: Request; params: { id: string } }) {
@@ -92,6 +93,7 @@ export async function action({ request, params }: { request: Request; params: {
);
}
await prisma.invoice.delete({ where: { id: params.id } });
await log({ userId: user.id, action: "DELETE_INVOICE", entity: "Invoice", entityId: params.id, request });
return Response.json({ ok: true });
}
+51 -3
View File
@@ -35,6 +35,17 @@ export async function loader({ request, params }: { request: Request; params: {
if (!invoice) return Response.json({ error: "Not found" }, { status: 404 });
const missingFields: string[] = [];
if (!invoice.company.email && !invoice.company.phone) {
missingFields.push("Firma: E-Mail oder Telefon (Kontaktdaten, BR-DE-2)");
}
if (missingFields.length > 0) {
return Response.json(
{ error: "Pflichtfelder für E-Rechnung fehlen", missingFields },
{ status: 422 }
);
}
const { zugferd } = await import("node-zugferd");
const { EN16931 } = await import("node-zugferd/profile");
@@ -73,7 +84,8 @@ export async function loader({ request, params }: { request: Request; params: {
rateApplicablePercent: Number(rate),
}));
const lines = invoice.items.map((item) => ({
const lines = invoice.items.map((item, index) => ({
identifier: String(index + 1),
tradeProduct: { name: item.description },
tradeDelivery: {
billedQuantity: {
@@ -95,11 +107,14 @@ export async function loader({ request, params }: { request: Request; params: {
}));
const doc = z.create({
businessProcessType: "urn:fdc:peppol.eu:2017:poacc:billing:01:1.0",
specificationIdentifier: "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0",
number: invoice.number ?? invoice.id,
typeCode: "380",
issueDate: invoice.issueDate,
transaction: {
tradeAgreement: {
buyerReference: invoice.number ?? invoice.id,
seller: {
name: invoice.company.name,
postalAddress: {
@@ -108,6 +123,18 @@ export async function loader({ request, params }: { request: Request; params: {
...(invoice.company.city ? { city: invoice.company.city } : {}),
countryCode: "DE",
},
...(invoice.company.email || invoice.company.phone
? {
tradeContact: {
name: invoice.company.name,
...(invoice.company.email ? { emailAddress: invoice.company.email } : {}),
...(invoice.company.phone ? { phoneNumber: invoice.company.phone } : {}),
},
}
: {}),
...(invoice.company.email
? { electronicAddress: { value: invoice.company.email, schemeIdentifier: "EM" as const } }
: {}),
taxRegistration: {
...(invoice.company.vatId ? { vatIdentifier: invoice.company.vatId } : {}),
...(invoice.company.taxId ? { localIdentifier: invoice.company.taxId } : {}),
@@ -121,6 +148,9 @@ export async function loader({ request, params }: { request: Request; params: {
...(invoice.customer.city ? { city: invoice.customer.city } : {}),
countryCode: "DE",
},
...(invoice.customer.email
? { electronicAddress: { value: invoice.customer.email, schemeIdentifier: "EM" as const } }
: {}),
},
},
tradeDelivery: {
@@ -131,6 +161,18 @@ export async function loader({ request, params }: { request: Request; params: {
tradeSettlement: {
currencyCode: "EUR",
paymentTerms: { dueDate: invoice.dueDate },
...(invoice.company.bankIban
? {
paymentInstruction: {
typeCode: "58" as const,
transfers: [{ paymentAccountIdentifier: invoice.company.bankIban }],
},
}
: {
paymentInstruction: {
typeCode: "ZZZ" as const,
},
}),
vatBreakdown,
monetarySummation: {
lineTotalAmount: netTotal,
@@ -144,9 +186,15 @@ export async function loader({ request, params }: { request: Request; params: {
},
});
const xml = await doc.toXML();
let xml: string;
try {
xml = await doc.toXML() as string;
} catch (err) {
const message = err instanceof Error ? err.message : "Unbekannter Fehler";
return Response.json({ error: `E-Rechnung konnte nicht erstellt werden: ${message}` }, { status: 422 });
}
return new Response(xml as string, {
return new Response(xml, {
status: 200,
headers: {
"Content-Type": "application/xml; charset=utf-8",
+1 -1
View File
@@ -20,7 +20,7 @@ export async function action({ request, params }: { request: Request; params: {
if (!service) return Response.json({ error: "Not found" }, { status: 404 });
if (request.method === "DELETE") {
await prisma.service.delete({ where: { id: params.id } });
await prisma.service.delete({ where: { id: params.id, company: { userId: user.id } } });
return Response.json({ ok: true });
}
@@ -170,7 +170,17 @@ export default function InvoiceDetailPage() {
*/
async function downloadFile(url: string, filename: string) {
const res = await fetch(url);
if (!res.ok) return;
if (!res.ok) {
const contentType = res.headers.get("content-type") ?? "";
if (contentType.includes("application/json")) {
const data = await res.json() as { error?: string; missingFields?: string[] };
const detail = data.missingFields?.length
? `\n\n• ${data.missingFields.join("\n• ")}`
: "";
alert(`${data.error ?? "Fehler"}${detail}`);
}
return;
}
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
@@ -184,6 +194,11 @@ export default function InvoiceDetailPage() {
return downloadFile(`/api/invoices/${invoice.id}/pdf`, `rechnung-${invoice.number ?? invoice.id}.pdf`);
}
const xmlMissingFields: string[] = [];
if (!invoice.company.email && !invoice.company.phone) {
xmlMissingFields.push("E-Mail oder Telefon der Firma fehlt");
}
function downloadXml() {
return downloadFile(`/api/invoices/${invoice.id}/xml`, `rechnung-${invoice.number ?? invoice.id}.xml`);
}
@@ -215,9 +230,20 @@ export default function InvoiceDetailPage() {
<Button variant="outline" size="sm" onClick={downloadPdf}>
<Download className="h-4 w-4" /> PDF
</Button>
<Button variant="outline" size="sm" onClick={downloadXml}>
<Download className="h-4 w-4" /> E-Rechnung
</Button>
<span
title={xmlMissingFields.length > 0 ? `Pflichtfelder fehlen:\n• ${xmlMissingFields.join("\n• ")}` : undefined}
className="inline-flex"
>
<Button
variant="outline"
size="sm"
onClick={downloadXml}
disabled={xmlMissingFields.length > 0}
className={xmlMissingFields.length > 0 ? "pointer-events-none opacity-50" : ""}
>
<Download className="h-4 w-4" /> E-Rechnung
</Button>
</span>
</>
)}
{invoice.status === "DRAFT" && (
+4
View File
@@ -1,5 +1,6 @@
import { Form, useActionData, useNavigation, redirect } from "react-router";
import { login, createUserSession, getUserSession } from "@/session.server";
import { checkLoginRateLimit } from "@/lib/rate-limiter.server";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -13,6 +14,9 @@ export async function loader({ request }: { request: Request }) {
}
export async function action({ request }: { request: Request }) {
const rateLimitError = await checkLoginRateLimit(request);
if (rateLimitError) return { error: rateLimitError };
const formData = await request.formData();
const identifier = formData.get("identifier") as string;
const password = formData.get("password") as string;
+9 -3
View File
@@ -3,15 +3,19 @@ import bcrypt from "bcryptjs";
import prisma from "@/lib/prisma.server";
import { log } from "@/lib/logger.server";
if (!process.env.AUTH_SECRET) {
throw new Error("AUTH_SECRET environment variable is required");
}
const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
maxAge: process.env.NODE_ENV === "development" ? 60 * 60 * 24 * 30 : 60 * 60 * 4,
maxAge: 60 * 60 * 4, // 4 Stunden
path: "/",
sameSite: "lax",
secrets: [process.env.AUTH_SECRET ?? "fallback-secret-change-in-production"],
secure: process.env.SESSION_SECURE === "true",
secrets: [process.env.AUTH_SECRET],
secure: process.env.NODE_ENV === "production",
},
});
@@ -28,6 +32,8 @@ export async function login(
});
if (!user) {
// Dummy-Vergleich verhindert Timing-Angriffe zur Benutzernamen-Enumeration
await bcrypt.compare(password, "$2a$12$dummyhashfortimingattackprevention000000000000000000000");
await log({ action: "LOGIN_FAILED", metadata: { identifier }, request });
return null;
}