Refactor: centralize Zod schemas and fully integrate into API routes

Improvements #1-3 deepening:

1. Server-side invoice amount validation
   - All amounts (qty × unitPrice) recalculated server-side using tax.ts
   - Prevents client-side manipulation attacks
   - Supports kleinunternehmer auto-inheritance

2. Comprehensive audit logging
   - LogAction type extended with 11 new actions
   - All CRUD operations now logged with metadata
   - Metadata includes: amounts, counts, status transitions, oldStatus/newStatus

3. Advanced Zod validation (centralized)
   - New file: app/lib/schemas.ts (220 lines, 18+ validators)
   - Custom validators: currencySchema, taxRateSchema, ibanSchema, taxIdSchema, vatIdSchema
   - All API routes (invoices, companies, customers) now use centralized schemas
   - Consistent German error messages
   - Single source of truth for validation logic

Additional improvements:
- DB indices applied: invoices(status, dueDate, deletedAt, customerId), customers(companyId)
- Migration 20260415192953_add_indices applied successfully
- Build succeeds without critical errors
- TypeScript compilation validates all schemas

Files modified:
- app/lib/schemas.ts (NEW)
- app/routes/api.invoices.ts (uses centralized schemas)
- app/routes/api.invoices.$id.ts (status transition validation)
- app/routes/api.companies.ts, api.companies.$id.ts
- app/routes/api.customers.ts, api.customers.$id.ts
- app/lib/logger.server.ts (metadata support)
- prisma/schema.prisma (indices)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
hwinkel
2026-04-15 21:34:38 +02:00
parent 1ffbcf237c
commit f10a79471e
14 changed files with 578 additions and 147 deletions
+3 -13
View File
@@ -1,18 +1,7 @@
import { getApiUser } from "@/session.server";
import prisma from "@/lib/prisma.server";
import { z } from "zod";
const customerSchema = z.object({
companyId: z.string().min(1),
name: z.string().min(1),
taxId: z.string().optional(),
address: z.string().min(1),
zip: z.string().min(1),
city: z.string().min(1),
country: z.string().optional().default("DE"),
email: z.string().email().optional().or(z.literal("")),
phone: z.string().optional(),
});
import { log } from "@/lib/logger.server";
import { customerSchema } from "@/lib/schemas";
export async function action({ request }: { request: Request }) {
const user = await getApiUser(request);
@@ -28,5 +17,6 @@ export async function action({ request }: { request: Request }) {
if (!company) return Response.json({ error: "Company not found" }, { status: 404 });
const customer = await prisma.customer.create({ data: parsed.data });
await log({ userId: user.id, action: "CREATE_CUSTOMER", entity: "Customer", entityId: customer.id, request });
return Response.json(customer, { status: 201 });
}