import { UUidWithPrefix } from "#components/Ausweis/types.js"; import { VALID_UUID_PREFIXES } from "#lib/constants.js"; import { generatePrefixedId } from "#lib/db.js"; import { authorizationHeaders, authorizationMiddleware } from "#lib/middleware/authorization.js"; import { prisma } from "#lib/server/prisma.js"; import { APIError, defineApiRoute } from "astro-typesafe-api/server"; import { GEGNachweisWohnenSchema } from "src/generated/zod/gegnachweiswohnen.js"; import { z } from "zod"; export const PUT = defineApiRoute({ meta: { contentTypes: ["application/json"], description: "Erstellt einen neuen GEG Nachweis für Wohngebäude.", tags: ["GEG Nachweis", "Verbrauchsausweis Wohnen"], }, input: z.object({ nachweis: GEGNachweisWohnenSchema.omit({ id: true, benutzer_id: true, geg_einpreisung_id: true, aufnahme_id: true, bestellt: true, created_at: true, rechnung_id: true, storniert: true, updated_at: true, zurueckgestellt: true, ausweisart: true }), aufnahme_id: UUidWithPrefix }), output: z.object({ id: UUidWithPrefix, objekt_id: UUidWithPrefix, aufnahme_id: UUidWithPrefix, }), headers: authorizationHeaders, middleware: authorizationMiddleware, async fetch(input, ctx, user) { const aufnahme = await prisma.aufnahme.findUnique({ where: { id: input.aufnahme_id } }) if (!aufnahme || aufnahme.benutzer_id !== user.id) { throw new APIError({ code: "FORBIDDEN", message: "Aufnahme konnte nicht gefunden werden oder gehört nicht zu diesem Benutzer." }) } const id = generatePrefixedId(9, VALID_UUID_PREFIXES.GEGNachweisWohnen) const nachweis = await prisma.gEGNachweisWohnen.create({ data: { id, ...input.nachweis, benutzer: { connect: { id: user.id, }, }, aufnahme: { connect: { id: aufnahme.id, }, } }, select: { id: true, aufnahme: { select: { id: true, objekt: { select: { id: true, }, }, }, }, }, }); return { id: nachweis.id, objekt_id: nachweis.aufnahme.objekt.id, aufnahme_id: nachweis.aufnahme.id, }; }, }); export const GET = defineApiRoute({ meta: { description: "Gibt eine spezifische GEG Nachweis Anfrage des Benutzers zurück.", tags: ["GEG Nachweis"], headers: { Authorization: { description: "Ein gültiger Authentifizierungstoken", required: true, allowEmptyValue: false, examples: { Bearer: { value: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", }, }, }, }, }, headers: authorizationHeaders, middleware: authorizationMiddleware, async fetch(input, context, user) { const { id } = context.params; const nachweis = await prisma.gEGNachweisGewerbe.findUnique({ where: { id, }, include: { benutzer: true, aufnahme: { include: { events: { include: { benutzer: { select: { id: true, }, }, }, orderBy: { date: "asc", }, }, }, }, }, }); if ( !nachweis || (nachweis.benutzer_id !== null && nachweis.benutzer_id !== user.id) ) { // Falls wir den Ausweis nicht finden können, werfen wir einen Fehler throw new APIError({ code: "NOT_FOUND", message: "GEG Nachweis konnte nicht gefunden werden.", }); } return nachweis; }, });