Vue.component('manual-invoice', { template: `
`, data() { return { isModalOpen: false, editingInvoiceData: null, } }, mounted() { const prefillData = localStorage.getItem('ManualInvoice_create'); if (prefillData) { try { this.editingInvoiceData = JSON.parse(prefillData); this.isModalOpen = true; } catch (e) { console.error("Failed to parse prefill data:", e); } finally { localStorage.removeItem('ManualInvoice_create'); } } }, methods: { openModal(invoice = null) { this.editingInvoiceData = invoice ? JSON.parse(JSON.stringify(invoice)) : null; this.isModalOpen = true; }, closeModal() { this.isModalOpen = false; this.editingInvoiceData = null; this.$refs.table.$refs.table.refreshTable(); }, handleSave(invoiceData) { console.log("--- INVOICE SAVED (DEMO) ---"); console.log(JSON.parse(JSON.stringify(invoiceData))); window.notify('success', 'Rechnung in der Konsole geloggt!'); this.closeModal(); }, testPrefill() { const mockInvoice = { id: null, invoiceNumber: `RE-${new Date().getFullYear()}-XXXX`, invoiceDate: moment().unix(), dueDate: moment().add(14, 'days').unix(), status: 'draft', billingAddressId: 1, // Example ID for autocomplete to fetch customer: {}, // Will be populated by watcher positions: [ { product_name: 'Stunden Techniker', product_info: 'Arbeiten an Server-Infrastruktur', start_date: moment().format('YYYY-MM-DD'), end_date: moment().format('YYYY-MM-DD'), amount: 3.5, price: 95.00, vatrate: 20 }, { product_name: 'Anfahrtspauschale', product_info: '', start_date: moment().format('YYYY-MM-DD'), end_date: moment().format('YYYY-MM-DD'), amount: 1, price: 45.00, vatrate: 20 } ], closingText: 'Wir bedanken uns für die gute Zusammenarbeit.', taxText: '' }; localStorage.setItem('ManualInvoice_create', JSON.stringify(mockInvoice)); window.location.reload(); }, formatPrice(value) { return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(value || 0); }, formatDate(timestamp) { if (!timestamp) return '–'; return moment.unix(timestamp).format('DD.MM.YYYY'); } } }); Vue.component('manual-invoice-modal', { props: ['initialData'], template: `
Drücke STRG + Q um die Vorschau umzuschalten.

{{ isCreateMode ? 'Neue Rechnung' : 'Rechnung bearbeiten' }}

Xinon Logo
{{ invoiceData.customer.company }}
{{ invoiceData.customer.name }}
{{ invoiceData.customer.street }}
{{ invoiceData.customer.zip }} {{ invoiceData.customer.city }}
{{ invoiceData.customer.country }}
Kundennummer:{{ selectedCustomerObject.customer_number || '-' }}
Rechnungsnummer:{{ invoiceData.invoiceNumber }}
Belegdatum:{{ formatDate(invoiceData.invoiceDate) }}
Ihre UID:{{ invoiceData.customer.uid }}

Ihre Rechnung vom {{ formatDate(invoiceData.invoiceDate) }}

Leistung / Produkt Zeitraum Preis Menge Netto € Ust. % Brutto €
Gesamtbetrag Netto: {{ formatPrice(totals.net) }} €
+ Umsatzsteuer {{ vatRate }}%: {{ formatPrice(vatValue) }} €
Gesamtbetrag Brutto: {{ formatPrice(totals.gross) }} €

{{invoiceData.taxText}}

Bitte überweisen Sie den Rechnungsbetrag bis zum {{ formatDate(invoiceData.dueDate) }} auf folgendes Konto:
IBAN: {{ bankDetails.iban }}
BIC: {{ bankDetails.bic }}

Bitte geben Sie als Verwendungszweck unbedingt die Rechnungsnummer an.
`, data() { return { isCreateMode: !this.initialData || !this.initialData.id, customerApiUrl: window.TT_CONFIG['BASE_PATH'] + '/Address/Api?do=findAddress&fibu_primary_account=1', selectedCustomerObject: {}, isLargeScreen: window.innerWidth >= 1920, showPreviewOnSmallScreen: false, invoiceData: { id: null, invoiceNumber: `RE-${new Date().getFullYear()}-`, invoiceDate: moment().unix(), dueDate: moment().add(14, 'days').unix(), status: 'draft', billingAddressId: null, customer: { company: '', name: '', street: '', zip: '', city: '', country: 'Österreich', uid: '' }, positions: [], closingText: 'Wir danken für Ihren Auftrag und verbleiben mit freundlichen Grüßen,\nIhr Xinon Team', taxText: '', }, bankDetails: { iban: 'ATXX XXXX XXXX XXXX XXXX', bic: 'XXXXXXXX' }, positionsConfig: { fields: { product_name: { type: 'input', label: 'Bezeichnung' }, product_info: { type: 'input', label: 'Zusatzinfo' }, start_date: { type: 'input', label: 'Start', inputType: 'date' }, end_date: { type: 'input', label: 'Ende', inputType: 'date' }, amount: { type: 'input', label: 'Menge', inputType: 'number' }, price: { type: 'input', label: 'Einzelpreis (€)', inputType: 'number' }, vatrate: { type: 'input', label: 'USt. (%)', inputType: 'number' }, }, validateForm: (formData) => { if (!formData.product_name) { window.notify('error', 'Bezeichnung ist erforderlich.'); return false; } if (!formData.amount) { window.notify('error', 'Menge ist erforderlich.'); return false; } if (formData.price === null || formData.price === undefined) { window.notify('error', 'Preis ist erforderlich.'); return false; } return true; } } }; }, computed: { overlayClasses() { return { 'preview-active-small': !this.isLargeScreen && this.showPreviewOnSmallScreen, 'editor-active-small': !this.isLargeScreen && !this.showPreviewOnSmallScreen, }; }, totals() { let net = 0; const vat = {}; if (!Array.isArray(this.invoiceData.positions)) return { net: 0, vat: {}, gross: 0 }; this.invoiceData.positions.forEach(p => { const lineTotal = (parseFloat(p.amount) || 0) * (parseFloat(p.price) || 0); const vatRate = parseInt(p.vatrate) || 0; net += lineTotal; if (!vat[vatRate]) { vat[vatRate] = 0; } vat[vatRate] += lineTotal * (vatRate / 100); }); const gross = net + Object.values(vat).reduce((sum, v) => sum + v, 0); return { net, vat, gross }; } }, watch: { 'invoiceData.billingAddressId': { async handler(newId) { if (!newId) { this.invoiceData.customer = { company: '', name: '', street: '', zip: '', city: '', country: 'Österreich', uid: '' }; this.selectedCustomerObject = {}; return; } const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/Address/api?do=getAddress&id=${newId}`); if (response.data.status === 'OK' && response.data.result.address) { const addr = response.data.result.address; this.selectedCustomerObject = addr; this.invoiceData.customer = { company: addr.company, name: `${addr.firstname} ${addr.lastname}`, street: addr.street, zip: addr.zip, city: addr.city, country: 'Österreich', uid: addr.uid }; } }, immediate: true } }, created() { if (this.initialData) { // FIX: Merge initial data with default structure to ensure all keys, especially nested ones, exist. this.invoiceData = { ...this.invoiceData, // Start with default structure ...JSON.parse(JSON.stringify(this.initialData)) // Overwrite with passed data }; // Explicitly ensure nested objects exist if they weren't in initialData if (!this.invoiceData.customer) { this.invoiceData.customer = { company: '', name: '', street: '', zip: '', city: '', country: 'Österreich', uid: '' }; } // Ensure positions is an array if (!Array.isArray(this.invoiceData.positions)) { try { const parsed = JSON.parse(this.invoiceData.positions); this.invoiceData.positions = Array.isArray(parsed) ? parsed : []; } catch (e) { this.invoiceData.positions = []; } } } }, mounted() { window.addEventListener('resize', this.handleResize); this.handleResize(); this.$nextTick(() => { if (this.$refs.overlay) { this.$refs.overlay.focus(); } }); }, beforeDestroy() { window.removeEventListener('resize', this.handleResize); }, methods: { close() { this.$emit('close'); }, handleResize() { this.isLargeScreen = window.innerWidth >= 1920; }, togglePreviewVisibility() { if (!this.isLargeScreen) this.showPreviewOnSmallScreen = !this.showPreviewOnSmallScreen; }, formatPrice(value) { return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value || 0); }, formatDate(timestamp) { if (!timestamp) return ''; return moment.unix(timestamp).format('DD.MM.YYYY'); }, formatPeriod(start, end) { if (!start) return ''; const startDate = moment(start); const endDate = end ? moment(end) : moment(start); if (!startDate.isValid()) return ''; if (startDate.isSame(endDate, 'day')) return startDate.format('DD.MM.YYYY'); if(startDate.isValid() && endDate.isValid()) { return `${startDate.format('DD.MM.YYYY')} - ${endDate.format('DD.MM.YYYY')}`; } return startDate.format('DD.MM.YYYY'); } } });