From 2f6fd212b67a8561b5514888b6539f653bdc854a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Patrick=20M=C3=BCller?= <p.mueller@pcsg.de>
Date: Wed, 9 Jun 2021 10:44:54 +0200
Subject: [PATCH] temp commit

---
 composer.json                            | 48 ++++++------
 events.xml                               |  8 ++
 locale.xml                               | 35 ++++++---
 src/QUI/ERP/Coupons/Events.php           | 58 +++++++++++++++
 src/QUI/ERP/Coupons/Products/Handler.php | 95 +++++++++++++++---------
 5 files changed, 173 insertions(+), 71 deletions(-)

diff --git a/composer.json b/composer.json
index 9a9e1f9..3b95539 100644
--- a/composer.json
+++ b/composer.json
@@ -1,27 +1,27 @@
 {
-    "name": "quiqqer\/coupons",
-    "type": "quiqqer-module",
-    "description": "Coupons for QUIQQER",
-    "license": "GPL-3.0+",
-    "authors": [
-        {
-            "name": "Patrick M\u00fcller",
-            "email": "support@pcsg.de",
-            "homepage": "http:\/\/www.pcsg.de",
-            "role": "Developer"
-        }
-    ],
-    "support": {
-        "email": "support@pcsg.de"
-    },
-    "require": {
-        "quiqqer\/quiqqer": "^1.2|*@dev",
-        "quiqqer\/discount": "^1|*@dev",
-        "quiqqer/products": "^1.3|*@dev"
-    },
-    "autoload": {
-        "psr-4": {
-            "QUI\\ERP\\Coupons\\": "src\/QUI\/ERP\/Coupons"
-        }
+  "name": "quiqqer\/coupons",
+  "type": "quiqqer-module",
+  "description": "Coupons for QUIQQER",
+  "license": "GPL-3.0+",
+  "authors": [
+    {
+      "name": "Patrick M\u00fcller",
+      "email": "support@pcsg.de",
+      "homepage": "https:\/\/www.pcsg.de",
+      "role": "Developer"
     }
+  ],
+  "support": {
+    "email": "support@pcsg.de"
+  },
+  "require": {
+    "quiqqer\/quiqqer": "^1.2|*@dev",
+    "quiqqer\/discount": "^1.1|*@dev",
+    "quiqqer/products": "^1.3|*@dev"
+  },
+  "autoload": {
+    "psr-4": {
+      "QUI\\ERP\\Coupons\\": "src\/QUI\/ERP\/Coupons"
+    }
+  }
 }
diff --git a/events.xml b/events.xml
index eee1145..6abc225 100644
--- a/events.xml
+++ b/events.xml
@@ -36,4 +36,12 @@
            fire="\QUI\ERP\Coupons\Events::onQuiqqerOrderBasketRemovePos"
     />
 
+    <event on="onQuiqqerOrderOrderProcessGetBodyBegin"
+           fire="\QUI\ERP\Coupons\Events::onQuiqqerOrderOrderProcessGetBodyBegin"
+    />
+
+    <event on="onQuiqqerOrderBasketToOrderBegin"
+           fire="\QUI\ERP\Coupons\Events::onQuiqqerOrderBasketToOrderBegin"
+    />
+
 </events>
diff --git a/locale.xml b/locale.xml
index a6ddf62..1389baf 100644
--- a/locale.xml
+++ b/locale.xml
@@ -89,15 +89,15 @@
     </groups>
 
     <groups name="quiqqer/coupons" datatype="php">
-        
-        <locale name="Coupon.mail.subject">
+
+        <locale name="ProductCoupon.mail.subject">
             <de><![CDATA[Ihr persönlicher Gutschein-Code]]></de>
             <en><![CDATA[Your personal coupon code]]></en>
         </locale>
-        <locale name="Coupon.mail.body">
+        <locale name="ProductCoupon.mail.body">
             <de><![CDATA[
 <p>Hallo [customerName],</p>
-<p>vielen Dank für Ihren Gutschein-Einkauf. Hiermit erhalten Sie Ihren exklusiven Gutschein-Code für "[couponDescription]".</p>
+<p>vielen Dank für Ihren Gutschein-Einkauf. Hiermit erhalten Sie Ihren exklusiven Gutschein-Code für "[productTitle]".</p>
 <p>
 <b>Gutschein-Code:</b> [couponCode]<br/>
 <b>Wert:</b> [discountAmountFormatted]<br/>
@@ -105,6 +105,7 @@
 <b>Einlösbar bis:</b> [validUntilDateFormatted]<br/>
 </p>
 <p>[transferableInfo]</p>
+<p>[profileDownloadInfo]</p>
 <p>
 Beste Grüße<br/>
 [company]
@@ -114,18 +115,28 @@ Beste Grüße<br/>
 
 ]]></en>
         </locale>
-        <locale name="Coupon.mail.transferable_info.is_transferable">
-            <de><![CDATA[Sie dürfen diesen Gutschein verschenken! Der Gutschein-Code ist nicht personalisiert und kann von jedem in unserem Shop eingelöst werden. Bewahren Sie ihn daher gut auf!]]></de>
+        <locale name="ProductCoupon.mail.transferable_info.is_transferable">
+            <de>
+                <![CDATA[Sie dürfen diesen Gutschein verschenken! Der Gutschein-Code ist nicht personalisiert und kann von jedem in unserem Shop eingelöst werden. Bewahren Sie ihn daher gut auf!]]></de>
             <en><![CDATA[You may give this coupn as a gift! The coupon code is not personalized and can be redeemed by anyone in our store. Therefore, keep it safe!]]></en>
         </locale>
-        <locale name="Coupon.mail.transferable_info.is_not_transferable">
-            <de><![CDATA[Bitte bachten Sie: Dieser Gutschein kann nur von Ihnen persönlich eingesetzt werden, wenn Sie in unserem Shop eingeloggt sind. Dritte können den Gutschein-Code nicht einlösen.]]></de>
+        <locale name="ProductCoupon.mail.transferable_info.is_not_transferable">
+            <de>
+                <![CDATA[Bitte bachten Sie: Dieser Gutschein kann nur von Ihnen persönlich eingesetzt werden, wenn Sie in unserem Shop eingeloggt sind. Dritte können den Gutschein-Code nicht einlösen.]]></de>
             <en><![CDATA[Please note: This voucher can only be used by you personally when you are logged in to our store. Third parties can not redeem the voucher code.]]></en>
         </locale>
+        <locale name="ProductCoupon.mail.profile_download_info">
+            <de><![CDATA[Sie finden den Gutschein als PDF-Datei im Anhang oder in Ihrem Benutzer-Profil in unserem Shop (bitte vorher einloggen).]]></de>
+            <en><![CDATA[You can find the coupon as a PDF file attached or in your user profile in our shop (please log in first).]]></en>
+        </locale>
+        <locale name="ProductCoupon.coupon_title">
+            <de><![CDATA[Produkt #[productId] aus Bestellung [orderId]]]></de>
+            <en><![CDATA[Product #[productId] from order [orderId]]]></en>
+        </locale>
 
         <locale name="DownloadProduct.pdf.filename">
-            <de><![CDATA[Gutschein_[productTitle]__[date]]]></de>
-            <en><![CDATA[Coupon_[productTitle]__[date]]]></en>
+            <de><![CDATA[[productTitle]__[date]]]></de>
+            <en><![CDATA[[productTitle]__[date]]]></en>
         </locale>
         <locale name="CouponCode.tpl.header">
             <de><![CDATA[G U T S C H E I N]]></de>
@@ -153,8 +164,8 @@ Beste Grüße<br/>
             <en><![CDATA[Coupon code [couponCode]]]></en>
         </locale>
         <locale name="Discount.default_title.product">
-            <de><![CDATA[Produkt "[productTitle]" (#[productId])]]></de>
-            <en><![CDATA[Product "[productTitle]" (#[productId])]]></en>
+            <de><![CDATA["[productTitle]"]]></de>
+            <en><![CDATA["[productTitle]"]]></en>
         </locale>
 
         <locale name="exception.ajax.create.missing_field">
diff --git a/src/QUI/ERP/Coupons/Events.php b/src/QUI/ERP/Coupons/Events.php
index 52c4269..6a1f7c3 100644
--- a/src/QUI/ERP/Coupons/Events.php
+++ b/src/QUI/ERP/Coupons/Events.php
@@ -552,4 +552,62 @@ public static function onQuiqqerOrderCreated(AbstractOrder $Order)
     {
         QUI\ERP\Coupons\Products\Handler::createCouponCodesFromOrder($Order);
     }
+
+    public static function onQuiqqerOrderBasketToOrderBegin(
+        QUI\ERP\Order\Basket\BasketOrder $BasketOrder,
+        AbstractOrder $Order,
+        array &$products
+    ) {
+        foreach ($products as $k => $product) {
+            $products[$k]['vat'] = 0;
+        }
+    }
+
+    /**
+     * quiqqer/order: onQuiqqerOrderOrderProcessGetBodyBegin
+     *
+     * Set VAT to 0% for specific coupons.
+     *
+     * @param QUI\ERP\Order\OrderProcess $OrderProcess
+     * @return void
+     */
+    public static function onQuiqqerOrderOrderProcessGetBodyBegin(QUI\ERP\Order\OrderProcess $OrderProcess)
+    {
+        try {
+            $Order = $OrderProcess->getOrder();
+        } catch (\Exception $Exception) {
+            QUI\System\Log::writeException($Exception);
+            return;
+        }
+
+        if (empty($Order)) {
+            return;
+        }
+//
+//        $OrderBasket = new QUI\ERP\Order\Basket\BasketOrder($Order->getHash());
+//
+//        foreach ($OrderBasket->get)
+
+        $Articles     = $Order->getArticles();
+        $articleStock = [];
+
+        /** @var QUI\ERP\Accounting\Article $Article */
+        foreach ($Articles as $Article) {
+            try {
+                // Do not parse coupon codes / discounts
+                if (empty($Article->getId()) || !\is_numeric($Article->getId())) {
+                    continue;
+                }
+
+                $Product = Products::getProduct($Article->getId());
+
+                if ($Product instanceof CouponProductType) {
+
+                }
+            } catch (\Exception $Exception) {
+                QUI\System\Log::writeDebugException($Exception);
+                continue;
+            }
+        }
+    }
 }
diff --git a/src/QUI/ERP/Coupons/Products/Handler.php b/src/QUI/ERP/Coupons/Products/Handler.php
index 90468b6..43f3723 100644
--- a/src/QUI/ERP/Coupons/Products/Handler.php
+++ b/src/QUI/ERP/Coupons/Products/Handler.php
@@ -46,26 +46,41 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
                     continue;
                 }
 
-                $CouponCode    = self::createCouponCodeFromProduct($Product, $Customer);
-                $couponPdfFile = null;
+                $CouponCode                = self::createCouponCodeFromProduct($Product, $Order, $Customer);
+                $couponFilePathCustomerDir = null;
 
                 // Generate coupon PDF
                 if ($Product->getFieldValue(CouponProductType::PRODUCT_FIELD_ID_GENERATE_PDF)) {
                     $couponPdfFile = self::createCouponCodePdf($CouponCode, $Product);
 
-                    // Add PDF file to customer files
-                    CustomerFiles::addFileToCustomer($Customer->getId(), $couponPdfFile);
+                    // Rename file
+                    $productTitelSanitized = preg_replace("/[^\p{L}\p{N} ]/ui", '', $Product->getTitle());
+
+                    $fileName = QUI::getLocale()->get(
+                        'quiqqer/coupons',
+                        'DownloadProduct.pdf.filename',
+                        [
+                            'productTitle' => \str_replace(' ', '_', $productTitelSanitized),
+                            'date'         => \date('Y_m_d')
+                        ]
+                    );
 
-                    \unlink($couponPdfFile);
+                    $fileName .= '__'.\mb_substr($Order->getHash(), 0, 6);
 
-                    $customerDir     = CustomerFiles::getFolderPath($Customer);
-                    $pdfFileCustomer = $customerDir.DIRECTORY_SEPARATOR.\basename($couponPdfFile, '.pdf');
+                    $newCouponPdfFile = \str_replace(\basename($couponPdfFile, '.pdf'), $fileName, $couponPdfFile);
 
-                    CustomerFiles::addFileToDownloadEntry($Customer->getId(), $pdfFileCustomer);
+                    \rename($couponPdfFile, $newCouponPdfFile);
+
+                    // Add PDF file to customer files
+                    CustomerFiles::addFileToCustomer($Customer->getId(), $newCouponPdfFile);
+                    CustomerFiles::addFileToDownloadEntry($Customer->getId(), \basename($newCouponPdfFile));
+
+                    $customerDir               = CustomerFiles::getFolderPath($Customer);
+                    $couponFilePathCustomerDir = $customerDir.DIRECTORY_SEPARATOR.\basename($newCouponPdfFile);
                 }
 
                 // Send coupon via email
-                self::sendCouponMail($CouponCode, $Product, $Customer, $couponPdfFile);
+                self::sendCouponMail($CouponCode, $Product, $Customer, $couponFilePathCustomerDir);
             } catch (\Exception $Exception) {
                 if ($Exception->getCode() === 404) {
                     QUI\System\Log::writeDebugException($Exception);
@@ -80,16 +95,28 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
      * Create coupon codes from an order
      *
      * @param Product $Product
+     * @param QUI\ERP\Order\AbstractOrder $Order
      * @param QUI\Interfaces\Users\User $User - The user that bought the product
      * @return CouponCode
      *
      * @throws QUI\Exception
      * @throws \Exception
      */
-    protected static function createCouponCodeFromProduct(Product $Product, QUI\Interfaces\Users\User $User): CouponCode
-    {
+    protected static function createCouponCodeFromProduct(
+        Product $Product,
+        QUI\ERP\Order\AbstractOrder $Order,
+        QUI\Interfaces\Users\User $User
+    ): CouponCode {
         $Discount         = self::createDiscountFromProduct($Product);
         $couponAttributes = [
+            'title'     => QUI::getSystemLocale()->get(
+                'quiqqer/coupons',
+                'ProductCoupon.coupon_title',
+                [
+                    'orderId'   => $Order->getPrefixedId(),
+                    'productId' => $Product->getId()
+                ]
+            ),
             'maxUsages' => CouponsHandler::MAX_USAGE_ONCE
         ];
 
@@ -170,18 +197,7 @@ protected static function createDiscountFromProduct(Product $Product): Discount
      */
     public static function createCouponCodePdf(CouponCode $CouponCode, Product $Product): string
     {
-        $fileName = QUI::getLocale()->get(
-            'quiqqer/coupons',
-            'DownloadProduct.pdf.filename',
-            [
-                'productTitle' => \str_replace(' ', '_', $Product->getTitle()),
-                'date'         => \date('Y_m_d')
-            ]
-        );
-
-        $Document = new Document([
-            'filename' => $fileName.'.pdf',
-        ]);
+        $Document = new Document();
 
 //        $Document->setAttribute('foldingMarks', true);
         $Document->setAttribute('disableSmartShrinking', true);
@@ -190,6 +206,7 @@ public static function createCouponCodePdf(CouponCode $CouponCode, Product $Prod
         $Document->setAttribute('marginBottom', 40);
         $Document->setAttribute('marginLeft', 0);
         $Document->setAttribute('marginRight', 0);
+        $Document->setAttribute('showPageNumbers', false);
 
         $Engine = QUI::getTemplateManager()->getEngine();
 
@@ -243,42 +260,49 @@ public static function sendCouponMail(
 
         $Mailer = QUI::getMailManager()->getMailer();
         $Mailer->addRecipient($recipient);
-
-        $Mailer->setSubject(QUI::getLocale()->get('quiqqer/coupons', 'Coupon.mail.subject'));
+        $Mailer->setSubject(QUI::getLocale()->get('quiqqer/coupons', 'ProductCoupon.mail.subject'));
 
         $couponViewData = self::getCouponViewData($CouponCode, $Product);
 
         if ($couponViewData['isTransferable']) {
             $transferableInfo = QUI::getLocale()->get(
                 'quiqqer/coupons',
-                'Coupon.mail.transferable_info.is_transferable'
+                'ProductCoupon.mail.transferable_info.is_transferable'
             );
         } else {
             $transferableInfo = QUI::getLocale()->get(
                 'quiqqer/coupons',
-                'Coupon.mail.transferable_info.is_not_transferable'
+                'ProductCoupon.mail.transferable_info.is_not_transferable'
+            );
+        }
+
+        $profileDownloadInfo = '';
+
+        if ($couponPdfFile) {
+            $Mailer->addAttachment($couponPdfFile);
+
+            $profileDownloadInfo = QUI::getLocale()->get(
+                'quiqqer/coupons',
+                'ProductCoupon.mail.profile_download_info'
             );
         }
 
         $Mailer->setBody(
             QUI::getLocale()->get(
                 'quiqqer/coupons',
-                'Coupon.mail.body',
+                'ProductCoupon.mail.body',
                 \array_merge(
                     $couponViewData,
                     [
-                        'customerName'     => $Customer->getName(),
-                        'company'          => QUI\ERP\Defaults::conf('company', 'name'),
-                        'transferableInfo' => $transferableInfo
+                        'customerName'        => $Customer->getName(),
+                        'company'             => QUI\ERP\Defaults::conf('company', 'name'),
+                        'transferableInfo'    => $transferableInfo,
+                        'profileDownloadInfo' => $profileDownloadInfo
                     ]
                 )
             )
         );
 
-        if ($couponPdfFile) {
-            $Mailer->addAttachment($couponPdfFile);
-        }
-
         $Mailer->send();
     }
 
@@ -324,6 +348,7 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro
         return [
             'isTransferable'          => empty($User),
             'couponCode'              => $CouponCode->getCode(),
+            'productTitle'            => $Product->getTitle(),
             'userName'                => $User ? $User->getName() : false,
             'couponDescription'       => $Product->getFieldValueByLocale(
                 CouponProductType::PRODUCT_FIELD_ID_COUPON_DESCRIPTION
-- 
GitLab