From 3babd48a7f66388eb0a975deed953af1a8033ddf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Patrick=20M=C3=BCller?= <p.mueller@pcsg.de>
Date: Tue, 5 Apr 2022 15:32:40 +0200
Subject: [PATCH] refactor: improved invoice customer files handling

---
 ajax/invoices/setCustomerFiles.php            | 18 ++---
 bin/backend/classes/Invoices.js               |  6 +-
 bin/backend/controls/panels/Invoice.js        | 76 +++++++++----------
 .../controls/panels/TemporaryInvoice.js       |  4 +-
 locale.xml                                    |  4 +
 .../ERP/Accounting/Invoice/EventHandler.php   | 10 +++
 6 files changed, 65 insertions(+), 53 deletions(-)

diff --git a/ajax/invoices/setCustomerFiles.php b/ajax/invoices/setCustomerFiles.php
index 855ede6..da7ddd4 100644
--- a/ajax/invoices/setCustomerFiles.php
+++ b/ajax/invoices/setCustomerFiles.php
@@ -1,29 +1,25 @@
 <?php
 
 /**
- * This file contains package_quiqqer_invoice_ajax_invoices_setStatus
- */
-
-/**
- * set a status to the invoice
+ * Set customer files to an invoice.
  *
- * @param string $invoiceId - ID of the invoice
- * @param string $status - new status
+ * @param string $invoiceHash
+ * @param array $customerFiles
  *
- * @return string|integer
+ * @return void
  */
 QUI::$Ajax->registerFunction(
     'package_quiqqer_invoice_ajax_invoices_setCustomerFiles',
-    function ($invoiceId, $customerFiles) {
+    function ($invoiceHash, $customerFiles) {
         $customerFiles = \json_decode($customerFiles, true);
 
-        $Invoice = QUI\ERP\Accounting\Invoice\Utils\Invoice::getInvoiceByString($invoiceId);
+        $Invoice = QUI\ERP\Accounting\Invoice\Utils\Invoice::getInvoiceByString($invoiceHash);
         $Invoice->clearCustomerFiles();
 
         foreach ($customerFiles as $customerFile) {
             $Invoice->addCustomerFile($customerFile['hash'], $customerFile['options']);
         }
     },
-    ['invoiceId', 'customerFiles'],
+    ['invoiceHash', 'customerFiles'],
     'Permission::checkAdminUser'
 );
diff --git a/bin/backend/classes/Invoices.js b/bin/backend/classes/Invoices.js
index 223b8f3..5307e3a 100644
--- a/bin/backend/classes/Invoices.js
+++ b/bin/backend/classes/Invoices.js
@@ -642,15 +642,15 @@ define('package/quiqqer/invoice/bin/backend/classes/Invoices', [
         /**
          * Set invoice customer files
          *
-         * @param {Number} invoiceId
+         * @param {String} invoiceHash
          * @param {String} customerFiles (JSON)
          * @return {Promise}
          */
-        setCustomerFiles: function (invoiceId, customerFiles) {
+        setCustomerFiles: function (invoiceHash, customerFiles) {
             return new Promise(function (resolve, reject) {
                 QUIAjax.post('package_quiqqer_invoice_ajax_invoices_setCustomerFiles', resolve, {
                     'package'    : 'quiqqer/invoice',
-                    invoiceId    : invoiceId,
+                    invoiceHash  : invoiceHash,
                     customerFiles: customerFiles,
                     onError      : reject,
                     showError    : false
diff --git a/bin/backend/controls/panels/Invoice.js b/bin/backend/controls/panels/Invoice.js
index ada34bf..f30bae4 100644
--- a/bin/backend/controls/panels/Invoice.js
+++ b/bin/backend/controls/panels/Invoice.js
@@ -284,7 +284,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
                         continue;
                     }
 
-                    cat = categories[category];
+                    cat   = categories[category];
                     title = cat.title;
 
                     this.addCategory({
@@ -410,7 +410,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
          * show the lock message window
          */
         $showLockMessage: function () {
-            const self = this;
+            const self  = this;
             let btnText = QUILocale.get('quiqqer/quiqqer', 'submit');
 
             if (window.USER.isSU) {
@@ -583,31 +583,31 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
                             data = {};
                         }
 
-                        data.textInvoiceStatus = QUILocale.get(lg, 'invoice.settings.processingStatus.title');
+                        data.textInvoiceStatus    = QUILocale.get(lg, 'invoice.settings.processingStatus.title');
                         data.textInvoiceRecipient = QUILocale.get(lg, 'cutomerData');
-                        data.textCustomer = QUILocale.get(lg, 'customer');
-                        data.textCompany = QUILocale.get(lg, 'company');
-                        data.textStreet = QUILocale.get(lg, 'street');
-                        data.textZip = QUILocale.get(lg, 'zip');
-                        data.textCity = QUILocale.get(lg, 'city');
+                        data.textCustomer         = QUILocale.get(lg, 'customer');
+                        data.textCompany          = QUILocale.get(lg, 'company');
+                        data.textStreet           = QUILocale.get(lg, 'street');
+                        data.textZip              = QUILocale.get(lg, 'zip');
+                        data.textCity             = QUILocale.get(lg, 'city');
 
                         data.textInvoiceDelivery = QUILocale.get(lg, 'deliveryAddress');
                         data.textDeliveryCompany = QUILocale.get(lg, 'company');
-                        data.textDeliveryStreet = QUILocale.get(lg, 'street');
-                        data.textDeliveryZip = QUILocale.get(lg, 'zip');
-                        data.textDeliveryCity = QUILocale.get(lg, 'city');
+                        data.textDeliveryStreet  = QUILocale.get(lg, 'street');
+                        data.textDeliveryZip     = QUILocale.get(lg, 'zip');
+                        data.textDeliveryCity    = QUILocale.get(lg, 'city');
                         data.textDeliveryCountry = QUILocale.get(lg, 'country');
 
-                        data.textInvoiceData = QUILocale.get(lg, 'erp.panel.invoice.data.title');
-                        data.textInvoiceDate = QUILocale.get(lg, 'erp.panel.invoice.data.date');
-                        data.textProjectName = QUILocale.get(lg, 'erp.panel.invoice.data.projectName');
-                        data.textOrderedBy = QUILocale.get(lg, 'erp.panel.invoice.data.orderedBy');
-                        data.textEditor = QUILocale.get(lg, 'erp.panel.invoice.data.editor');
+                        data.textInvoiceData   = QUILocale.get(lg, 'erp.panel.invoice.data.title');
+                        data.textInvoiceDate   = QUILocale.get(lg, 'erp.panel.invoice.data.date');
+                        data.textProjectName   = QUILocale.get(lg, 'erp.panel.invoice.data.projectName');
+                        data.textOrderedBy     = QUILocale.get(lg, 'erp.panel.invoice.data.orderedBy');
+                        data.textEditor        = QUILocale.get(lg, 'erp.panel.invoice.data.editor');
                         data.textContactPerson = QUILocale.get(lg, 'erp.panel.invoice.data.contactPerson');
 
-                        data.textInvoicePayment = QUILocale.get(lg, 'erp.panel.invoice.data.payment');
+                        data.textInvoicePayment       = QUILocale.get(lg, 'erp.panel.invoice.data.payment');
                         data.textInvoicePaymentMethod = QUILocale.get(lg, 'erp.panel.invoice.data.paymentMethod');
-                        data.textTermOfPayment = QUILocale.get(lg, 'erp.panel.invoice.data.termOfPayment');
+                        data.textTermOfPayment        = QUILocale.get(lg, 'erp.panel.invoice.data.termOfPayment');
 
                         data.textInvoiceText = QUILocale.get(lg, 'erp.panel.invoice.data.invoiceText');
 
@@ -619,18 +619,18 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
                             html: Mustache.render(template, data)
                         });
 
-                        const Form = Container.getElement('form');
+                        const Form  = Container.getElement('form');
                         let address = {};
 
                         try {
                             address = JSON.decode(data.invoice_address);
 
-                            Form.elements.customer.value =
+                            Form.elements.customer.value  =
                                 address.salutation + ' ' + address.firstname + ' ' + address.lastname;
-                            Form.elements.company.value = address.company;
+                            Form.elements.company.value   = address.company;
                             Form.elements.street_no.value = address.street_no;
-                            Form.elements.zip.value = address.zip;
-                            Form.elements.city.value = address.city;
+                            Form.elements.zip.value       = address.zip;
+                            Form.elements.city.value      = address.city;
                         } catch (e) {
                             console.error(e);
                         }
@@ -665,13 +665,13 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
                                 }
 
                                 Form.elements['delivery-customer'].value = deliveryAddress.salutation + ' ' +
-                                                                           deliveryAddress.firstname + ' ' +
-                                                                           deliveryAddress.lastname;
+                                    deliveryAddress.firstname + ' ' +
+                                    deliveryAddress.lastname;
 
-                                Form.elements['delivery-company'].value = deliveryAddress.company;
+                                Form.elements['delivery-company'].value   = deliveryAddress.company;
                                 Form.elements['delivery-street_no'].value = deliveryAddress.street_no;
-                                Form.elements['delivery-zip'].value = deliveryAddress.zip;
-                                Form.elements['delivery-city'].value = deliveryAddress.city;
+                                Form.elements['delivery-zip'].value       = deliveryAddress.zip;
+                                Form.elements['delivery-city'].value      = deliveryAddress.city;
                             } catch (e) {
                                 console.error(e);
                             }
@@ -852,7 +852,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
             this.getCategory('invoiceFiles').setActive();
 
             const InvoiceAttributes = this.getAttribute('data');
-            let InvoiceData = InvoiceAttributes.data;
+            let InvoiceData         = InvoiceAttributes.data;
 
             if (InvoiceData) {
                 InvoiceData = JSON.decode(InvoiceData);
@@ -878,19 +878,19 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/Invoice', [
                     confirmItemDelete: true,
                     events           : {
                         onChange: (FileSelectControl) => {
-                            const customerFiles = FileSelectControl.getValue();
-
                             this.Loader.show();
 
-                            Invoices.setCustomerFiles(this.getAttribute('invoiceId'), customerFiles).then(() => {
-                                InvoiceData.customer_files = customerFiles;
+                            FileSelectControl.getFiles().then((customerFiles) => {
+                                Invoices.setCustomerFiles(this.getAttribute('data').hash, customerFiles).then(() => {
+                                    InvoiceData.customer_files = customerFiles;
 
-                                InvoiceAttributes.data = JSON.encode(InvoiceData);
-                                this.setAttribute('data', InvoiceAttributes);
+                                    InvoiceAttributes.data = JSON.encode(InvoiceData);
+                                    this.setAttribute('data', InvoiceAttributes);
 
-                                this.Loader.hide();
-                            }).catch(() => {
-                                this.Loader.hide();
+                                    this.Loader.hide();
+                                }).catch(() => {
+                                    this.Loader.hide();
+                                });
                             });
                         }
                     }
diff --git a/bin/backend/controls/panels/TemporaryInvoice.js b/bin/backend/controls/panels/TemporaryInvoice.js
index 30a636a..c8d4fe0 100644
--- a/bin/backend/controls/panels/TemporaryInvoice.js
+++ b/bin/backend/controls/panels/TemporaryInvoice.js
@@ -774,7 +774,9 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                     confirmItemDelete: true,
                     events           : {
                         onChange: (FileSelectControl) => {
-                            this.setAttribute('attached_customer_files', FileSelectControl.getValue());
+                            FileSelectControl.getFiles().then((customerFiles) => {
+                                this.setAttribute('attached_customer_files', customerFiles);
+                            });
                         }
                     }
                 }).inject(Container);
diff --git a/locale.xml b/locale.xml
index 4e061e8..03a0e8a 100644
--- a/locale.xml
+++ b/locale.xml
@@ -1661,6 +1661,10 @@
             <en>
                 <![CDATA[The invoice does not have an assigned customer yet. Please assign a customer to the invoice first before assigning customer files to the invoice.]]></en>
         </locale>
+        <locale name="exception.Invoice.addCustomerFile.file_not_found">
+            <de><![CDATA[Diese Datei ist noch nicht in den Kunden-Dateien hochgeladen und kann der Rechnung daher nicht hinzugefügt werden.]]></de>
+            <en><![CDATA[This file is not yet uploaded in the customer files and therefore cannot be added to the invoice.]]></en>
+        </locale>
 
         <locale name="RestApi.Provider.invoice.comment.source">
             <de><![CDATA[Rechnung erstellt über REST API. Herkunft: [source]]]></de>
diff --git a/src/QUI/ERP/Accounting/Invoice/EventHandler.php b/src/QUI/ERP/Accounting/Invoice/EventHandler.php
index 24d3079..7444834 100644
--- a/src/QUI/ERP/Accounting/Invoice/EventHandler.php
+++ b/src/QUI/ERP/Accounting/Invoice/EventHandler.php
@@ -292,6 +292,16 @@ public static function onQuiqqerErpOutputSendMailBefore(
         string $recipient,
         QUI\Mail\Mailer $Mailer
     ) {
+        $allowedEntityTypes = [
+            OutputProviderInvoice::getEntityType(),
+            OutputProviderCancelled::getEntityType(),
+            OutputProviderCreditNote::getEntityType()
+        ];
+
+        if (!\in_array($entityType, $allowedEntityTypes)) {
+            return;
+        }
+
         try {
             $Invoice = OutputProviderInvoice::getEntity($entityId);
         } catch (\Exception $Exception) {
-- 
GitLab