major(fullstack): Add dynamic section spawning, removal of app. form create DTOs,

This commit is contained in:
2025-12-15 19:12:00 +01:00
parent 7bacff967e
commit 844ab8661c
47 changed files with 1283 additions and 511 deletions

View File

@@ -1,19 +1,12 @@
import type {
CreateApplicationFormDto,
CreateFormElementDto,
ApplicationFormDto,
PagedApplicationFormDto
} from '~~/.api-client'
import type { ApplicationFormDto, PagedApplicationFormDto, FormElementDto } from '~~/.api-client'
import { useApplicationFormApi } from './useApplicationFormApi'
export function useApplicationForm() {
const applicationFormApi = useApplicationFormApi()
async function createApplicationForm(
createApplicationFormDto: CreateApplicationFormDto
): Promise<ApplicationFormDto> {
async function createApplicationForm(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
try {
return await applicationFormApi.createApplicationForm(createApplicationFormDto)
return await applicationFormApi.createApplicationForm(applicationFormDto)
} catch (e: unknown) {
console.error('Failed creating application form:', e)
return Promise.reject(e)
@@ -46,6 +39,7 @@ export function useApplicationForm() {
return Promise.reject(new Error('ID or application form DTO missing'))
}
console.log('Updating application form with ID:', id, applicationFormDto)
try {
return await applicationFormApi.updateApplicationForm(id, applicationFormDto)
} catch (e: unknown) {
@@ -79,7 +73,7 @@ export function useApplicationForm() {
async function addFormElementToSubSection(
applicationFormId: string,
subsectionId: string,
createFormElementDto: CreateFormElementDto,
formElementDto: FormElementDto,
position: number
): Promise<ApplicationFormDto> {
if (!applicationFormId || !subsectionId) {
@@ -90,7 +84,7 @@ export function useApplicationForm() {
return await applicationFormApi.addFormElementToSubSection(
applicationFormId,
subsectionId,
createFormElementDto,
formElementDto,
position
)
} catch (e: unknown) {

View File

@@ -1,10 +1,9 @@
import {
ApplicationFormApi,
Configuration,
type CreateApplicationFormDto,
type CreateFormElementDto,
type ApplicationFormDto,
type PagedApplicationFormDto
type PagedApplicationFormDto,
type FormElementDto
} from '~~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'
import { wrappedFetchWrap } from '~/utils/wrappedFetch'
@@ -25,10 +24,8 @@ export function useApplicationFormApi() {
new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
)
async function createApplicationForm(
createApplicationFormDto: CreateApplicationFormDto
): Promise<ApplicationFormDto> {
return applicationFormApiClient.createApplicationForm({ createApplicationFormDto })
async function createApplicationForm(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
return applicationFormApiClient.createApplicationForm({ applicationFormDto })
}
async function getAllApplicationForms(organizationId: string): Promise<PagedApplicationFormDto> {
@@ -57,13 +54,13 @@ export function useApplicationFormApi() {
async function addFormElementToSubSection(
applicationFormId: string,
subsectionId: string,
createFormElementDto: CreateFormElementDto,
formElementDto: FormElementDto,
position: number
): Promise<ApplicationFormDto> {
return applicationFormApiClient.addFormElementToSubSection({
applicationFormId,
subsectionId,
createFormElementDto,
formElementDto,
position
})
}

View File

@@ -1,9 +1,4 @@
import {
type CreateApplicationFormDto,
type ApplicationFormDto,
type PagedApplicationFormDto,
ResponseError
} from '~~/.api-client'
import { type ApplicationFormDto, type PagedApplicationFormDto, ResponseError } from '~~/.api-client'
import { useApplicationFormTemplateApi } from './useApplicationFormTemplateApi'
const currentApplicationForm: Ref<ApplicationFormDto | undefined> = ref()
@@ -11,11 +6,9 @@ const currentApplicationForm: Ref<ApplicationFormDto | undefined> = ref()
export async function useApplicationFormTemplate() {
const applicationFormApi = await useApplicationFormTemplateApi()
async function createApplicationFormTemplate(
createApplicationFormDto: CreateApplicationFormDto
): Promise<ApplicationFormDto> {
async function createApplicationFormTemplate(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
try {
currentApplicationForm.value = await applicationFormApi.createApplicationFormTemplate(createApplicationFormDto)
currentApplicationForm.value = await applicationFormApi.createApplicationFormTemplate(applicationFormDto)
return currentApplicationForm.value
} catch (e: unknown) {
if (e instanceof ResponseError) {

View File

@@ -1,5 +1,5 @@
import { ApplicationFormTemplateApi, Configuration } from '../../../.api-client'
import type { CreateApplicationFormDto, ApplicationFormDto, PagedApplicationFormDto } from '~~/.api-client'
import type { ApplicationFormDto, PagedApplicationFormDto } from '~~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'
import { wrappedFetchWrap } from '~/utils/wrappedFetch'
@@ -19,10 +19,8 @@ export async function useApplicationFormTemplateApi() {
new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
)
async function createApplicationFormTemplate(
createApplicationFormDto: CreateApplicationFormDto
): Promise<ApplicationFormDto> {
return applicationFormApiClient.createApplicationFormTemplate({ createApplicationFormDto })
async function createApplicationFormTemplate(applicationFormDto: ApplicationFormDto): Promise<ApplicationFormDto> {
return applicationFormApiClient.createApplicationFormTemplate({ applicationFormDto })
}
async function getAllApplicationFormTemplates(): Promise<PagedApplicationFormDto> {

View File

@@ -7,3 +7,5 @@ export { useNotification } from './notification/useNotification'
export { useNotificationApi } from './notification/useNotificationApi'
export { useUser } from './user/useUser'
export { useUserApi } from './user/useUserApi'
export { useSectionSpawning } from './useSectionSpawning'
export { useClonableElements } from './useClonableElements'

View File

@@ -19,8 +19,10 @@ export function useApplicationFormValidator() {
): Map<FormElementId, ComplianceStatus> {
formElementComplianceMap.value.clear()
formElements.forEach((formElement) => {
if (visibilityMap && visibilityMap.get(formElement.id) === false) {
formElements.forEach((formElement, index) => {
const elementKey = formElement.id || formElement.reference || `element-${index}`
if (visibilityMap && visibilityMap.get(elementKey) === false) {
return
}
@@ -49,15 +51,15 @@ export function useApplicationFormValidator() {
const currentHighestComplianceStatusPos =
Object.values(ComplianceStatus).indexOf(currentHighestComplianceStatus)
if (formElementComplianceMap.value.has(formElement.id)) {
const newComplianceStatus = formElementComplianceMap.value.get(formElement.id)!
if (formElementComplianceMap.value.has(elementKey)) {
const newComplianceStatus = formElementComplianceMap.value.get(elementKey)!
const newComplianceStatusPos = Object.values(ComplianceStatus).indexOf(newComplianceStatus)
if (newComplianceStatusPos > currentHighestComplianceStatusPos) {
formElementComplianceMap.value.set(formElement.id, newComplianceStatus)
formElementComplianceMap.value.set(elementKey, newComplianceStatus)
}
} else {
formElementComplianceMap.value.set(formElement.id, currentHighestComplianceStatus)
formElementComplianceMap.value.set(elementKey, currentHighestComplianceStatus)
}
})
})

View File

@@ -0,0 +1,48 @@
import type { FormElementDto } from '~~/.api-client'
export function useClonableElements() {
function cloneElement(element: FormElementDto, existingElements: FormElementDto[]): FormElementDto {
const newReference = element.reference ? generateNextReference(existingElements, element.reference) : undefined
const isTextField = element.type === 'TEXTAREA' || element.type === 'TEXTFIELD'
const clonedElement = JSON.parse(JSON.stringify(element)) as FormElementDto
const resetOptions = clonedElement.options.map((option) => ({
...option,
value: isTextField ? '' : option.value
}))
return {
...clonedElement,
id: undefined,
formElementSubSectionId: undefined,
reference: newReference,
options: resetOptions
}
}
function generateNextReference(existingElements: FormElementDto[], baseReference: string): string {
const { base } = extractReferenceBase(baseReference)
const existingSuffixes = existingElements
.filter((el) => el.reference && el.reference.startsWith(base))
.map((el) => {
const { suffix } = extractReferenceBase(el.reference!)
return suffix
})
const maxSuffix = existingSuffixes.length > 0 ? Math.max(...existingSuffixes) : 0
return `${base}_${maxSuffix + 1}`
}
function extractReferenceBase(reference: string): { base: string; suffix: number } {
const match = reference.match(/^(.+?)_(\d+)$/)
if (match && match[1] && match[2]) {
return { base: match[1], suffix: parseInt(match[2], 10) }
}
return { base: reference, suffix: 1 }
}
return {
cloneElement
}
}

View File

@@ -1,15 +1,15 @@
import type { ApplicationFormDto, CreateFormElementDto, FormElementDto } from '~~/.api-client'
import type { FormElementDto } from '~~/.api-client'
export function useFormElementManagement() {
const applicationForm = useApplicationForm()
function addInputFormElement(elements: FormElementDto[], position: number): FormElementDto[] {
const inputFormElement = createInputFormElement()
const updatedElements = [...elements]
updatedElements.splice(position + 1, 0, inputFormElement)
return updatedElements
}
async function addFormElementToSubSection(
applicationFormId: string | undefined,
subsectionId: string,
formElements: FormElementDto[],
position: number
): Promise<ApplicationFormDto | undefined> {
const inputFormElement: CreateFormElementDto = {
function createInputFormElement(): FormElementDto {
return {
title: 'Formular ergänzen',
description: 'Bitte fügen Sie hier Ihre Ergänzungen ein.',
options: [
@@ -22,27 +22,9 @@ export function useFormElementManagement() {
],
type: 'TITLE_BODY_TEXTFIELDS'
}
if (applicationFormId) {
try {
return await applicationForm.addFormElementToSubSection(
applicationFormId,
subsectionId,
inputFormElement,
position + 1
)
} catch (error) {
console.error('Failed to add form element:', error)
throw error
}
} else {
// @ts-expect-error Add CreateFormElementDto to formElements array. ID will be generated by the backend.
formElements.splice(position + 1, 0, inputFormElement)
return undefined
}
}
return {
addFormElementToSubSection
addInputFormElement
}
}

View File

@@ -8,7 +8,10 @@ export function useFormElementVisibility() {
allFormElements.forEach((element) => {
const isVisible = isElementVisible(element, formElementsByRef, visibilityMap)
visibilityMap.set(element.id, isVisible)
const key = element.id || element.reference
if (key) {
visibilityMap.set(key, isVisible)
}
})
return visibilityMap
@@ -42,10 +45,10 @@ export function useFormElementVisibility() {
const sourceValue = getFormElementValue(sourceElement)
const operator = condition.operator || VCOperator.Equals
const conditionMet = evaluateCondition(sourceValue, condition.expectedValue, operator)
const operator = condition.formElementOperator || VCOperator.Equals
const conditionMet = evaluateCondition(sourceValue, condition.formElementExpectedValue, operator)
return condition.conditionType === VCType.Show ? conditionMet : !conditionMet
return condition.formElementConditionType === VCType.Show ? conditionMet : !conditionMet
}
function getFormElementValue(element: FormElementDto): string {

View File

@@ -20,9 +20,11 @@ export function useFormStepper(
const sections = computed(() => toValue(formElementSections) ?? [])
const visibleSections = computed(() => sections.value.filter((section) => !section.isTemplate))
const stepperItems = computed(() => {
const items: StepperItem[] = []
sections.value.forEach((section: FormElementSectionDto) => {
visibleSections.value.forEach((section: FormElementSectionDto) => {
items.push({
title: section.shortTitle,
description: section.description
@@ -32,7 +34,7 @@ export function useFormStepper(
})
const currentFormElementSection = computed<FormElementSectionDto | undefined>(
() => sections.value[activeStepperItemIndex.value]
() => visibleSections.value[activeStepperItemIndex.value]
)
async function navigateStepper(direction: 'forward' | 'backward') {

View File

@@ -0,0 +1,197 @@
import type { FormElementDto, FormElementSectionDto, SectionSpawnTriggerDto } from '~~/.api-client'
import { VisibilityConditionOperator, VisibilityConditionType } from '~~/.api-client'
export function useSectionSpawning() {
function processSpawnTriggers(
sections: FormElementSectionDto[],
updatedFormElements: FormElementDto[]
): FormElementSectionDto[] {
let resultSections = sections
for (const formElement of updatedFormElements) {
if (!formElement.sectionSpawnTrigger || !formElement.reference) {
continue
}
// Extract trigger configuration and current element value
const trigger = formElement.sectionSpawnTrigger
const triggerValue = getFormElementValue(formElement)
const shouldSpawn = shouldSpawnSection(trigger, triggerValue)
// Use resultSections to check for existing spawned sections (in case multiple spawns happen)
const existingSpawnedSections = getSpawnedSectionsForElement(resultSections, formElement.reference)
// Handle three spawn states:
// 1. Condition met but no section spawned yet → create new section
if (shouldSpawn && existingSpawnedSections.length === 0) {
resultSections = spawnNewSection(resultSections, formElement, trigger, triggerValue)
}
// 2. Condition no longer met but section exists → remove spawned section
else if (!shouldSpawn && existingSpawnedSections.length > 0) {
resultSections = removeSpawnedSections(resultSections, formElement.reference)
}
// 3. Condition still met and section exists → update section titles if value changed
else if (shouldSpawn && existingSpawnedSections.length > 0 && triggerValue) {
resultSections = updateSpawnedSectionTitles(resultSections, formElement.reference, trigger, triggerValue)
}
}
return resultSections
}
function spawnNewSection(
sections: FormElementSectionDto[],
element: FormElementDto,
trigger: SectionSpawnTriggerDto,
triggerValue: string
): FormElementSectionDto[] {
const templateSection = findTemplateSection(sections, trigger.templateReference)
if (!templateSection) {
return sections
}
const newSection = spawnSectionFromTemplate(templateSection, element.reference!, triggerValue)
return sections.concat(newSection as FormElementSectionDto)
}
function updateSpawnedSectionTitles(
sections: FormElementSectionDto[],
elementReference: string,
trigger: SectionSpawnTriggerDto,
triggerValue: string
): FormElementSectionDto[] {
const template = findTemplateSection(sections, trigger.templateReference)
if (!template) {
return sections
}
const hasTitleTemplate = template.titleTemplate
const hasShortTitleTemplate = template.shortTitle?.includes('{{triggerValue}}')
const hasDescriptionTemplate = template.description?.includes('{{triggerValue}}')
if (!hasTitleTemplate && !hasShortTitleTemplate && !hasDescriptionTemplate) {
return sections
}
return sections.map((section) => {
if (section.spawnedFromElementReference === elementReference && !section.isTemplate) {
const sectionUpdate: Partial<FormElementSectionDto> = {}
if (hasTitleTemplate) {
sectionUpdate.title = interpolateTitle(template.titleTemplate!, triggerValue)
}
if (hasShortTitleTemplate && template.shortTitle) {
sectionUpdate.shortTitle = interpolateTitle(template.shortTitle, triggerValue)
}
if (hasDescriptionTemplate && template.description) {
sectionUpdate.description = interpolateTitle(template.description, triggerValue)
}
return { ...section, ...sectionUpdate }
}
return section
})
}
function removeSpawnedSections(sections: FormElementSectionDto[], elementReference: string): FormElementSectionDto[] {
return sections.filter((section) => section.spawnedFromElementReference !== elementReference || section.isTemplate)
}
function spawnSectionFromTemplate(
templateSection: FormElementSectionDto,
triggerElementReference: string,
triggerValue: string
): FormElementSectionDto {
const clonedSection = JSON.parse(JSON.stringify(templateSection)) as FormElementSectionDto
const title = templateSection.titleTemplate
? interpolateTitle(templateSection.titleTemplate, triggerValue)
: templateSection.title
const shortTitle = templateSection.shortTitle?.includes('{{triggerValue}}')
? interpolateTitle(templateSection.shortTitle, triggerValue)
: templateSection.shortTitle
const description = templateSection.description?.includes('{{triggerValue}}')
? interpolateTitle(templateSection.description, triggerValue)
: templateSection.description
return {
...clonedSection,
id: undefined,
applicationFormId: undefined,
title,
shortTitle,
description,
isTemplate: false,
spawnedFromElementReference: triggerElementReference,
formElementSubSections: clonedSection.formElementSubSections.map((subsection) => ({
...subsection,
id: undefined,
formElementSectionId: undefined,
formElements: subsection.formElements.map((element) => ({
...element,
id: undefined,
formElementSubSectionId: undefined
}))
}))
}
}
function shouldSpawnSection(trigger: SectionSpawnTriggerDto, triggerElementValue: string): boolean {
const operator = trigger.sectionSpawnOperator || VisibilityConditionOperator.Equals
const isConditionMet = evaluateCondition(triggerElementValue, trigger.sectionSpawnExpectedValue || '', operator)
return trigger.sectionSpawnConditionType === VisibilityConditionType.Show ? isConditionMet : !isConditionMet
}
function getSpawnedSectionsForElement(
sections: FormElementSectionDto[],
elementReference: string
): FormElementSectionDto[] {
return sections.filter((section) => !section.isTemplate && section.spawnedFromElementReference === elementReference)
}
function findTemplateSection(
sections: FormElementSectionDto[],
templateReference: string
): FormElementSectionDto | undefined {
return sections.find((section) => section.isTemplate && section.templateReference === templateReference)
}
function evaluateCondition(
actualValue: string,
expectedValue: string,
operator: VisibilityConditionOperator
): boolean {
switch (operator) {
case VisibilityConditionOperator.Equals:
return actualValue.toLowerCase() === expectedValue.toLowerCase()
case VisibilityConditionOperator.NotEquals:
return actualValue.toLowerCase() !== expectedValue.toLowerCase()
case VisibilityConditionOperator.IsEmpty:
return actualValue === ''
case VisibilityConditionOperator.IsNotEmpty:
return actualValue !== ''
default:
return false
}
}
function interpolateTitle(titleTemplate: string, triggerValue: string): string {
return titleTemplate.replace(/\{\{triggerValue\}\}/g, triggerValue)
}
function getFormElementValue(element: FormElementDto): string {
if (element.type === 'TEXTAREA' || element.type === 'TEXTFIELD') {
return element.options[0]?.value || ''
}
const selectedOption = element.options.find((option) => option.value === 'true')
return selectedOption?.label || ''
}
return {
processSpawnTriggers
}
}

View File

@@ -14,9 +14,7 @@ export function useUserApi() {
)
)
const userApiClient = new UserApi(
new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
)
const userApiClient = new UserApi(new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) }))
async function getUserById(id: string): Promise<UserDto> {
return userApiClient.getUserById({ id })
@@ -39,4 +37,3 @@ export function useUserApi() {
deleteUser
}
}