myCRM/assets/js/views/ContactManagement_old.vue.backup
olli 47b7099ba6 feat: Implement reusable CrudDataTable component for contact management
- Created a new CrudDataTable.vue component to handle data display and interactions.
- Integrated column configuration, filtering, and sorting functionalities.
- Added support for dynamic column visibility and order persistence using localStorage.
- Enhanced data loading with error handling and user feedback via toast notifications.
- Updated ContactManagement_old.vue to utilize the new CrudDataTable component, improving code organization and maintainability.
2025-11-10 10:06:10 +01:00

1066 lines
36 KiB
Plaintext

<template>
<div class="contact-management">
<div class="card">
<div class="flex justify-between items-center mb-4">
<div class="font-semibold text-xl">Kontakte</div>
<div class="flex gap-2">
<Button
label="Spalten anpassen"
icon="pi pi-cog"
outlined
@click="columnConfigDialog = true"
/>
<Button label="Neuer Kontakt" icon="pi pi-plus" @click="openNewContactDialog" />
</div>
</div>
<DataTable
v-model:filters="filters"
:value="contacts"
:loading="loading"
:paginator="true"
:rows="10"
:rowsPerPageOptions="[10, 25, 50, 100]"
:rowHover="true"
:globalFilterFields="['companyName', 'city', 'email', 'phone']"
sortField="companyName"
:sortOrder="1"
dataKey="id"
filterDisplay="menu"
showGridlines
scrollable
scrollHeight="flex"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
currentPageReportTemplate="Zeige {first} bis {last} von {totalRecords} Einträgen"
>
<template #header>
<div class="flex justify-between flex-wrap gap-2">
<div class="flex gap-2">
<Button
label="Alle"
:outlined="typeFilter !== 'all'"
@click="filterByType('all')"
size="small"
/>
<Button
label="Debitoren"
:outlined="typeFilter !== 'debtor'"
@click="filterByType('debtor')"
size="small"
/>
<Button
label="Kreditoren"
:outlined="typeFilter !== 'creditor'"
@click="filterByType('creditor')"
size="small"
/>
</div>
<IconField>
<InputIcon>
<i class="pi pi-search" />
</InputIcon>
<InputText
v-model="filters['global'].value"
placeholder="Suchen..."
/>
</IconField>
</div>
</template>
<template #empty>Keine Kontakte gefunden.</template>
<template #loading>Lade Kontakte. Bitte warten...</template>
<template v-for="column in availableColumns" :key="column.key">
<!-- Firma -->
<Column v-if="column.key === 'companyName' && visibleColumns.companyName" field="companyName" header="Firma" sortable style="min-width: 200px">
<template #body="{ data }">
<div class="font-semibold">{{ data.companyName }}</div>
</template>
<template #filter="{ filterModel }">
<InputText v-model="filterModel.value" type="text" placeholder="Suche nach Firma" />
</template>
</Column>
<!-- Kundennummer -->
<Column v-if="column.key === 'companyNumber' && visibleColumns.companyNumber" field="companyNumber" header="Kundennummer" sortable style="min-width: 130px">
<template #body="{ data }">
<div class="text-500">{{ data.companyNumber }}</div>
</template>
</Column>
<!-- Straße -->
<Column v-if="column.key === 'street' && visibleColumns.street" field="street" header="Straße" style="min-width: 200px">
<template #body="{ data }">
{{ data.street }}
</template>
</Column>
<!-- PLZ -->
<Column v-if="column.key === 'zipCode' && visibleColumns.zipCode" field="zipCode" header="PLZ" sortable style="min-width: 100px">
<template #body="{ data }">
{{ data.zipCode }}
</template>
</Column>
<!-- Ort -->
<Column v-if="column.key === 'city' && visibleColumns.city" field="city" header="Ort" sortable style="min-width: 150px">
<template #body="{ data }">
{{ data.city }}
</template>
<template #filter="{ filterModel }">
<InputText v-model="filterModel.value" type="text" placeholder="Suche nach Ort" />
</template>
</Column>
<!-- Land -->
<Column v-if="column.key === 'country' && visibleColumns.country" field="country" header="Land" sortable style="min-width: 120px">
<template #body="{ data }">
{{ data.country }}
</template>
</Column>
<!-- Ansprechpartner -->
<Column v-if="column.key === 'contactPersons' && visibleColumns.contactPersons" header="Ansprechpartner" style="min-width: 200px">
<template #body="{ data }">
<div v-if="data.contactPersons && data.contactPersons.length > 0">
<div
v-for="person in data.contactPersons.slice(0, 2)"
:key="person.id"
class="mb-1"
>
<div class="font-medium">
{{ person.firstName }} {{ person.lastName }}
<Tag v-if="person.isPrimary" value="Primär" severity="info" class="ml-1" />
</div>
<div class="text-sm text-500" v-if="person.email">
{{ person.email }}
</div>
</div>
</div>
<span v-else class="text-500">Keine Ansprechpartner</span>
</template>
</Column>
<!-- Telefon -->
<Column v-if="column.key === 'phone' && visibleColumns.phone" header="Telefon" style="min-width: 150px">
<template #body="{ data }">
<div v-if="data.phone">
<i class="pi pi-phone mr-1"></i>
{{ data.phone }}
</div>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- Fax -->
<Column v-if="column.key === 'fax' && visibleColumns.fax" header="Fax" style="min-width: 150px">
<template #body="{ data }">
<div v-if="data.fax">
<i class="pi pi-print mr-1"></i>
{{ data.fax }}
</div>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- E-Mail -->
<Column v-if="column.key === 'email' && visibleColumns.email" header="E-Mail" style="min-width: 200px">
<template #body="{ data }">
<div v-if="data.email">
<a :href="'mailto:' + data.email" class="text-primary">
<i class="pi pi-envelope mr-1"></i>
{{ data.email }}
</a>
</div>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- Website -->
<Column v-if="column.key === 'website' && visibleColumns.website" header="Website" style="min-width: 200px">
<template #body="{ data }">
<div v-if="data.website">
<a :href="data.website" target="_blank" class="text-primary">
<i class="pi pi-globe mr-1"></i>
{{ data.website }}
</a>
</div>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- Steuernummer -->
<Column v-if="column.key === 'taxNumber' && visibleColumns.taxNumber" header="Steuernummer" style="min-width: 150px">
<template #body="{ data }">
<span v-if="data.taxNumber">{{ data.taxNumber }}</span>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- USt-IdNr. -->
<Column v-if="column.key === 'vatNumber' && visibleColumns.vatNumber" header="USt-IdNr." style="min-width: 150px">
<template #body="{ data }">
<span v-if="data.vatNumber">{{ data.vatNumber }}</span>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- Typ -->
<Column v-if="column.key === 'type' && visibleColumns.type" header="Typ" style="min-width: 130px">
<template #body="{ data }">
<div class="flex gap-1">
<Tag v-if="data.isDebtor" value="Debitor" severity="success" />
<Tag v-if="data.isCreditor" value="Kreditor" severity="warning" />
</div>
</template>
</Column>
<!-- Notizen -->
<Column v-if="column.key === 'notes' && visibleColumns.notes" header="Notizen" style="min-width: 200px">
<template #body="{ data }">
<span v-if="data.notes" class="text-500">{{ data.notes.substring(0, 50) }}{{ data.notes.length > 50 ? '...' : '' }}</span>
<span v-else class="text-500">---</span>
</template>
</Column>
<!-- Erstellt am -->
<Column v-if="column.key === 'createdAt' && visibleColumns.createdAt" header="Erstellt am" sortable style="min-width: 150px">
<template #body="{ data }">
<span v-if="data.createdAt">{{ new Date(data.createdAt).toLocaleDateString('de-DE') }}</span>
</template>
</Column>
<!-- Zuletzt geändert -->
<Column v-if="column.key === 'updatedAt' && visibleColumns.updatedAt" header="Zuletzt geändert" sortable style="min-width: 150px">
<template #body="{ data }">
<span v-if="data.updatedAt">{{ new Date(data.updatedAt).toLocaleDateString('de-DE') }}</span>
</template>
</Column>
<!-- Status -->
<Column v-if="column.key === 'status' && visibleColumns.status" field="isActive" header="Status" dataType="boolean" style="min-width: 100px">
<template #body="{ data }">
<Tag
:value="data.isActive ? 'Aktiv' : 'Inaktiv'"
:severity="data.isActive ? 'success' : 'danger'"
/>
</template>
<template #filter="{ filterModel }">
<Select
v-model="filterModel.value"
:options="statusOptions"
optionLabel="label"
optionValue="value"
placeholder="Status wählen"
showClear
>
<template #option="slotProps">
<Tag :value="slotProps.option.label" :severity="slotProps.option.value ? 'success' : 'danger'" />
</template>
</Select>
</template>
</Column>
</template>
<Column :exportable="false" style="min-width: 120px">
<template #body="{ data }">
<div class="flex gap-2">
<Button
icon="pi pi-pencil"
outlined
rounded
@click="editContact(data)"
size="small"
/>
<Button
icon="pi pi-trash"
outlined
rounded
severity="danger"
@click="confirmDelete(data)"
size="small"
/>
</div>
</template>
</Column>
</DataTable>
</div>
<!-- Contact Dialog -->
<Dialog
v-model:visible="contactDialog"
:header="editingContact?.id ? 'Kontakt bearbeiten' : 'Neuer Kontakt'"
:modal="true"
:style="{ width: '1200px', maxHeight: '90vh' }"
:closable="true"
>
<div v-if="editingContact">
<!-- Basisdaten -->
<Card class="mb-3">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-building text-primary"></i>
<span>Basisdaten</span>
</div>
</template>
<template #content>
<div class="flex flex-col gap-4">
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full md:w-2/3">
<label for="companyName">Firmenname <span class="text-red-500">*</span></label>
<InputText
id="companyName"
v-model="editingContact.companyName"
:invalid="submitted && !editingContact.companyName"
/>
<small v-if="submitted && !editingContact.companyName" class="text-red-500">
Firmenname ist erforderlich
</small>
</div>
<div class="flex flex-col gap-2 w-full md:w-1/3">
<label for="companyNumber">Kundennummer</label>
<InputText id="companyNumber" v-model="editingContact.companyNumber" />
</div>
</div>
<div class="flex gap-4">
<div class="flex items-center gap-2">
<Checkbox inputId="isDebtor" v-model="editingContact.isDebtor" :binary="true" />
<label for="isDebtor">Debitor</label>
</div>
<div class="flex items-center gap-2">
<Checkbox inputId="isCreditor" v-model="editingContact.isCreditor" :binary="true" />
<label for="isCreditor">Kreditor</label>
</div>
<div class="flex items-center gap-2">
<Checkbox inputId="isActive" v-model="editingContact.isActive" :binary="true" />
<label for="isActive">Aktiv</label>
</div>
</div>
</div>
</template>
</Card>
<!-- Adresse -->
<Card class="mb-3">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-map-marker text-primary"></i>
<span>Adresse</span>
</div>
</template>
<template #content>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-2">
<label for="street">Straße</label>
<InputText id="street" v-model="editingContact.street" />
</div>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label for="zipCode">PLZ</label>
<InputText id="zipCode" v-model="editingContact.zipCode" />
</div>
<div class="flex flex-col gap-2 w-full md:w-1/2">
<label for="city">Ort</label>
<InputText id="city" v-model="editingContact.city" />
</div>
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label for="country">Land</label>
<InputText id="country" v-model="editingContact.country" />
</div>
</div>
</div>
</template>
</Card>
<!-- Kontaktdaten -->
<Card class="mb-3">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-phone text-primary"></i>
<span>Kontaktdaten</span>
</div>
</template>
<template #content>
<div class="flex flex-col gap-4">
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full">
<label for="phone">Telefon</label>
<InputText id="phone" v-model="editingContact.phone" />
</div>
<div class="flex flex-col gap-2 w-full">
<label for="fax">Fax</label>
<InputText id="fax" v-model="editingContact.fax" />
</div>
</div>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full">
<label for="email">E-Mail</label>
<InputText id="email" v-model="editingContact.email" type="email" />
</div>
<div class="flex flex-col gap-2 w-full">
<label for="website">Website</label>
<InputText id="website" v-model="editingContact.website" />
</div>
</div>
</div>
</template>
</Card>
<!-- Steuerdaten -->
<Card class="mb-3">
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-calculator text-primary"></i>
<span>Steuerdaten</span>
</div>
</template>
<template #content>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full">
<label for="taxNumber">Steuernummer</label>
<InputText id="taxNumber" v-model="editingContact.taxNumber" />
</div>
<div class="flex flex-col gap-2 w-full">
<label for="vatNumber">USt-IdNr.</label>
<InputText id="vatNumber" v-model="editingContact.vatNumber" />
</div>
</div>
</template>
</Card>
<!-- Ansprechpartner -->
<Card class="mb-3">
<template #title>
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<i class="pi pi-users text-primary"></i>
<span>Ansprechpartner</span>
</div>
<Button
label="Hinzufügen"
icon="pi pi-plus"
size="small"
outlined
@click="addContactPerson"
:disabled="editingContact.contactPersons.length >= 2"
/>
</div>
</template>
<template #content>
<div v-if="editingContact.contactPersons.length === 0" class="text-center py-4 text-500">
<i class="pi pi-user-plus text-4xl mb-3"></i>
<p>Noch keine Ansprechpartner hinzugefügt</p>
</div>
<div
v-for="(person, index) in editingContact.contactPersons"
:key="index"
class="mb-4"
>
<Divider v-if="index > 0" />
<div class="flex flex-col gap-4">
<div class="flex justify-between items-center mb-3">
<h4 class="m-0 font-semibold">
<i class="pi pi-user mr-2"></i>
Ansprechpartner {{ index + 1 }}
<Tag v-if="person.isPrimary" value="Primär" severity="info" class="ml-2" />
</h4>
<Button
icon="pi pi-trash"
text
rounded
severity="danger"
@click="removeContactPerson(index)"
size="small"
/>
</div>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label :for="'salutation-' + index">Anrede</label>
<Dropdown
:id="'salutation-' + index"
v-model="person.salutation"
:options="salutations"
placeholder="Wählen..."
/>
</div>
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label :for="'title-' + index">Titel</label>
<InputText :id="'title-' + index" v-model="person.title" />
</div>
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label :for="'firstName-' + index">
Vorname <span class="text-red-500">*</span>
</label>
<InputText
:id="'firstName-' + index"
v-model="person.firstName"
:invalid="submitted && !person.firstName"
/>
</div>
<div class="flex flex-col gap-2 w-full md:w-1/4">
<label :for="'lastName-' + index">
Nachname <span class="text-red-500">*</span>
</label>
<InputText
:id="'lastName-' + index"
v-model="person.lastName"
:invalid="submitted && !person.lastName"
/>
</div>
</div>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full">
<label :for="'position-' + index">Position</label>
<InputText :id="'position-' + index" v-model="person.position" />
</div>
<div class="flex flex-col gap-2 w-full">
<label :for="'department-' + index">Abteilung</label>
<InputText :id="'department-' + index" v-model="person.department" />
</div>
</div>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex flex-col gap-2 w-full">
<label :for="'personPhone-' + index">Telefon</label>
<InputText :id="'personPhone-' + index" v-model="person.phone" />
</div>
<div class="flex flex-col gap-2 w-full">
<label :for="'mobile-' + index">Mobil</label>
<InputText :id="'mobile-' + index" v-model="person.mobile" />
</div>
<div class="flex flex-col gap-2 w-full">
<label :for="'personEmail-' + index">E-Mail</label>
<InputText
:id="'personEmail-' + index"
v-model="person.email"
type="email"
/>
</div>
</div>
<div class="flex items-center gap-2">
<Checkbox
:inputId="'isPrimary-' + index"
v-model="person.isPrimary"
:binary="true"
/>
<label :for="'isPrimary-' + index">Hauptansprechpartner</label>
</div>
</div>
</div>
</template>
</Card>
<!-- Notizen -->
<Card>
<template #title>
<div class="flex items-center gap-2">
<i class="pi pi-comment text-primary"></i>
<span>Notizen</span>
</div>
</template>
<template #content>
<div class="flex flex-col gap-2">
<label for="notes">Interne Notizen zu diesem Kontakt</label>
<Textarea
id="notes"
v-model="editingContact.notes"
:rows="4"
placeholder="Interne Notizen..."
/>
</div>
</template>
</Card>
</div>
<template #footer>
<Button label="Abbrechen" outlined @click="hideDialog" />
<Button label="Speichern" @click="saveContact" :loading="saving" />
</template>
</Dialog>
<!-- Delete Confirmation -->
<Dialog
v-model:visible="deleteDialog"
header="Bestätigung"
:modal="true"
:style="{ width: '450px' }"
>
<div class="flex align-items-center">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem; color: var(--red-500)"></i>
<span v-if="editingContact">
Möchten Sie den Kontakt <b>{{ editingContact.companyName }}</b> wirklich löschen?
</span>
</div>
<template #footer>
<Button label="Nein" outlined @click="deleteDialog = false" />
<Button label="Ja" severity="danger" @click="deleteContact" :loading="deleting" />
</template>
</Dialog>
<!-- Column Configuration Dialog -->
<Dialog
v-model:visible="columnConfigDialog"
header="Spalten anpassen"
:modal="true"
:style="{ width: '600px' }"
>
<div class="flex flex-col gap-3">
<p class="text-500 mb-2">Wählen Sie die anzuzeigenden Spalten aus und ziehen Sie sie, um die Reihenfolge zu ändern:</p>
<div class="flex flex-col gap-2">
<div
v-for="(column, index) in availableColumns"
:key="column.key"
class="flex items-center gap-2 p-3 border rounded-md hover-row cursor-move"
draggable="true"
@dragstart="onDragStart(index)"
@dragover.prevent
@drop="onDrop(index)"
>
<i class="pi pi-bars text-500"></i>
<Checkbox
:inputId="'col-' + column.key"
v-model="visibleColumns[column.key]"
:binary="true"
/>
<label :for="'col-' + column.key" class="cursor-pointer flex-1">{{ column.label }}</label>
</div>
</div>
</div>
<template #footer>
<Button label="Abbrechen" outlined @click="columnConfigDialog = false" />
<Button label="Speichern" @click="saveColumnConfig" />
</template>
</Dialog>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
import { FilterMatchMode, FilterOperator } from '@primevue/core/api'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Textarea from 'primevue/textarea'
import Dialog from 'primevue/dialog'
import Card from 'primevue/card'
import Tag from 'primevue/tag'
import Checkbox from 'primevue/checkbox'
import Dropdown from 'primevue/dropdown'
import Divider from 'primevue/divider'
import IconField from 'primevue/iconfield'
import InputIcon from 'primevue/inputicon'
import Select from 'primevue/select'
const toast = useToast()
const contacts = ref([])
const loading = ref(false)
const contactDialog = ref(false)
const deleteDialog = ref(false)
const columnConfigDialog = ref(false)
const editingContact = ref(null)
const submitted = ref(false)
const saving = ref(false)
const deleting = ref(false)
const typeFilter = ref('all')
// Available columns configuration - default order
const defaultColumns = [
{ key: 'companyName', label: 'Firma' },
{ key: 'companyNumber', label: 'Kundennummer' },
{ key: 'city', label: 'Ort' },
{ key: 'street', label: 'Straße' },
{ key: 'zipCode', label: 'PLZ' },
{ key: 'country', label: 'Land' },
{ key: 'contactPersons', label: 'Ansprechpartner' },
{ key: 'phone', label: 'Telefon' },
{ key: 'fax', label: 'Fax' },
{ key: 'email', label: 'E-Mail' },
{ key: 'website', label: 'Website' },
{ key: 'taxNumber', label: 'Steuernummer' },
{ key: 'vatNumber', label: 'USt-IdNr.' },
{ key: 'type', label: 'Typ (Debitor/Kreditor)' },
{ key: 'status', label: 'Status' },
{ key: 'notes', label: 'Notizen' },
{ key: 'createdAt', label: 'Erstellt am' },
{ key: 'updatedAt', label: 'Zuletzt geändert' }
]
// Load visible columns from localStorage or use defaults
const loadColumnConfig = () => {
const saved = localStorage.getItem('contactTableColumns')
if (saved) {
const config = JSON.parse(saved)
// Handle old format (just visibility object)
if (!config.visibility) {
return config
}
// Apply saved order
if (config.order) {
const orderedColumns = []
config.order.forEach(key => {
const column = defaultColumns.find(col => col.key === key)
if (column) orderedColumns.push(column)
})
// Add any new columns that weren't in saved order
defaultColumns.forEach(col => {
if (!orderedColumns.find(c => c.key === col.key)) {
orderedColumns.push(col)
}
})
availableColumns.value = orderedColumns
}
return config.visibility
}
// Default: all columns visible
return {
companyName: true,
companyNumber: false,
city: true,
street: false,
zipCode: false,
country: false,
contactPersons: true,
phone: true,
fax: false,
email: true,
website: true,
taxNumber: false,
vatNumber: false,
type: true,
status: true,
notes: false,
createdAt: false,
updatedAt: false
}
}
const availableColumns = ref([...defaultColumns])
const visibleColumns = ref(loadColumnConfig())
// Drag and drop for column reordering
let draggedIndex = null
const onDragStart = (index) => {
draggedIndex = index
}
const onDrop = (dropIndex) => {
if (draggedIndex === null || draggedIndex === dropIndex) return
const columns = [...availableColumns.value]
const draggedItem = columns[draggedIndex]
columns.splice(draggedIndex, 1)
columns.splice(dropIndex, 0, draggedItem)
availableColumns.value = columns
draggedIndex = null
}
const saveColumnConfig = () => {
// Save both visibility and order
const config = {
visibility: visibleColumns.value,
order: availableColumns.value.map(col => col.key)
}
localStorage.setItem('contactTableColumns', JSON.stringify(config))
columnConfigDialog.value = false
toast.add({
severity: 'success',
summary: 'Gespeichert',
detail: 'Spaltenkonfiguration wurde gespeichert',
life: 3000
})
}
const filters = ref({
global: { value: null, matchMode: FilterMatchMode.CONTAINS },
companyName: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
city: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
isActive: { value: null, matchMode: FilterMatchMode.EQUALS }
})
const salutations = ref(['Herr', 'Frau', 'Divers'])
const statusOptions = ref([
{ label: 'Aktiv', value: true },
{ label: 'Inaktiv', value: false }
])
const typeOptions = ref(['Debitor', 'Kreditor'])
const emptyContact = () => ({
companyName: '',
companyNumber: '',
street: '',
zipCode: '',
city: '',
country: 'Deutschland',
phone: '',
fax: '',
email: '',
website: '',
taxNumber: '',
vatNumber: '',
isDebtor: false,
isCreditor: false,
isActive: true,
notes: '',
contactPersons: []
})
const emptyContactPerson = () => ({
salutation: null,
title: '',
firstName: '',
lastName: '',
position: '',
department: '',
phone: '',
mobile: '',
email: '',
isPrimary: false
})
onMounted(() => {
loadContacts()
})
const loadContacts = async () => {
loading.value = true
try {
// Alle Kontakte laden - API Platform unterstützt itemsPerPage Parameter
let url = '/api/contacts'
const params = new URLSearchParams()
// Große Anzahl setzen, um alle Kontakte zu erhalten
params.append('itemsPerPage', '5000')
if (typeFilter.value === 'debtor') {
params.append('isDebtor', 'true')
} else if (typeFilter.value === 'creditor') {
params.append('isCreditor', 'true')
}
url += '?' + params.toString()
const response = await fetch(url, {
credentials: 'include'
})
if (!response.ok) throw new Error('Fehler beim Laden der Kontakte')
const data = await response.json()
// API Platform gibt hydra:member zurück
contacts.value = data['hydra:member'] || data.member || []
} catch (error) {
console.error('Error loading contacts:', error)
toast.add({
severity: 'error',
summary: 'Fehler',
detail: 'Kontakte konnten nicht geladen werden',
life: 3000
})
} finally {
loading.value = false
}
}
const filterByType = (type) => {
typeFilter.value = type
loadContacts()
}
const openNewContactDialog = () => {
editingContact.value = emptyContact()
submitted.value = false
contactDialog.value = true
}
const editContact = (contact) => {
editingContact.value = { ...contact }
// Ensure contactPersons is initialized
if (!editingContact.value.contactPersons) {
editingContact.value.contactPersons = []
}
submitted.value = false
contactDialog.value = true
}
const hideDialog = () => {
contactDialog.value = false
submitted.value = false
editingContact.value = null
}
const addContactPerson = () => {
if (editingContact.value.contactPersons.length < 2) {
editingContact.value.contactPersons.push(emptyContactPerson())
}
}
const removeContactPerson = (index) => {
editingContact.value.contactPersons.splice(index, 1)
}
const validateContact = () => {
if (!editingContact.value.companyName) {
return false
}
// Validate contact persons
for (const person of editingContact.value.contactPersons) {
if (!person.firstName || !person.lastName) {
return false
}
}
return true
}
const saveContact = async () => {
submitted.value = true
if (!validateContact()) {
toast.add({
severity: 'warn',
summary: 'Validierung fehlgeschlagen',
detail: 'Bitte füllen Sie alle Pflichtfelder aus',
life: 3000
})
return
}
saving.value = true
try {
const url = editingContact.value.id
? `/api/contacts/${editingContact.value.id}`
: '/api/contacts'
const method = editingContact.value.id ? 'PUT' : 'POST'
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(editingContact.value)
})
if (!response.ok) {
const error = await response.json()
// API Platform liefert Validierungsfehler in 'violations' Array
if (error.violations && error.violations.length > 0) {
const errorMessages = error.violations
.map(v => `${v.propertyPath}: ${v.message}`)
.join('\n')
throw new Error(errorMessages)
}
// Fallback für andere Fehlerformate
throw new Error(error['hydra:description'] || error.message || error.detail || 'Fehler beim Speichern')
}
toast.add({
severity: 'success',
summary: 'Erfolg',
detail: 'Kontakt wurde gespeichert',
life: 3000
})
hideDialog()
loadContacts()
} catch (error) {
console.error('Error saving contact:', error)
toast.add({
severity: 'error',
summary: 'Fehler',
detail: error.message || 'Kontakt konnte nicht gespeichert werden',
life: 5000
})
} finally {
saving.value = false
}
}
const confirmDelete = (contact) => {
editingContact.value = contact
deleteDialog.value = true
}
const deleteContact = async () => {
deleting.value = true
try {
const response = await fetch(`/api/contacts/${editingContact.value.id}`, {
method: 'DELETE',
credentials: 'include'
})
if (!response.ok) throw new Error('Fehler beim Löschen')
toast.add({
severity: 'success',
summary: 'Erfolg',
detail: 'Kontakt wurde gelöscht',
life: 3000
})
deleteDialog.value = false
editingContact.value = null
loadContacts()
} catch (error) {
console.error('Error deleting contact:', error)
toast.add({
severity: 'error',
summary: 'Fehler',
detail: 'Kontakt konnte nicht gelöscht werden',
life: 3000
})
} finally {
deleting.value = false
}
}
</script>
<style scoped>
.contact-management {
padding: 1rem;
}
.p-invalid {
border-color: var(--red-500);
}
.p-error {
color: var(--red-500);
font-size: 0.875rem;
}
</style>