import { config } from '../config.js' function getPrimaryContact(client) { const contacts = client?.contacts || [] return contacts.find((c) => c.is_primary) || contacts[0] || {} } export function sanitizeInvoiceClient(client) { const contact = getPrimaryContact(client) const baseUrl = config.invoiceNinja.url return { id: client.id, number: client.number || '', displayName: client.display_name || client.name || '', companyName: client.name || '', website: client.website || '', phone: contact.phone || client.phone || '', email: contact.email || '', contactFirstName: contact.first_name || '', contactLastName: contact.last_name || '', address1: client.address1 || '', address2: client.address2 || '', city: client.city || '', state: client.state || '', postalCode: client.postal_code || '', countryId: client.country_id || '', vatNumber: client.vat_number || '', idNumber: client.id_number || '', balance: Number(client.balance ?? 0), paidToDate: Number(client.paid_to_date ?? 0), publicNotes: client.public_notes || '', privateNotes: client.private_notes || '', editUrl: `${baseUrl}/clients/${client.id}/edit`, } } export async function listInvoiceNinjaClients() { const token = config.invoiceNinja.apiToken if (!token) { const error = new Error('INVOICE_NINJA_API_TOKEN ist nicht konfiguriert') error.status = 503 throw error } const clients = [] let page = 1 let totalPages = 1 while (page <= totalPages) { const url = new URL(`${config.invoiceNinja.url}/api/v1/clients`) url.searchParams.set('per_page', '100') url.searchParams.set('page', String(page)) url.searchParams.set('include', 'contacts') const response = await fetch(url, { headers: { 'X-API-TOKEN': token, 'X-Requested-With': 'XMLHttpRequest', Accept: 'application/json', }, }) const data = await response.json().catch(() => ({})) if (!response.ok) { const error = new Error(data.message || 'Invoice Ninja API Fehler') error.status = response.status === 401 ? 502 : response.status throw error } const batch = (data.data || []).filter((c) => !c.is_deleted) clients.push(...batch.map(sanitizeInvoiceClient)) totalPages = Number(data.meta?.pagination?.total_pages || 1) page += 1 } return clients.sort((a, b) => (a.displayName || a.companyName).localeCompare(b.displayName || b.companyName, 'de') ) }