From c274f52b52001b983ddb294c0726f15806d64fef Mon Sep 17 00:00:00 2001
From: Henning Leutz <leutz@pcsg.de>
Date: Mon, 31 May 2021 15:16:26 +0200
Subject: [PATCH] feat: quiqqer/erp#70

---
 ajax/invoices/temporary/get.php               |  2 +
 ajax/invoices/temporary/save.php              |  6 +++
 .../panels/TemporaryInvoice.Data.html         | 14 +++++-
 .../controls/panels/TemporaryInvoice.js       | 49 ++++++++++++++++---
 .../Accounting/Invoice/InvoiceTemporary.php   | 20 +++++++-
 5 files changed, 80 insertions(+), 11 deletions(-)

diff --git a/ajax/invoices/temporary/get.php b/ajax/invoices/temporary/get.php
index bb2a5e2..ea1ffe0 100644
--- a/ajax/invoices/temporary/get.php
+++ b/ajax/invoices/temporary/get.php
@@ -21,6 +21,8 @@ function ($invoiceId) {
             $invoice['invoice_address'] = \json_decode($invoice['invoice_address'], true);
         }
 
+        $invoice['currencyRate'] = $Invoice->getCurrency()->getExchangeRate();
+
         return $invoice;
     },
     ['invoiceId'],
diff --git a/ajax/invoices/temporary/save.php b/ajax/invoices/temporary/save.php
index 29893d4..04b66cb 100644
--- a/ajax/invoices/temporary/save.php
+++ b/ajax/invoices/temporary/save.php
@@ -48,6 +48,12 @@ function ($invoiceId, $data) {
             $Invoice->setCurrency($data['currency']);
         }
 
+        if (!empty($data['currencyRate'])) {
+            $Currency = $Invoice->getCurrency();
+            $Currency->setExchangeRate(\floatval($data['currencyRate']));
+            $Invoice->setCurrency($Currency);
+        }
+
         $Invoice->setAttribute('invoice_address', false); // needed because of address reset
         $Invoice->setAttributes($data);
         $Invoice->save();
diff --git a/bin/backend/controls/panels/TemporaryInvoice.Data.html b/bin/backend/controls/panels/TemporaryInvoice.Data.html
index 4b059b0..a96e682 100644
--- a/bin/backend/controls/panels/TemporaryInvoice.Data.html
+++ b/bin/backend/controls/panels/TemporaryInvoice.Data.html
@@ -139,7 +139,17 @@
                 </label>
             </td>
         </tr>
-        <tr class="currency-row">
+        </tbody>
+    </table>
+
+    <table class="data-table data-table-flexbox invoice-data invoice-currency">
+        <thead>
+        <tr>
+            <th>{{textInvoiceCurrency}}</th>
+        </tr>
+        </thead>
+        <tbody>
+        <tr>
             <td>
                 <label class="field-container">
                     <span class="field-container-item" title="{{textCurrency}}">
@@ -152,7 +162,7 @@
                 </label>
             </td>
         </tr>
-        <tr class="currency-row">
+        <tr>
             <td>
                 <label class="field-container">
                     <span class="field-container-item" title="{{textCurrencyRate}}">
diff --git a/bin/backend/controls/panels/TemporaryInvoice.js b/bin/backend/controls/panels/TemporaryInvoice.js
index 08ffb6b..432c337 100644
--- a/bin/backend/controls/panels/TemporaryInvoice.js
+++ b/bin/backend/controls/panels/TemporaryInvoice.js
@@ -278,6 +278,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                 payment_method         : this.getAttribute('payment_method'),
                 additional_invoice_text: this.getAttribute('additional_invoice_text'),
                 currency               : this.getAttribute('currency'),
+                currencyRate           : this.getAttribute('currencyRate'),
                 addressDelivery        : deliveryAddress,
                 processing_status      : this.getAttribute('processing_status')
             };
@@ -330,7 +331,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                         textCurrency    : QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textCurrency'),
                         textCurrencyRate: QUILocale.get(lg, 'erp.panel.temporary.invoice.category.data.textCurrencyRate'),
 
-                        textInvoiceDeliveryAddress: QUILocale.get(lg, 'deliveryAddress'),
+                        textInvoiceDeliveryAddress: QUILocale.get(lg, 'deliveryAddress')
                     })
                 });
 
@@ -351,7 +352,8 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                     editor_id        : self.getAttribute('editor_id'),
                     processing_status: self.getAttribute('processing_status'),
                     contact_person   : self.getAttribute('contact_person'),
-                    currency         : self.getAttribute('currency')
+                    currency         : self.getAttribute('currency'),
+                    currencyRate     : self.getAttribute('currencyRate')
                 }, Form);
 
                 Form.elements.date.set('disabled', true);
@@ -388,11 +390,16 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                 return new Promise(function (resolve, reject) {
                     var Form = self.getContent().getElement('form');
 
-                    require(['utils/Controls'], function (ControlUtils) {
-                        ControlUtils.parse(Form).then(resolve);
+                    require([
+                        'Packages',
+                        'utils/Controls'
+                    ], function (Packages, ControlUtils) {
+                        ControlUtils.parse(Form).then(function () {
+                            return Packages.getConfig('quiqqer/currency');
+                        }).then(resolve);
                     }, reject);
                 });
-            }).then(function () {
+            }).then(function (config) {
                 var Content = self.getContent();
 
                 var quiId = Content.getElement(
@@ -402,12 +409,17 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                 var editorIdQUIId    = Content.getElement('[name="editorId"]').get('data-quiid');
                 var orderedByIdQUIId = Content.getElement('[name="orderedBy"]').get('data-quiid');
                 var currencyIdQUIId  = Content.getElement('[name="currency"]').get('data-quiid');
+                var CurrencyRate     = Content.getElement('[name="currencyRate"]');
 
                 var Data      = QUI.Controls.getById(quiId);
                 var EditorId  = QUI.Controls.getById(editorIdQUIId);
                 var OrderedBy = QUI.Controls.getById(orderedByIdQUIId);
                 var Currency  = QUI.Controls.getById(currencyIdQUIId);
 
+                if (parseInt(config.currency.differentAccountingCurrencies) === 0) {
+                    Content.getElements('table.invoice-currency').setStyle('display', 'none');
+                }
+
                 OrderedBy.setAttribute('showAddressName', false);
 
                 Data.addEvent('onChange', function () {
@@ -474,7 +486,26 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
 
                 // currency
                 Currency.addEvent('change', function (Instance, value) {
+                    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) {
+                                self.setAttribute('currencyRate', data.rate);
+                                CurrencyRate.value = data.rate;
+                            }
+
+                            self.Loader.hide();
+                        }).catch(function (err) {
+                            console.error(err);
+                            self.Loader.hide();
+                        });
+                    });
                 });
 
                 // editor
@@ -823,7 +854,7 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                             onSubmit: function (Win) {
                                 Win.Loader.show();
 
-                                var Today = new Date()
+                                var Today = new Date();
                                 var today = Today.toISOString().split('T')[0];
 
                                 self.setAttribute('date', today + ' 00:00:00');
@@ -1226,7 +1257,9 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                 'project_name',
                 'payment_method',
                 'editor_id',
-                'ordered_by'
+                'ordered_by',
+                'currencyRate',
+                'currency'
             ].each(function (entry) {
                 if (!formData.hasOwnProperty(entry)) {
                     return;
@@ -1813,6 +1846,6 @@ define('package/quiqqer/invoice/bin/backend/controls/panels/TemporaryInvoice', [
                     Dialogs.openPrintDialog(self.getAttribute('id'), entityType).then(resolve);
                 });
             });
-        },
+        }
     });
 });
diff --git a/src/QUI/ERP/Accounting/Invoice/InvoiceTemporary.php b/src/QUI/ERP/Accounting/Invoice/InvoiceTemporary.php
index d4bef34..13714a3 100644
--- a/src/QUI/ERP/Accounting/Invoice/InvoiceTemporary.php
+++ b/src/QUI/ERP/Accounting/Invoice/InvoiceTemporary.php
@@ -90,6 +90,11 @@ class InvoiceTemporary extends QUI\QDOM
      */
     protected $addressDelivery = [];
 
+    /**
+     * @var null
+     */
+    protected $Currency = null;
+
     /**
      * Invoice constructor.
      *
@@ -379,6 +384,7 @@ public function setCurrency($currency)
         }
 
         $this->setAttribute('currency_data', $currency->toArray());
+        $this->Currency = null;
     }
 
     /**
@@ -390,6 +396,10 @@ public function setCurrency($currency)
      */
     public function getCurrency(): QUI\ERP\Currency\Currency
     {
+        if ($this->Currency !== null) {
+            return $this->Currency;
+        }
+
         $currency = $this->getAttribute('currency_data');
 
         if (!$currency) {
@@ -404,7 +414,15 @@ public function getCurrency(): QUI\ERP\Currency\Currency
             return QUI\ERP\Defaults::getCurrency();
         }
 
-        return QUI\ERP\Currency\Handler::getCurrency($currency['code']);
+        $Currency = QUI\ERP\Currency\Handler::getCurrency($currency['code']);
+
+        if (isset($currency['rate'])) {
+            $Currency->setExchangeRate($currency['rate']);
+        }
+
+        $this->Currency = $Currency;
+
+        return $Currency;
     }
 
     /**
-- 
GitLab