This repository has been archived on 2026-11-05. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
thetool/public/js/pages/ManualInvoice/ManualInvoice.js
T

443 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Vue.component('manual-invoice', {
template: `
<tt-card>
<div class="d-flex justify-content-between align-items-center mb-3">
<tt-button text="Neue Rechnung" icon="fas fa-plus" @click="openModal()" additional-class="btn-primary"/>
</div>
<tt-table-crud
ref="table"
emit-edit
@edit="openModal($event)">
<template v-slot:total="{ row }">
{{ formatPrice(row.total) }}
</template>
<template v-slot:total_gross="{ row }">
{{ formatPrice(row.total_gross) }}
</template>
<template v-slot:invoice_date="{ row }">
{{ formatDate(row.invoice_date) }}
</template>
<template v-slot:customerName="{ row }">
{{ row.customerName }}
</template>
<template v-slot:actions="{ row }">
<button class="btn btn-sm btn-primary" @click="downloadPdf(row.id)" title="PDF herunterladen">
<i class="fas fa-file-pdf"></i>
</button>
</template>
</tt-table-crud>
<manual-invoice-modal
v-if="isModalOpen"
:initial-data="editingInvoiceData"
@close="closeModal"
@save="handleSave"
/>
</tt-card>
`,
data() {
return {
isModalOpen: false,
editingInvoiceData: null,
}
},
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();
},
async handleSave(invoiceData) {
try {
// Calculate totals for each position
const positions = invoiceData.positions.map(p => {
const amount = parseFloat(p.amount) || 0;
const price = parseFloat(p.price) || 0;
const vatrate = parseFloat(p.vatrate) || 0;
const price_total = amount * price;
const price_gross = price_total * (1 + vatrate / 100);
return {
...p,
amount,
price,
vatrate,
price_total,
price_gross,
product_id: 0,
contract_id: 0,
billing_id: 0,
billing_period: 0
};
});
// Prepare invoice data
const payload = {
id: invoiceData.id || null,
invoice_number: invoiceData.invoice_number,
invoice_date: invoiceData.invoice_date,
owner_id: invoiceData.owner_id || 0,
billingaddress_id: invoiceData.billingaddress_id || 0,
customer_number: invoiceData.customer_number || 0,
company: invoiceData.company || '',
firstname: invoiceData.firstname || '',
lastname: invoiceData.lastname || '',
street: invoiceData.street || '',
zip: invoiceData.zip || '',
city: invoiceData.city || '',
country: invoiceData.country || 'Österreich',
email: invoiceData.email || '',
uid: invoiceData.uid || '',
billing_type: invoiceData.billing_type || 'invoice',
billing_delivery: 'email',
tax_text: invoiceData.tax_text || '',
fibu_payment_due: 14,
fibu_account_number: invoiceData.fibu_account_number || 0,
vatgroup_id: 1,
positions: positions
};
const url = invoiceData.id
? window.TT_CONFIG.UPDATE_URL
: window.TT_CONFIG.CREATE_URL;
const response = await axios.post(url, payload);
if (response.data.success) {
window.notify('success', response.data.message || 'Rechnung erfolgreich gespeichert!');
this.closeModal();
} else {
window.notify('error', response.data.message || 'Fehler beim Speichern der Rechnung');
}
} catch (error) {
console.error('Error saving invoice:', error);
window.notify('error', 'Fehler beim Speichern der Rechnung: ' + (error.response?.data?.message || error.message));
}
},
downloadPdf(invoiceId) {
window.location.href = `${window.TT_CONFIG.BASE_PATH}/ManualInvoice/downloadInvoicePdf?id=${invoiceId}`;
},
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: `
<div class="manual-invoice-overlay" :class="overlayClasses" tabindex="-1" ref="overlay">
<div class="info-bar" v-if="!isLargeScreen">
<i class="fas fa-info-circle mr-2"></i> Drücke <strong>STRG + Q</strong> um die Vorschau umzuschalten.
</div>
<div class="invoice-editor-pane" v-show="isLargeScreen || !showPreviewOnSmallScreen">
<div class="editor-header">
<h3>{{ isCreateMode ? 'Neue Rechnung' : 'Rechnung bearbeiten' }}</h3>
<div class="editor-actions">
<tt-button text="Speichern" icon="fas fa-save" @click="saveInvoice" additional-class="btn-success"/>
<tt-button text="Schließen" icon="fas fa-times" @click="close" additional-class="btn-secondary"/>
</div>
</div>
<div class="editor-content">
<tt-card>
<template v-slot:header><h5><i class="fas fa-user-tie mr-2"></i>Kunde</h5></template>
<tt-autocomplete label="Kunde suchen" :api-url="customerApiUrl" v-model="invoiceData.billingaddress_id" sm row />
</tt-card>
<tt-card>
<template v-slot:header><h5><i class="fas fa-file-invoice mr-2"></i>Rechnungsdetails</h5></template>
<div class="form-grid">
<tt-input label="Rechnungsnr." v-model="invoiceData.invoice_number" sm/>
<tt-date-picker label="Rechnungsdatum" v-model="invoiceData.invoice_date" :date-range="false" sm/>
<tt-select label="Zahlungsart" v-model="invoiceData.billing_type" :options="billingTypeOptions" sm/>
</div>
</tt-card>
<tt-card>
<template v-slot:header><h5><i class="fas fa-list-ol mr-2"></i>Positionen</h5></template>
<tt-positions-manager ref="positionsManager" v-model="invoiceData.positions" :config="positionsConfig" />
</tt-card>
<tt-card>
<template v-slot:header><h5><i class="fas fa-paragraph mr-2"></i>Texte</h5></template>
<tt-textarea label="Steuerhinweis (z.B. Reverse Charge)" v-model="invoiceData.tax_text" rows="2"/>
</tt-card>
</div>
</div>
<div class="invoice-preview-pane" v-show="isLargeScreen || showPreviewOnSmallScreen">
<div class="pdf-preview-container">
<div v-if="pdfLoading" class="pdf-loading">
<i class="fas fa-spinner fa-spin fa-3x"></i>
<p>PDF wird generiert...</p>
</div>
<object v-else :data="pdfPreviewUrl" type="application/pdf" width="100%" height="100%">
<p>PDF Vorschau kann nicht angezeigt werden. <a :href="pdfPreviewUrl" target="_blank">Hier klicken zum Öffnen</a></p>
</object>
</div>
</div>
</div>
`,
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,
pdfLoading: false,
pdfPreviewUrl: '',
previewDebounceTimer: null,
invoiceData: {
id: null,
invoice_number: `MRN${new Date().getFullYear()}-X000001`,
invoice_date: moment().unix(),
billingaddress_id: null,
owner_id: null,
customer_number: 0,
fibu_account_number: 0,
company: '',
firstname: '',
lastname: '',
street: '',
zip: '',
city: '',
country: 'Österreich',
uid: '',
email: '',
billing_type: 'invoice',
tax_text: '',
positions: [],
total: 0,
total_gross: 0
},
billingTypeOptions: [
{value: 'invoice', text: 'Rechnung'},
{value: 'sepa', text: 'SEPA'}
],
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': {
handler() {
this.debouncedPreviewUpdate();
},
deep: true
},
'invoiceData.billingaddress_id': {
async handler(newId) {
if (!newId) {
this.invoiceData.company = '';
this.invoiceData.firstname = '';
this.invoiceData.lastname = '';
this.invoiceData.street = '';
this.invoiceData.zip = '';
this.invoiceData.city = '';
this.invoiceData.country = 'Österreich';
this.invoiceData.uid = '';
this.invoiceData.email = '';
this.invoiceData.customer_number = 0;
this.invoiceData.fibu_account_number = 0;
this.invoiceData.owner_id = 0;
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.company = addr.company || '';
this.invoiceData.firstname = addr.firstname || '';
this.invoiceData.lastname = addr.lastname || '';
this.invoiceData.street = addr.street || '';
this.invoiceData.zip = addr.zip || '';
this.invoiceData.city = addr.city || '';
this.invoiceData.country = 'Österreich';
this.invoiceData.uid = addr.uid || '';
this.invoiceData.email = addr.email || '';
this.invoiceData.customer_number = addr.customer_number || 0;
this.invoiceData.fibu_account_number = addr.fibu_account_number || 0;
this.invoiceData.owner_id = newId;
}
},
immediate: true
}
},
created() {
if (this.initialData) {
this.invoiceData = {
...this.invoiceData,
...JSON.parse(JSON.stringify(this.initialData))
};
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);
window.addEventListener('keydown', this.handleGlobalKeydown);
this.handleResize();
this.$nextTick(() => {
if (this.$refs.overlay) {
this.$refs.overlay.focus();
}
this.updatePdfPreview();
});
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
window.removeEventListener('keydown', this.handleGlobalKeydown);
if (this.previewDebounceTimer) {
clearTimeout(this.previewDebounceTimer);
}
},
methods: {
close() { this.$emit('close'); },
saveInvoice() {
if (!this.invoiceData.billingaddress_id) {
window.notify('error', 'Bitte wählen Sie einen Kunden aus.');
return;
}
if (!this.invoiceData.positions || this.invoiceData.positions.length === 0) {
window.notify('error', 'Bitte fügen Sie mindestens eine Position hinzu.');
return;
}
this.$emit('save', this.invoiceData);
},
handleResize() { this.isLargeScreen = window.innerWidth >= 1920; },
handleGlobalKeydown(event) {
// Handle CTRL+Q to toggle preview on small screens
if (event.ctrlKey && event.key === 'q') {
event.preventDefault();
this.togglePreviewVisibility();
}
},
togglePreviewVisibility() { if (!this.isLargeScreen) this.showPreviewOnSmallScreen = !this.showPreviewOnSmallScreen; },
debouncedPreviewUpdate() {
if (this.previewDebounceTimer) {
clearTimeout(this.previewDebounceTimer);
}
this.previewDebounceTimer = setTimeout(() => {
this.updatePdfPreview();
}, 2000);
},
async updatePdfPreview() {
this.pdfLoading = true;
try {
// Calculate position totals
const positions = this.invoiceData.positions.map(p => {
const amount = parseFloat(p.amount) || 0;
const price = parseFloat(p.price) || 0;
const vatrate = parseFloat(p.vatrate) || 0;
const price_total = amount * price;
const price_gross = price_total * (1 + vatrate / 100);
return {
...p,
amount,
price,
vatrate,
price_total,
price_gross
};
});
const payload = {
preview: true,
invoice_number: this.invoiceData.invoice_number,
invoice_date: this.invoiceData.invoice_date,
customer_number: this.invoiceData.customer_number,
fibu_account_number: this.invoiceData.fibu_account_number,
company: this.invoiceData.company,
firstname: this.invoiceData.firstname,
lastname: this.invoiceData.lastname,
street: this.invoiceData.street,
zip: this.invoiceData.zip,
city: this.invoiceData.city,
country: this.invoiceData.country,
email: this.invoiceData.email,
uid: this.invoiceData.uid,
tax_text: this.invoiceData.tax_text,
billing_type: this.invoiceData.billing_type,
total: this.totals.net,
total_gross: this.totals.gross,
positions: positions
};
const response = await axios.post(
`${window.TT_CONFIG.BASE_PATH}/ManualInvoice/createPDF`,
payload,
{ responseType: 'blob' }
);
// Create a blob URL for the PDF
const blob = new Blob([response.data], { type: 'application/pdf' });
if (this.pdfPreviewUrl) {
URL.revokeObjectURL(this.pdfPreviewUrl);
}
this.pdfPreviewUrl = URL.createObjectURL(blob) + '#view=FitH';
} catch (error) {
console.error('Error generating PDF preview:', error);
window.notify('error', 'Fehler beim Generieren der PDF-Vorschau');
} finally {
this.pdfLoading = false;
}
}
}
});