Change for Agrar
All checks were successful
Build and Push Docker Images / build-backend (push) Successful in 32s
Build and Push Docker Images / build-frontend (push) Successful in 1m10s

This commit is contained in:
2026-01-26 22:04:27 +01:00
parent c56fcfbd14
commit 2aed851224
3 changed files with 72 additions and 124 deletions

View File

@@ -1,40 +1,19 @@
import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify';
import { publicLinkService } from '../../modules/publiclinks.service';
import dayjs from 'dayjs'; // Falls nicht installiert: npm install dayjs
export default async function publiclinksNonAuthenticatedRoutes(server: FastifyInstance) {
server.get("/workflows/context/:token", async (req, reply) => {
const { token } = req.params as { token: string };
// Wir lesen die PIN aus dem Header (Best Practice für Security)
const pin = req.headers['x-public-pin'] as string | undefined;
try {
const context = await publicLinkService.getLinkContext(server, token, pin);
return reply.send(context);
} catch (error: any) {
// Spezifische Fehlercodes für das Frontend
if (error.message === "Link_NotFound") {
return reply.code(404).send({ error: "Link nicht gefunden oder abgelaufen" });
}
if (error.message === "Pin_Required") {
return reply.code(401).send({
error: "PIN erforderlich",
code: "PIN_REQUIRED",
requirePin: true
});
}
if (error.message === "Pin_Invalid") {
return reply.code(403).send({
error: "PIN falsch",
code: "PIN_INVALID",
requirePin: true
});
}
if (error.message === "Link_NotFound") return reply.code(404).send({ error: "Link nicht gefunden" });
if (error.message === "Pin_Required") return reply.code(401).send({ error: "PIN erforderlich", requirePin: true });
if (error.message === "Pin_Invalid") return reply.code(403).send({ error: "PIN falsch", requirePin: true });
server.log.error(error);
return reply.code(500).send({ error: "Interner Server Fehler" });
@@ -43,49 +22,42 @@ export default async function publiclinksNonAuthenticatedRoutes(server: FastifyI
server.post("/workflows/submit/:token", async (req, reply) => {
const { token } = req.params as { token: string };
// PIN sicher aus dem Header lesen
const pin = req.headers['x-public-pin'] as string | undefined;
// Der Body enthält { profile, project, service, ... }
const payload = req.body;
console.log(payload)
// Payload vom Frontend (enthält nun 'quantity' statt 'startDate/endDate')
const body = req.body as any;
try {
// Service aufrufen (führt die 3 Schritte aus: Lieferschein -> Zeit -> History)
/**
* TRANSFORMATION
* Wenn das Backend weiterhin Zeiträume erwartet, bauen wir diese hier:
* Wir nehmen 'jetzt' als Ende und rechnen die 'quantity' (Stunden) zurück.
*/
const quantity = parseFloat(body.quantity) || 0;
const payload = {
...body,
// Wir generieren Start/Ende, damit der Service kompatibel bleibt
endDate: new Date(),
startDate: dayjs().subtract(quantity, 'hour').toDate()
};
// Service aufrufen
const result = await publicLinkService.submitFormData(server, token, payload, pin);
// 201 Created zurückgeben
return reply.code(201).send(result);
} catch (error: any) {
console.log(error);
server.log.error(error);
// Fehler-Mapping für saubere HTTP Codes
if (error.message === "Link_NotFound") {
return reply.code(404).send({ error: "Link ungültig oder nicht aktiv" });
}
if (error.message === "Link_NotFound") return reply.code(404).send({ error: "Link ungültig" });
if (error.message === "Pin_Required") return reply.code(401).send({ error: "PIN erforderlich" });
if (error.message === "Pin_Invalid") return reply.code(403).send({ error: "PIN ist falsch" });
if (error.message === "Profile_Missing") return reply.code(400).send({ error: "Profil fehlt" });
if (error.message === "Pin_Required") {
return reply.code(401).send({ error: "PIN erforderlich" });
}
if (error.message === "Pin_Invalid") {
return reply.code(403).send({ error: "PIN ist falsch" });
}
if (error.message === "Profile_Missing") {
return reply.code(400).send({ error: "Kein Mitarbeiter-Profil gefunden (weder im Link noch in der Eingabe)" });
}
if (error.message === "Project not found" || error.message === "Service not found") {
return reply.code(400).send({ error: "Ausgewähltes Projekt oder Leistung existiert nicht mehr." });
}
// Fallback für alle anderen Fehler (z.B. DB Constraints)
return reply.code(500).send({
error: "Interner Fehler beim Speichern",
error: "Fehler beim Speichern",
details: error.message
});
}
});
}
}

View File

@@ -1,6 +1,4 @@
<script setup>
import dayjs from 'dayjs'
const props = defineProps({
context: { type: Object, required: true },
token: { type: String, required: true },
@@ -8,23 +6,18 @@ const props = defineProps({
})
const runtimeConfig = useRuntimeConfig()
const emit = defineEmits(['success'])
const { $api } = useNuxtApp()
const toast = useToast()
const config = computed(() => props.context.config)
const data = computed(() => props.context.data)
// Initiale Werte setzen
// Initiale Werte setzen (Quantity statt Start/EndDate)
const form = ref({
profile: props.context.meta?.defaultProfileId || null,
project: null,
service: config.value?.defaults?.serviceId || null,
// Wenn manualTime erlaubt, setze Startzeit auf jetzt, sonst null (wird im Backend gesetzt)
startDate: config.value?.features?.timeTracking?.allowManualTime ? new Date() : null,
endDate: config.value?.features?.timeTracking?.allowManualTime ? dayjs().add(1, 'hour').toDate() : null,
quantity: config.value?.features?.timeTracking?.defaultDurationHours || 1,
dieselUsage: 0,
description: ''
})
@@ -32,13 +25,11 @@ const form = ref({
const isSubmitting = ref(false)
const errors = ref({})
// Validierung basierend auf JSON Config
const validate = () => {
errors.value = {}
let isValid = true
const validationRules = config.value.validation || {}
// Standard-Validierung
if (!form.value.project && data.value.projects?.length > 0) {
errors.value.project = 'Pflichtfeld'
isValid = false
@@ -49,13 +40,11 @@ const validate = () => {
isValid = false
}
// Profil nur validieren, wenn Auswahl möglich ist
if (!form.value.profile && data.value.profiles?.length > 0 && !props.context.meta.defaultProfileId) {
errors.value.profile = 'Bitte Mitarbeiter wählen'
if (!form.value.quantity || form.value.quantity <= 0) {
errors.value.quantity = 'Menge erforderlich'
isValid = false
}
// Feature: Agriculture
if (config.value.features?.agriculture?.showDieselUsage && validationRules.requireDiesel) {
if (!form.value.dieselUsage || form.value.dieselUsage <= 0) {
errors.value.diesel = 'Dieselverbrauch erforderlich'
@@ -72,12 +61,9 @@ const submit = async () => {
isSubmitting.value = true
try {
const payload = { ...form.value }
// Headers vorbereiten (PIN mitsenden!)
const headers = {}
if (props.pin) headers['x-public-pin'] = props.pin
// An den Submit-Endpunkt senden (den müssen wir im Backend noch bauen!)
await $fetch(`${runtimeConfig.public.apiBase}/workflows/submit/${props.token}`, {
method: 'POST',
body: payload,
@@ -104,7 +90,6 @@ const submit = async () => {
</template>
<div class="space-y-5">
<UFormGroup
v-if="!context?.meta?.defaultProfileId && data?.profiles?.length > 0"
label="Mitarbeiter"
@@ -118,7 +103,6 @@ const submit = async () => {
value-attribute="id"
placeholder="Name auswählen..."
searchable
searchable-placeholder="Suchen..."
/>
</UFormGroup>
@@ -135,7 +119,6 @@ const submit = async () => {
value-attribute="id"
placeholder="Wählen..."
searchable
searchable-placeholder="Suchen..."
/>
</UFormGroup>
@@ -152,37 +135,29 @@ const submit = async () => {
value-attribute="id"
placeholder="Wählen..."
searchable
searchable-placeholder="Suchen..."
/>
</UFormGroup>
<div v-if="config?.features?.timeTracking?.allowManualTime" class="grid grid-cols-2 gap-3">
<UFormGroup label="Start">
<input
type="datetime-local"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
:value="dayjs(form.startDate).format('YYYY-MM-DDTHH:mm')"
@input="e => form.startDate = new Date(e.target.value)"
/>
</UFormGroup>
<UFormGroup label="Dauer (Stunden)">
<input
type="number"
step="0.25"
placeholder="z.B. 1.5"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
@input="e => form.endDate = dayjs(form.startDate).add(parseFloat(e.target.value), 'hour').toDate()"
/>
</UFormGroup>
<UFormGroup label="Ende" class="col-span-2">
<input
type="datetime-local"
class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
:value="dayjs(form.endDate).format('YYYY-MM-DDTHH:mm')"
@input="e => form.endDate = new Date(e.target.value)"
/>
</UFormGroup>
</div>
<UFormGroup
v-if="config?.features?.timeTracking?.allowManualTime"
label="Menge / Dauer"
:error="errors.quantity"
required
>
<UInput
v-model="form.quantity"
type="number"
step="0.25"
size="lg"
placeholder="0.00"
>
<template #trailing>
<span class="text-gray-500 text-sm pr-2">
{{ data?.units?.[0]?.symbol || 'h' }}
</span>
</template>
</UInput>
</UFormGroup>
<UFormGroup
v-if="config?.features?.agriculture?.showDieselUsage"
@@ -200,7 +175,6 @@ const submit = async () => {
<UFormGroup :label="config?.ui?.labels?.description || 'Notiz'">
<UTextarea v-model="form.description" :rows="3" />
</UFormGroup>
</div>
<template #footer>

View File

@@ -1,22 +1,21 @@
<script setup>
definePageMeta({
layout: 'blank', // Kein Menü, keine Sidebar
middleware: [], // Keine Auth-Checks durch Nuxt
auth: false // Falls du das nuxt-auth Modul nutzt
layout: 'blank',
middleware: [],
auth: false
})
const config = useRuntimeConfig()
const route = useRoute()
const token = route.params.token
const { $api } = useNuxtApp() // Dein Fetch-Wrapper
const toast = useToast()
// States
const status = ref('loading') // loading, pin_required, ready, error, success
const pin = ref('')
const context = ref(null)
const errorMsg = ref('')
// Daten laden
// Hilfs-Key um die Form-Komponente bei Reset komplett neu zu initialisieren
const formKey = ref(0)
const loadContext = async () => {
status.value = 'loading'
errorMsg.value = ''
@@ -25,19 +24,16 @@ const loadContext = async () => {
const headers = {}
if (pin.value) headers['x-public-pin'] = pin.value
// Abruf an dein Fastify Backend
// Pfad evtl. anpassen, wenn du Proxy nutzt
const res = await $fetch(`${config.public.apiBase}/workflows/context/${token}`, { headers })
context.value = res
status.value = 'ready'
} catch (err) {
if (err.statusCode === 401) {
status.value = 'pin_required' // PIN nötig (aber noch keine eingegeben)
} else if (err.statusCode === 403) {
if (err.statusCode === 401 || err.statusCode === 403) {
status.value = 'pin_required'
errorMsg.value = 'Falsche PIN'
pin.value = ''
if (err.statusCode === 403) {
errorMsg.value = 'Falsche PIN'
pin.value = ''
}
} else {
status.value = 'error'
errorMsg.value = 'Link ungültig oder abgelaufen.'
@@ -45,7 +41,6 @@ const loadContext = async () => {
}
}
// Initialer Aufruf
onMounted(() => {
loadContext()
})
@@ -57,6 +52,13 @@ const handlePinSubmit = () => {
const handleFormSuccess = () => {
status.value = 'success'
}
const resetForm = () => {
// PIN wird NICHT geleert
errorMsg.value = ''
formKey.value++ // Erzwingt Neu-Initialisierung der Kind-Komponente
loadContext() // Lädt Daten neu (Status geht auf loading -> ready)
}
</script>
<template>
@@ -83,7 +85,6 @@ const handleFormSuccess = () => {
<h2 class="text-xl font-bold text-gray-900">Geschützter Bereich</h2>
<p class="text-sm text-gray-500">Bitte PIN eingeben</p>
</div>
<form @submit.prevent="handlePinSubmit" class="space-y-4">
<UInput
v-model="pin"
@@ -104,12 +105,13 @@ const handleFormSuccess = () => {
</div>
<h2 class="text-2xl font-bold text-gray-900 mb-2">Gespeichert!</h2>
<p class="text-gray-500 mb-6">Die Daten wurden erfolgreich übertragen.</p>
<UButton variant="outline" @click="() => window.location.reload()">Neuen Eintrag erfassen</UButton>
<UButton variant="outline" @click="resetForm">Neuen Eintrag erfassen</UButton>
</UCard>
<div v-else-if="status === 'ready'" class="w-full max-w-lg">
<PublicDynamicForm
v-if="context && token"
:key="formKey"
:context="context"
:token="token"
:pin="pin"