Skip to content
Code-Schnipsel Gruppen Projekte
TemporaryInvoice.js 71,1 KiB
Newer Older
  • Learn to ignore specific revisions
  • Henning Leutz's avatar
    Henning Leutz committed
    /**
    
     * @module package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice
    
    Henning Leutz's avatar
    Henning Leutz committed
     * @author www.pcsg.de (Henning Leutz)
    
    Henning Leutz's avatar
    Henning Leutz committed
     *
    
     * Edit a Temporary Invoice and created a posted invoice
    
    Henning Leutz's avatar
    Henning Leutz committed
     */
    
    define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
    
    Henning Leutz's avatar
    Henning Leutz committed
        'qui/QUI',
    
    Henning Leutz's avatar
    Henning Leutz committed
        'qui/controls/desktop/Panel',
    
        'qui/controls/buttons/Button',
    
        'qui/controls/buttons/ButtonMultiple',
        'qui/controls/buttons/Separator',
        'qui/controls/windows/Confirm',
        'qui/utils/Form',
        'controls/users/address/Select',
    
        'package/quiqqer/invoice/bin/Invoices',
    
        'package/quiqqer/invoice/bin/backend/utils/Dialogs',
    
        'package/quiqqer/erp/bin/backend/controls/Comments',
        'package/quiqqer/erp/bin/backend/controls/articles/Text',
        'package/quiqqer/payments/bin/backend/Payments',
        'package/quiqqer/customer/bin/backend/controls/customer/address/Window',
    
        'package/quiqqer/customer/bin/backend/controls/customer/userFiles/Select',
    
        'utils/Lock',
    
        'Locale',
    
    Henning Leutz's avatar
    Henning Leutz committed
        'Ajax',
    
        'Mustache',
        'Users',
        'Editors',
    
        'text!package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice.Data.html',
        'text!package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice.Post.html',
        'text!package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice.Missing.html',
    
        'css!package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice.css'
    
    
    ], function(QUI, QUIPanel, QUIButton, QUIButtonMultiple, QUISeparator, QUIConfirm, QUIFormUtils,
        AddressSelect, Invoices, Dialogs, Comments, TextArticle,
        Payments, AddressWindow, CustomerFileSelect, Locker, QUILocale, QUIAjax, Mustache, Users, Editors,
        templateData, templatePost, templateMissing
    ) {
        'use strict';
    
    Henning Leutz's avatar
    Henning Leutz committed
        const lg = 'quiqqer/invoice';
    
    Henning Leutz's avatar
    Henning Leutz committed
        return new Class({
    
            Extends: QUIPanel,
    
    Henning Leutz's avatar
    Henning Leutz committed
            Type: 'package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice',
    
    Henning Leutz's avatar
    Henning Leutz committed
    
            Binds: [
    
                'save',
                'post',
                'openData',
                'openArticles',
                'openComments',
                'openAddCommentDialog',
                'openVerification',
                '$openCategory',
                '$closeCategory',
    
    Henning Leutz's avatar
    Henning Leutz committed
                '$onCreate',
    
                '$onInject',
    
                '$onKeyUp',
    
                '$onDestroy',
    
                '$onDeleteInvoice',
                '$onArticleReplaceClick',
                '$clickDelete',
                'toggleSort',
    
                '$showLockMessage',
    
    Henning Leutz's avatar
    Henning Leutz committed
                'openInvoiceFiles',
                '$openXmlCategory'
    
    Henning Leutz's avatar
    Henning Leutz committed
            ],
    
            options: {
    
                invoiceId: false, // @deprecated
    
    Henning Leutz's avatar
    Henning Leutz committed
                customer_id: false,
                invoice_address: false,
    
                invoice_address_id: false,
    
    Henning Leutz's avatar
    Henning Leutz committed
                project_name: '',
                date: '',
                time_for_payment: '',
                data: {},
                articles: []
    
            initialize: function(options) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                this.setAttributes({
    
    Henning Leutz's avatar
    Henning Leutz committed
                    icon: 'fa fa-file-text-o'
    
    Henning Leutz's avatar
    Henning Leutz committed
                });
    
                this.parent(options);
    
                if (this.getAttribute('invoiceId') && !this.getAttribute('hash')) {
    
                    this.setAttribute('hash', this.getAttribute('invoiceId'));
    
                if (this.getAttribute('uuid') && !this.getAttribute('hash')) {
                    this.setAttribute('hash', this.getAttribute('uuid'));
                }
    
    
                this.$AdditionalText = null;
                this.$ArticleList = null;
    
                this.$ArticleListSummary = null;
    
                this.$AddProduct = null;
                this.$ArticleSort = null;
                this.$AddressDelivery = null;
    
                this.$AddSeparator = null;
    
                this.$SortSeparator = null;
    
    
                this.$serializedList = {};
    
    Henning Leutz's avatar
    Henning Leutz committed
                this.addEvents({
    
    Henning Leutz's avatar
    Henning Leutz committed
                    onCreate: this.$onCreate,
                    onInject: this.$onInject,
    
                    onDestroy: this.$onDestroy
    
                });
    
                Invoices.addEvents({
    
                    onDeleteInvoice: this.$onDeleteInvoice
    
             * Return the lock key
             *
             * @return {string}
    
            $getLockKey: function() {
                return 'lock-invoice-temporary-' + this.getAttribute('hash');
    
            /**
             * Return the lock group
             * @return {string}
             */
    
            $getLockGroups: function() {
    
                return 'quiqqer/invoice';
            },
    
            /**
             * Panel refresh
             */
    
            refresh: function() {
                if (!this.getAttribute('prefixedNumber')) {
                    this.setAttribute('title', '...');
                    this.parent();
                    return;
    
                let title = this.getAttribute('prefixedNumber');
    
                title = title + ' (';
    
                if (this.getAttribute('isbrutto')) {
    
                    title = title + QUILocale.get(lg, 'brutto.panel.title');
    
                } else {
    
                    title = title + QUILocale.get(lg, 'netto.panel.title');
    
                }
    
                title = title + ')';
    
                this.setAttribute('title', title);
                this.parent();
            },
    
            /**
             * Refresh the invoice data
             */
    
            doRefresh: function() {
                return Invoices.getTemporaryInvoice(this.getAttribute('hash')).then((data) => {
    
                    if (data.articles) {
                        this.$serializedList = data.articles;
    
                        if (typeof this.$serializedList.articles !== 'undefined') {
                            this.setAttribute('articles', this.$serializedList.articles);
                            this.setAttribute('priceFactors', data.articles.priceFactors);
                        }
    
                        if (this.$ArticleList) {
                            this.$ArticleList.unserialize(this.$serializedList);
                        }
    
                    if (data.invoice_address) {
    
                        this.setAttribute('invoice_address', data.invoice_address);
    
            /**
             * Saves the current data
             *
             * @return {Promise}
             */
    
                if (this.$locked) {
                    return Promise.resolve();
                }
    
                this.Loader.show();
                this.$unloadCategory(false);
    
                const currentData = this.getCurrentData();
    
                return Invoices.saveInvoice(this.getAttribute('hash'), currentData).then(function() {
    
                    this.Loader.hide();
                    this.showSavedIconAnimation();
    
                }.bind(this)).catch(function(err) {
    
                    console.error(err);
                    console.error(err.getMessage());
    
    Henning Leutz's avatar
    Henning Leutz committed
                    this.Loader.hide();
                }.bind(this));
    
             * Post the temporary invoice
    
             *
             * @return {Promise}
             */
    
    Henning Leutz's avatar
    Henning Leutz committed
                const self = this;
    
    
                this.Loader.show();
                this.$unloadCategory(false);
    
                return Invoices.saveInvoice(
    
                    this.getAttribute('hash'),
    
                    this.getCurrentData()
    
                ).then(function(Data) {
    
                    return Promise.all([
    
                        Invoices.postInvoice(self.getAttribute('hash')),
    
                        Invoices.getSetting('temporaryInvoice', 'openPrintDialogAfterPost'),
                        Data
                    ]);
    
                }).then(function(result) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let newInvoiceHash = result[0],
    
                        openPrintDialogAfterPost = result[1],
    
    Henning Leutz's avatar
    Henning Leutz committed
                        Data = result[2];
    
    
                    if (!openPrintDialogAfterPost) {
                        self.destroy();
                        return;
                    }
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let entityType;
    
    
                    switch (parseInt(Data.type)) {
                        case 3:
                            entityType = 'CreditNote';
                            break;
    
                        case 4:
                            entityType = 'Canceled';
                            break;
    
                        default:
                            entityType = 'Invoice';
                    }
    
                    // open print dialog
    
                    Dialogs.openPrintDialog(newInvoiceHash, entityType).then(function() {
    
                        self.destroy();
    
                }).catch(function(err) {
    
                    console.error(err);
                    console.error(err.getMessage());
                    this.Loader.hide();
                }.bind(this));
    
             * @returns {{customer_id, invoice_address_id, project_name, articles, date, time_for_payment}}
    
            getCurrentData: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                let deliveryAddress = this.getAttribute('addressDelivery');
    
    
                if (!deliveryAddress) {
                    deliveryAddress = this.getAttribute('delivery_address');
                }
    
    
                return {
    
    Henning Leutz's avatar
    Henning Leutz committed
                    customer_id: this.getAttribute('customer_id'),
                    invoice_address_id: this.getAttribute('invoice_address_id'),
    
                    invoice_address: this.getAttribute('invoice_address'),
    
    Henning Leutz's avatar
    Henning Leutz committed
                    project_name: this.getAttribute('project_name'),
                    articles: this.getAttribute('articles'),
                    priceFactors: this.getAttribute('priceFactors'),
                    date: this.getAttribute('date'),
                    editor_id: this.getAttribute('editor_id'),
                    ordered_by: this.getAttribute('ordered_by'),
                    contact_person: this.getAttribute('contact_person'),
                    contactEmail: this.getAttribute('contactEmail'),
                    time_for_payment: this.getAttribute('time_for_payment'),
                    payment_method: this.getAttribute('payment_method'),
    
                    additional_invoice_text: this.getAttribute('additional_invoice_text'),
    
    Henning Leutz's avatar
    Henning Leutz committed
                    currency: this.getAttribute('currency'),
                    currencyRate: this.getAttribute('currencyRate'),
                    addressDelivery: deliveryAddress,
                    processing_status: this.getAttribute('processing_status'),
    
                    attached_customer_files: this.getAttribute('attached_customer_files')
    
            /**
             * Return the current user data
             */
    
            getUserData: function() {
    
                return {
                    uid: this.getAttribute('customer_id'),
                    aid: this.getAttribute('invoice_address_id')
                };
    
    Henning Leutz's avatar
    Henning Leutz committed
            },
    
    
             * Categories
    
             * Open the data category
             *
             * @returns {Promise}
    
    Henning Leutz's avatar
    Henning Leutz committed
             */
    
            openData: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                const self = this;
    
                this.renderDataDone = false;
                this.Loader.show();
    
                return this.$closeCategory().then(function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const Container = self.getContent().getElement('.container');
    
    
                    Container.setStyle('height', null);
    
                    Container.set({
                        html: Mustache.render(templateData, {
    
    Henning Leutz's avatar
    Henning Leutz committed
                            textInvoiceData: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textInvoiceData'),
                            textInvoiceDate: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textInvoiceDate'),
    
                            textTermOfPayment: QUILocale.get(
                                lg,
                                'erp.panel.temporary.invoice.category.data.textTermOfPayment'
                            ),
    
    Henning Leutz's avatar
    Henning Leutz committed
                            textProjectName: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textProjectName'),
                            textOrderedBy: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textOrderedBy'),
                            textEditor: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textEditor'),
    
                            textInvoicePayment: QUILocale.get(
                                lg,
                                'erp.panel.temporary.invoice.category.data.textInvoicePayment'
                            ),
                            textPaymentMethod: QUILocale.get(
                                lg,
                                'erp.panel.temporary.invoice.category.data.textPaymentMethod'
                            ),
    
    Henning Leutz's avatar
    Henning Leutz committed
                            textInvoiceText: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textInvoiceText'),
                            textStatus: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textStatus'),
    
                            textContactPerson: QUILocale.get(
                                lg,
                                'erp.panel.temporary.invoice.category.data.textContactPerson'
                            ),
    
    Henning Leutz's avatar
    Henning Leutz committed
                            textCurrency: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textCurrency'),
    
                            textCurrencyRate: QUILocale.get(
                                lg,
                                'erp.panel.temporary.invoice.category.data.textCurrencyRate'
                            ),
    
    Henning Leutz's avatar
    Henning Leutz committed
                            textInvoiceDeliveryAddress: QUILocale.get(lg, 'deliveryAddress')
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const Form = Container.getElement('form');
    
    
                    QUIFormUtils.setDataToForm(self.getAttribute('data'), Form);
    
                    // set invoice date to today
                    // quiqqer/invoice#46
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let local = new Date();
    
                    local.setMinutes(local.getMinutes() - local.getTimezoneOffset());
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let dateDate = local.toJSON().slice(0, 10);
    
    
                    QUIFormUtils.setDataToForm({
    
    Henning Leutz's avatar
    Henning Leutz committed
                        date: dateDate,
                        time_for_payment: self.getAttribute('time_for_payment'),
                        project_name: self.getAttribute('project_name'),
                        editor_id: self.getAttribute('editor_id'),
    
                        processing_status: self.getAttribute('processing_status'),
    
    Henning Leutz's avatar
    Henning Leutz committed
                        contact_person: self.getAttribute('contact_person'),
                        currency: self.getAttribute('currency'),
                        currencyRate: self.getAttribute('currencyRate')
    
                    }, Form);
    
                    Form.elements.date.set('disabled', true);
                    Form.elements.date.set('title', QUILocale.get(lg, 'permissions.set.invoice.date'));
    
    
                    require(['Permissions'], function(Permissions) {
                        Permissions.hasPermission('quiqqer.invoice.changeDate').then(function(has) {
    
                            if (has) {
                                Form.elements.date.set('disabled', false);
                                Form.elements.date.set('title', '');
    
                    return QUI.parse(Container);
    
                }).then(function() {
                    return new Promise(function(resolve, reject) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                        const Form = self.getContent().getElement('form');
    
    Henning Leutz's avatar
    Henning Leutz committed
                        require([
                            'Packages',
                            'utils/Controls'
    
                        ], function(Packages, ControlUtils) {
                            ControlUtils.parse(Form).then(function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                                return Packages.getConfig('quiqqer/currency');
                            }).then(resolve);
    
                        }, reject);
                    });
    
                }).then(function(config) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const Content = self.getContent();
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const quiId = Content.getElement(
    
                        '[data-qui="package/quiqqer/erp/bin/backend/controls/userData/UserData"]'
    
                    ).get('data-quiid');
    
                    let editorIdQUIId = Content.getElement('[name="editorId"]').get('data-quiid');
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let orderedByIdQUIId = Content.getElement('[name="orderedBy"]').get('data-quiid');
    
                    let currencyIdQUIId = Content.getElement('[name="currency"]').get('data-quiid');
                    let CurrencyRate = Content.getElement('[name="currencyRate"]');
    
                    let Data = QUI.Controls.getById(quiId);
                    let EditorId = QUI.Controls.getById(editorIdQUIId);
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let OrderedBy = QUI.Controls.getById(orderedByIdQUIId);
    
                    let Currency = QUI.Controls.getById(currencyIdQUIId);
    
    Henning Leutz's avatar
    Henning Leutz committed
                    if (parseInt(config.currency.differentAccountingCurrencies) === 0) {
                        Content.getElements('table.invoice-currency').setStyle('display', 'none');
                    }
    
    
                    OrderedBy.setAttribute('showAddressName', false);
    
                    Data.addEvent('onChange', function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                        if (self.renderDataDone === false) {
                            return;
                        }
    
    
                        const Customer = Data.getValue();
    
                        let userId = Customer.userId;
    
                        self.setAttribute('customer_id', userId);
    
                        self.setAttribute('invoice_address_id', Customer.addressId);
                        self.setAttribute('contact_person', Customer.contactPerson);
                        self.setAttribute('contactEmail', Customer.contactEmail);
    
                        self.setAttribute('invoice_address', Data.getAddress());
    
                        if (Customer['quiqqer.erp.standard.payment'] !== '' && Customer['quiqqer.erp.standard.payment']) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                            self.getContent().getElement('[name="payment_method"]').value = Customer['quiqqer.erp.standard.payment'];
                        }
    
    
                        // reset deliver address
                        if (self.$AddressDelivery) {
                            self.$AddressDelivery.setAttribute('userId', userId);
                        }
    
                        Promise.all([
                            Invoices.getPaymentTime(userId),
                            Invoices.isNetto(userId)
    
                        ]).then(function(result) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                            let paymentTime = result[0];
    
    Henning Leutz's avatar
    Henning Leutz committed
                            if (Customer['quiqqer.erp.customer.payment.term']) {
                                paymentTime = Customer['quiqqer.erp.customer.payment.term'];
                            }
    
    
                            Content.getElement('[name="time_for_payment"]').value = paymentTime;
    
                            self.setAttribute('isbrutto', !isNetto);
                            self.setAttribute('time_for_payment', paymentTime);
                            self.refresh();
                        });
                    });
    
                    // currency
    
                    Currency.addEvent('change', function(Instance, value) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                        if (self.renderDataDone === false) {
                            return;
                        }
    
                        self.Loader.show();
    
                        self.setAttribute('currency', value);
    
                        require(['package/quiqqer/currency/bin/Currency'], function(Currencies) {
                            Currencies.getCurrency(value).then(function(data) {
                                if ('rate' in data) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    self.setAttribute('currencyRate', data.rate);
                                    CurrencyRate.value = data.rate;
                                }
    
                                self.Loader.hide();
    
                            }).catch(function(err) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                                console.error(err);
                                self.Loader.hide();
                            });
                        });
    
                    // editor
    
                    EditorId.addEvent('onChange', function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                        if (self.renderDataDone === false) {
                            return;
                        }
    
                        self.setAttribute('editor_id', EditorId.getValue());
                    });
    
                    if (typeof window.QUIQQER_EMPLOYEE_GROUP !== 'undefined') {
                        EditorId.setAttribute('search', true);
                        EditorId.setAttribute('searchSettings', {
                            filter: {
                                filter_group: window.QUIQQER_EMPLOYEE_GROUP
                            }
                        });
                    }
    
                    if (self.getAttribute('editor_id')) {
    
                        EditorId.addItem(self.getAttribute('editor_id'));
                    } else {
                        EditorId.addItem(USER.id);
                    }
    
                    // ordered by
    
                    OrderedBy.addEvent('onChange', function() {
    
                        self.setAttribute('ordered_by', OrderedBy.getValue());
                    });
    
                    if (typeof window.QUIQQER_CUSTOMER_GROUP !== 'undefined') {
                        OrderedBy.setAttribute('search', true);
                        OrderedBy.setAttribute('searchSettings', {
                            filter: {
                                filter_group: window.QUIQQER_CUSTOMER_GROUP
                            }
                        });
                    }
    
                    if (self.getAttribute('ordered_by')) {
                        OrderedBy.addItem(self.getAttribute('ordered_by'));
    
                    // invoice address
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let address = self.getAttribute('invoice_address');
    
                    if (!address) {
                        address = {};
                    }
    
                    address.userId = self.getAttribute('customer_id');
                    address.addressId = self.getAttribute('invoice_address_id');
    
                    address.contactPerson = self.getAttribute('contact_person') ? self.getAttribute('contact_person') : '';
    
                    if (self.getAttribute('contactEmail')) {
                        address.contactEmail = self.getAttribute('contactEmail');
                    }
    
                    address.name = self.getAttribute('customer_name');
    
                    return Data.setValue(address);
    
                    // invoice address
                    const dataQUIID = self.getContent().getElement(
                        '[data-qui="package/quiqqer/erp/bin/backend/controls/userData/UserData"]'
                    ).get('data-quiid');
    
                    let Data = QUI.Controls.getById(dataQUIID);
    
                    self.setAttribute('invoice_address', Data.getAddress());
    
    
                    // delivery address
                    self.$AddressDelivery = QUI.Controls.getById(
                        self.getContent().getElement(
    
                            '[data-qui="package/quiqqer/erp/bin/backend/controls/DeliveryAddress"]'
    
                        ).get('data-quiid')
                    );
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let deliveryAddress = self.getAttribute('addressDelivery');
    
                    if (!deliveryAddress) {
                        deliveryAddress = self.getAttribute('delivery_address');
    
                        if (deliveryAddress) {
                            deliveryAddress = JSON.decode(deliveryAddress);
    
    
                    if (deliveryAddress) {
                        self.$AddressDelivery.setAttribute('userId', self.getAttribute('customer_id'));
                        self.$AddressDelivery.setValue(deliveryAddress);
                    }
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let Container = self.getContent().getElement('.container');
    
    
                    new QUIButton({
    
    Henning Leutz's avatar
    Henning Leutz committed
                        text: QUILocale.get(lg, 'erp.panel.temporary.invoice.button.nextToArticles') +
                            ' <span class="fa fa-angle-right"></span>',
    
                            display: 'block',
                            'float': 'right',
    
    Henning Leutz's avatar
    Henning Leutz committed
                            margin: '0 0 20px'
    
                            onClick: function() {
                                self.openArticles().catch(function(e) {
    
                                    console.error(e);
    
                    }).inject(Container);
    
                    return Payments.getPayments();
    
                }).then(function(payments) {
    
                    // load payments
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let Payments = self.getContent().getElement('[name="payment_method"]');
    
                    new Element('option', {
    
    Henning Leutz's avatar
    Henning Leutz committed
                        html: '',
    
                        value: ''
                    }).inject(Payments);
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let i, len, title;
                    let current = QUILocale.getCurrent();
    
    Henning Leutz's avatar
    Henning Leutz committed
                    // payment sort
                    payments.sort((a, b) => {
                        let titleA = a.title[current] ? a.title[current].toLowerCase() : '';
                        let titleB = b.title[current] ? b.title[current].toLowerCase() : '';
    
                        if (titleA < titleB) {
                            return -1;
                        }
    
                        if (titleA > titleB) {
                            return 1;
                        }
    
                        return 0;
                    });
    
    
                    for (i = 0, len = payments.length; i < len; i++) {
                        title = payments[i].title;
    
                        if (typeOf(title) === 'object' && typeof title[current] !== 'undefined') {
                            title = title[current];
                        }
    
                        new Element('option', {
    
    Henning Leutz's avatar
    Henning Leutz committed
                            html: title,
    
                            value: payments[i].id
                        }).inject(Payments);
                    }
    
                    Payments.value = self.getAttribute('payment_method');
    
                    // additional-invoice-text -> wysiwyg
                    return self.$loadAdditionalInvoiceText();
    
                    self.getCategory('data').setActive();
    
                    return self.Loader.hide();
    
                    return self.$openCategory();
    
                    self.renderDataDone = true;
                });
    
             * Open the product category
             *
             * @returns {Promise}
    
    Henning Leutz's avatar
    Henning Leutz committed
             */
    
            openArticles: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                const self = this;
    
                this.Loader.show();
    
                return self.$closeCategory().then(function(Container) {
                    return new Promise(function(resolve) {
    
                        require([
                            'package/quiqqer/erp/bin/backend/controls/articles/ArticleList',
                            'package/quiqqer/erp/bin/backend/controls/articles/ArticleSummary'
    
                        ], function(List, Summary) {
    
                            self.$ArticleList = new List({
    
                                nettoinput: !self.getAttribute('isbrutto'),
    
    Henning Leutz's avatar
    Henning Leutz committed
                                currency: self.getAttribute('currency'),
                                events: {
    
                                    onArticleReplaceClick: self.$onArticleReplaceClick
                                },
    
    Henning Leutz's avatar
    Henning Leutz committed
                                styles: {
    
                                    height: 'calc(100% - 110px)'
    
                                }
                            }).inject(Container);
    
                            Container.setStyle('height', '100%');
    
                            self.$ArticleListSummary = new Summary({
                                currency: self.getAttribute('currency'),
    
    Henning Leutz's avatar
    Henning Leutz committed
                                List: self.$ArticleList,
                                styles: {
                                    bottom: -20,
                                    left: 0,
                                    opacity: 0,
    
                                    position: 'absolute'
                                }
                            }).inject(Container.getParent());
    
                            moofx(self.$ArticleListSummary.getElm()).animate({
    
    Henning Leutz's avatar
    Henning Leutz committed
                                bottom: 0,
    
                                opacity: 1
                            });
    
                            self.$ArticleList.setUser(self.getUserData());
    
                            if (self.$serializedList) {
                                self.$ArticleList.unserialize(self.$serializedList);
                            }
    
                            self.$AddProduct.show();
                            self.$AddSeparator.show();
                            self.$SortSeparator.show();
                            self.$ArticleSort.show();
    
                            self.getCategory('articles').setActive();
    
                            new QUIButton({
    
    Henning Leutz's avatar
    Henning Leutz committed
                                text: '<span class="fa fa-angle-left"></span> ' +
                                    QUILocale.get(lg, 'erp.panel.temporary.invoice.button.data'),
    
                                    'float': 'left',
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    margin: '20px 0 0'
    
                                    onClick: self.openData
                                }
                            }).inject(Container);
    
                            new QUIButton({
    
    Henning Leutz's avatar
    Henning Leutz committed
                                text: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.review.btnGoto') +
                                    ' <span class="fa fa-angle-right"></span>',
    
                                    'float': 'right',
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    margin: '20px 0 0'
    
                                    onClick: self.openVerification
                                }
                            }).inject(Container);
    
                            self.Loader.hide().then(resolve);
                        });
                    });
    
                    return self.$openCategory();
    
             * open the comments
             *
             * @return {Promise<Promise>}
    
            openComments: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                const self = this;
    
                this.Loader.show();
                this.getCategory('comments').setActive();
    
    
                return this.$closeCategory().then(function() {
    
                    self.refreshComments();
    
                    return self.$openCategory();
    
                    self.Loader.hide();
                });
    
             * Refresh the comment display
    
            refreshComments: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                const Container = this.getContent().getElement('.container');
    
                Container.set('html', '');
    
                new QUIButton({
                    textimage: 'fa fa-comments',
    
    Henning Leutz's avatar
    Henning Leutz committed
                    text: QUILocale.get(lg, 'invoice.panel.comment.add'),
                    styles: {
                        'float': 'right',
    
                        marginBottom: 10
                    },
    
    Henning Leutz's avatar
    Henning Leutz committed
                    events: {
    
                        onClick: this.openAddCommentDialog
                    }
                }).inject(Container);
    
                new Comments({
                    comments: this.getAttribute('comments')
                }).inject(Container);
    
            /**
             * Open invoice file management
             *
             * @returns {Promise}
             */
    
            openInvoiceFiles: function() {
    
                this.Loader.show();
    
                this.getCategory('invoiceFiles').setActive();
    
                return this.$closeCategory().then((Container) => {
                    Container.setStyle('overflow', 'hidden');
                    Container.setStyle('padding', 20);
                    Container.setStyle('height', '100%');
    
                    const customerId = this.getAttribute('customer_id');
    
                    if (!customerId) {
                        new Element('p', {
                            html: QUILocale.get(lg, 'controls.panels.TemporaryInvoice.invoice_files_no_customer')
                        }).inject(Container);
    
                        return;
                    }
    
    
                    return new Promise((resolve) => {
                        require(['package/quiqqer/erp/bin/backend/controls/customerFiles/Grid'], (FileGrid) => {
                            new FileGrid({
                                hash: this.getAttribute('hash')
                            }).inject(Container);
    
                }).then(() => {
                    return this.$openCategory();
                }).catch((err) => {
                    console.error('ERROR');
                    console.error(err);
    
                    return this.$openCategory();
                });
            },
    
    
    Henning Leutz's avatar
    Henning Leutz committed
            /**
    
             * Open the verification category
    
             * @returns {Promise}
    
    Henning Leutz's avatar
    Henning Leutz committed
             */
    
            openVerification: function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                let ParentContainer = null,
    
    Henning Leutz's avatar
    Henning Leutz committed
                    FrameContainer = null;
    
                this.Loader.show();
    
    Henning Leutz's avatar
    Henning Leutz committed
                return this.$closeCategory().then((Container) => {
    
                    FrameContainer = new Element('div', {
                        'class': 'quiqqer-invoice-backend-temporaryInvoice-previewContainer'
                    }).inject(Container);
    
                    Container.setStyle('overflow', 'hidden');
                    Container.setStyle('padding', 0);
                    Container.setStyle('height', '100%');
    
                    ParentContainer = Container;
    
                    return Invoices.getTemporaryInvoicePreview(
    
    Henning Leutz's avatar
    Henning Leutz committed
                        self.getAttribute('hash'),
    
                        self.getCurrentData()
    
                    ).then(function(html) {
    
                        return new Promise(function(resolve) {
                            require(['qui/controls/elements/Sandbox'], function(Sandbox) {
    
                                new Sandbox({
                                    content: html,
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    styles: {
                                        height: '100%',
    
                                        padding: 20,
    
    Henning Leutz's avatar
    Henning Leutz committed
                                        width: '95%'
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    events: {
    
                                        onLoad: function(Box) {
    
                                            Box.getElm().addClass('quiqqer-invoice-backend-temporaryInvoice-preview');
                                        }
                                    }
                                }).inject(FrameContainer);
    
                                resolve();
                            });
                        });
                    });
    
                    // check invoice date
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const Now = new Date();
    
                    Now.setHours(0, 0, 0, 0);
    
    
    Henning Leutz's avatar
    Henning Leutz committed
                    let InvoiceDate = new Date(self.getAttribute('date'));
    
    
                    if (InvoiceDate < Now) {
                        new QUIConfirm({
    
    Henning Leutz's avatar
    Henning Leutz committed
                            title: QUILocale.get(lg, 'window.invoice.date.past.title'),
                            text: QUILocale.get(lg, 'window.invoice.date.past.title'),
                            information: QUILocale.get(lg, 'window.invoice.date.past.content'),
                            icon: 'fa fa-clock-o',
                            texticon: 'fa fa-clock-o',
                            maxHeight: 400,
                            maxWidth: 600,
                            autoclose: false,
    
                            cancel_button: {
    
    Henning Leutz's avatar
    Henning Leutz committed
                                text: QUILocale.get(lg, 'window.invoice.date.past.cancel.text'),
    
                                textimage: 'fa fa-close'
                            },
    
    Henning Leutz's avatar
    Henning Leutz committed
                            ok_button: {
                                text: QUILocale.get(lg, 'window.invoice.date.past.ok.text'),
    
                                textimage: 'fa fa-check'
                            },
    
    Henning Leutz's avatar
    Henning Leutz committed
                            events: {
    
                                onSubmit: function(Win) {
    
                                    Win.Loader.show();
    
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    let Today = new Date();
                                    let today = Today.toISOString().split('T')[0];
    
    
                                    self.setAttribute('date', today + ' 00:00:00');
    
    
                                    self.save().then(function() {
    
                                        self.openVerification();
                                        Win.close();
                                    });
                                }
                            }
                        }).open();
                    }
    
                }).then(function() {
                    return Invoices.getMissingAttributes(self.getAttribute('hash'));
                }).then(function(missing) {
    
    Henning Leutz's avatar
    Henning Leutz committed
                    const Missing = new Element('div', {
    
                        'class': 'quiqqer-invoice-backend-temporaryInvoice-missing',
    
    Henning Leutz's avatar
    Henning Leutz committed
                        styles: {
    
                            opacity: 0,
    
    Henning Leutz's avatar
    Henning Leutz committed
                            bottom: -20
    
                        }
                    }).inject(ParentContainer);
    
                    if (Object.getLength(missing)) {
                        Missing.set('html', Mustache.render(templateMissing, {
                            message: QUILocale.get(lg, 'message.invoice.missing')
                        }));
    
    
    Henning Leutz's avatar
    Henning Leutz committed
                        const Info = new Element('info', {
    
                            'class': 'quiqqer-invoice-backend-temporaryInvoice-missing-miss-message',
    
    Henning Leutz's avatar
    Henning Leutz committed
                            styles: {
    
                                display: 'none',
                                opacity: 0
                            }
                        }).inject(ParentContainer);
    
                        Missing.getElement(
                            '.quiqqer-invoice-backend-temporaryInvoice-missing-miss-button'
    
                        ).addEvent('click', function() {
    
    Henning Leutz's avatar
    Henning Leutz committed
                            let isShow = parseInt(Info.getStyle('opacity'));
    
    
                            if (isShow) {
                                moofx(Info).animate({
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    bottom: 60,
    
                                    opacity: 0
                                }, {
    
                                    callback: function() {
    
                                        Info.setStyle('display', 'none');
                                    }
                                });
                            } else {
                                Info.setStyle('display', null);
    
                                moofx(Info).animate({
    
    Henning Leutz's avatar
    Henning Leutz committed
                                    bottom: 80,
    
                                    opacity: 1
                                });
                            }
                        });
    
    Henning Leutz's avatar
    Henning Leutz committed
                        for (let missed in missing) {