Index: /changelog
===================================================================
--- /changelog	(revision 8213)
+++ /changelog	(revision 8214)
@@ -556,4 +556,5 @@
 - Feature: PHP 8.2 kompatibilitÃ€t
 - Feature: Exportprofil kann nun stÃŒndlich mit dem Wordpress Cron ausgefÃŒhrt werden
+- Feature: Suche nach Rechnungen in Bestellverwaltung durch DatenbankÃ€nderung angepasst
 - Bugfix: ProduktgruppenÃŒbersichtsseite funktioniert ohne Lagerbestand
 - Bugfix: user_views Templates werden aus dem Child-Theme geladen
Index: /controller/wpsg_ShopController.class.php
===================================================================
--- /controller/wpsg_ShopController.class.php	(revision 8213)
+++ /controller/wpsg_ShopController.class.php	(revision 8214)
@@ -2819,9 +2819,9 @@
 				if ($bInvoice && $this->hasMod('wpsg_mod_rechnungen')) {
 
-				    $db_invoice = $this->callMod('wpsg_mod_rechnungen', 'getOrderInvoice', [$order_id]);
-
-				    if (wpsg_isSizedInt($db_invoice['id'])) {
-
-                        $arAttachment[] = $this->callMod('wpsg_mod_rechnungen', 'getDownloadFile', [intval($db_invoice['id'])]);
+                    $arInvoice = \wpsg\wpsg_invoice::findByOrderId(intval($order_id));
+
+                    foreach ($arInvoice as $oInvoice) {
+
+                        $arAttachment[] = $oInvoice->getFilePath();
 
                     }
@@ -3701,5 +3701,5 @@
 				if (!wpsg_isSizedInt($kunden_id)) {
 
-					$kunden_id = $order_data['k_id'];
+					$kunden_id = $order_data['k_id']??0;
 
 				}
@@ -3719,6 +3719,6 @@
 				}
 								
-				$arReplace['/%order_topay_brutto_formated%/i'] = wpsg_ff($order_data['topay_brutto'], $this->get_option('wpsg_currency'));
-				$arReplace['/%order_cdate_format_de%/i'] = date("d.m.Y | H:i", strtotime($order_data['cdate']));
+				$arReplace['/%order_topay_brutto_formated%/i'] = wpsg_ff($order_data['topay_brutto']??0, $this->get_option('wpsg_currency'));
+				$arReplace['/%order_cdate_format_de%/i'] = date("d.m.Y | H:i", strtotime($order_data['cdate']??'0000-00-00 00:00:00'));
 				$arReplace['/%order_done_url%/i'] = $this->getDoneURL($order_id);
  
@@ -3889,6 +3889,6 @@
 
 			/* Platzhalter fÃŒr die Warenkorbdarstellung, da es recht aufwendig ist suche ich hier vorher nach dem Vorkommen */
-			if (strpos(strtolower($value), '%basket_html%') !== false) $arReplace['/%basket_html%/i'] = $this->render(WPSG_PATH_VIEW.'/mailtemplates/html/order.phtml', false);
-			if (strpos(strtolower($value), '%basket_txt%') !== false) $arReplace['/%basket_txt%/i'] = $this->render(WPSG_PATH_VIEW.'/mailtemplates/order.phtml', false);
+			if (strpos(strtolower($value??''), '%basket_html%') !== false) $arReplace['/%basket_html%/i'] = $this->render(WPSG_PATH_VIEW.'/mailtemplates/html/order.phtml', false);
+			if (strpos(strtolower($value??''), '%basket_txt%') !== false) $arReplace['/%basket_txt%/i'] = $this->render(WPSG_PATH_VIEW.'/mailtemplates/order.phtml', false);
 
 			$revocation_form = WPSG_PATH_UPLOADS.'wpsg_revocation/'.$this->get_option('wpsg_revocationform');
@@ -3911,5 +3911,5 @@
 			if (wpsg_isSizedArray($arCustomReplace)) foreach ($arCustomReplace as $k => $v) { $arReplace[$k] = $v; }
 
-			$value = preg_replace(array_keys($arReplace), array_values($arReplace), $value);
+			$value = preg_replace(array_keys($arReplace), array_values($arReplace), $value??'');
 
 			// Sollte irgendein platzhalter mal nicht ersetzt werden denn clear ich das
Index: /lib/wpsg_basket.class.php
===================================================================
--- /lib/wpsg_basket.class.php	(revision 8213)
+++ /lib/wpsg_basket.class.php	(revision 8214)
@@ -577,7 +577,11 @@
 			        // Ich brauche das PDF von der Rechnung
                     $this->shop->callMod('wpsg_mod_rechnungen', 'writeAutoRechnung', [$oOrder->getId(), false, false]);
-                 
-                    $arAttach_Customer[] = $this->shop->callMod('wpsg_mod_rechnungen', 'getFilePathWithFilename', [$oOrder->getId()]);
-                    
+
+                    foreach (\wpsg\wpsg_invoice::findByOrderId($oOrder->getId()) as $oInvoice) {
+
+                        $arAttach_Customer[] = $oInvoice->getFilePath();
+
+                    }
+
                 } catch (\Exception $e) {
 			        
Index: /lib/wpsg_calculation.class.php
===================================================================
--- /lib/wpsg_calculation.class.php	(revision 8213)
+++ /lib/wpsg_calculation.class.php	(revision 8214)
@@ -1199,5 +1199,5 @@
 				$shipping = $this->shop->arShipping[$db_order['type_shipping']];
 					
-				$this->addShipping($shipping['price'],$this->shop->getBackendTaxview(),$shipping['mwst_key'],$db_order['type_shipping']);
+				$this->addShipping($shipping['price'],$this->shop->getBackendTaxview(), $shipping['mwst_key'], $db_order['type_shipping']);
 				
 			} else {
Index: /model/wpsg_customer.class.php
===================================================================
--- /model/wpsg_customer.class.php	(revision 8213)
+++ /model/wpsg_customer.class.php	(revision 8214)
@@ -301,5 +301,5 @@
 			}
 			
-			return preg_replace('/(.*)\040/', '', $this->strasse);
+			return preg_replace('/(.*)\040/', '', $this->strasse??'');
 			
 		} // public function getStreetNr()
Index: /model/wpsg_order.class.php
===================================================================
--- /model/wpsg_order.class.php	(revision 8213)
+++ /model/wpsg_order.class.php	(revision 8214)
@@ -1314,5 +1314,12 @@
 			if ($bJoinProducts === true) $strQueryJOIN .= " LEFT JOIN `".WPSG_TBL_PRODUCTS."` AS P ON (OP.`p_id` = P.`id`) ";
 			if ($bJoinCustomer === true) $strQueryJOIN .= " LEFT JOIN `".WPSG_TBL_KU."` AS C ON (C.`id` = O.`k_id`) ";
-			if ($bJoinInvoice === true) $strQueryJOIN .= " LEFT JOIN `".WPSG_TBL_RECHNUNGEN."` AS I ON ( ( FIND_IN_SET(O.`id`, I.`o_ids`) AND I.`storno` = '0000-00-00 00:00:00' AND I.`rnr` != '' ) OR ( I.`o_id` =  O.`id` AND I.`storno` = '0000-00-00 00:00:00' AND I.`rnr` != '' ) ) ";
+			if ($bJoinInvoice === true) {
+
+                $strQueryJOIN .= " 
+                    LEFT JOIN `".WPSG_TBL_ORDER_INVOICE."` AS ORDER_INVOICE ON (O.`id` = ORDER_INVOICE.`order_id`) 
+                    LEFT JOIN `".WPSG_TBL_RECHNUNGEN."` AS I ON (I.`id` = ORDER_INVOICE.`invoice_id`) 
+                ";
+
+            }
 			if ($bJoinOrderAdress === true) $strQueryJOIN .= " LEFT JOIN `".WPSG_TBL_ADRESS."` AS OA ON (OA.`id` = O.`adress_id`) ";
 			
Index: /mods/mod_rechnungen/wpsg_invoice.php
===================================================================
--- /mods/mod_rechnungen/wpsg_invoice.php	(revision 8213)
+++ /mods/mod_rechnungen/wpsg_invoice.php	(revision 8214)
@@ -11,5 +11,7 @@
     namespace wpsg;
 	
-	class wpsg_invoice extends \wpsg_model {
+	use phpseclib\File\ASN1\Element;
+
+    class wpsg_invoice extends \wpsg_model {
 		
 		 static $_tableName = 'WPSG_TBL_RECHNUNGEN';
@@ -29,5 +31,29 @@
 			
 		}
-		 
+
+        public function getOrderIds() {
+
+            return array_map('intval', $this->db->fetchAssocField("
+                SELECT `order_id` FROM `".WPSG_TBL_ORDER_INVOICE."` WHERE `invoice_id` = '".intval($this->getId())."'
+            "));
+
+        }
+
+        public function setOrder(int $order_id) {
+
+            // KÃ¶nnte man ÃŒber Uniqe der Datenbank ÃŒberlassen, aber lieber so
+            $exist = intval($this->db->fetchOne("SELECT `id` FROM `".WPSG_TBL_ORDER_INVOICE."` WHERE `order_id` = '".intval($order_id)."' AND `invoice_id` = '".intval($this->getId())."' "));
+
+            if ($exist <= 0) {
+
+                $this->db->ImportQuery(WPSG_TBL_ORDER_INVOICE, [
+                    'order_id' => M1::q($order_id),
+                    'invoice_id' => M1::q($this->getId())
+                ]);
+
+            }
+
+        }
+
 		public function isInvoice() {
 			
@@ -52,25 +78,48 @@
 		 */
 		public function getFilePath() {
-			
+
+            /*
+					if (file_exists($this->getFilePath($order_id).$r_id.'.pdf')) { $file = $this->getFilePath($order_id).$r_id.'.pdf'; }
+					else if (file_exists($this->getFilePath($order_id).$rnr.'.pdf')) { $file = $this->getFilePath($order_id).$rnr.'.pdf'; }
+					else if (file_exists($this->getFilePath($order_id).'R'.$r_id.'.pdf')) { $file = $this->getFilePath($order_id).'R'.$r_id.'.pdf'; }
+					else { $file = $this->getFilePath($order_id).'R'.$rnr.'.pdf'; }
+             */
+
+            $ym = date('Y/m', strtotime($this->__get('datum')));
+
 			if ($this->isMultiInvoice()) {
-				
-				$ym = date('Y/m', strtotime($this->__get('datum')));
-				
-				if ($this->shop->isMultiBlog()) {
- 					
- 					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/'.$ym.'/multi/'; 					
- 					 					
- 				} else {
- 					
- 					$path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$ym.'/multi/';
- 					 					
- 				}
-				 
-			} else throw new \Exception(_('Noch nicht implementiert'));
-			
-			\wpsg_ShopController::getShop()->protectDirectory($path);
-			
-			$path .= $this->getId().'.pdf';
-			
+
+				if ($this->shop->isMultiBlog()) $path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/'.$ym.'/multi/'.$this->getId();
+                else $path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$ym.'/multi/'.$this->getId();
+
+			} else {
+
+                if ($this->shop->isMultiBlog()) $path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/'.$ym.'/';
+                else $path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$ym.'/';
+
+                if (!file_exists($path.$this->getId().'.pdf')) {
+
+                    if ($this->__get('gnr') !== '') {
+
+                        if (file_exists($path.'G'.$this->__get('gnr').'.pdf')) $path .= 'G'.$this->__get('gnr').'.pdf';
+                        else if (file_exists($path.'G'.$this->getId().'.pdf')) $path .= 'G'.$this->getId().'.pdf';
+                        else if (file_exists($path.$this->__get('gnr').'.pdf')) $path .= $this->__get('gnr').'.pdf';
+                        else $path .= $this->getId().'.pdf';
+
+                    } else if ($this->__get('rnr') !== '') {
+
+                        if (file_exists($path.'R'.$this->__get('rnr').'.pdf')) $path .= 'R'.$this->__get('rnr').'.pdf';
+                        else if (file_exists($path.'R'.$this->getId().'.pdf')) $path .= 'R'.$this->getId().'.pdf';
+                        else if (file_exists($path.$this->__get('rnr').'.pdf')) $path .= $this->__get('rnr').'.pdf';
+                        else $path .= $this->getId().'.pdf';
+
+                    } else $path .= $this->getId().'.pdf';
+
+                } else $path .= $this->getId().'.pdf';
+
+            }
+			
+			\wpsg_ShopController::getShop()->protectDirectory(dirname($path));
+
 			return $path;
 			
@@ -82,6 +131,6 @@
 		public function getOrder() {
 
-			return \wpsg_order::getInstance(intval($this->__get('o_id')));
-			
+            return \wpsg_order::getInstance($this->getOrderIds()[0]);
+
 		}
 
@@ -112,12 +161,4 @@
 					$strReturn .= '<a title="'.$strTitle.'" class="link_invoice '.(($this->isStorno())?'bg_storno':'').' '.(($this->isInvoice())?'bg_invoice':'').'" href="';
 					$strReturn .= wp_nonce_url(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=ajax&noheader=1&mod=wpsg_mod_rechnungen&do=getRechnung&edit_id='.$this->getOrder()->getId().'&r_id='.$this->getId(), 'wpsg-mod_invoice-order_ajax-getRechnung-'.$this->getId());
-					$strReturn .= '" target="_blank">';
-
-				} else {
-
-					$multiOrderID = intval(explode(",", $this->__get('o_ids'))[0]);
-
-					$strReturn .= '<a title="'.$strTitle.'" class="link_invoice '.(($this->isStorno())?'bg_storno':'').' '.(($this->isInvoice())?'bg_invoice':'').'" href="';
-					$strReturn .= wp_nonce_url(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=ajax&noheader=1&mod=wpsg_mod_rechnungen&do=getRechnung&edit_id='.$multiOrderID.'&r_id='.$this->getId(), 'wpsg-mod_invoice-order_ajax-getRechnung-'.$this->getId());
 					$strReturn .= '" target="_blank">';
 
@@ -157,4 +198,31 @@
 			
 		}
-		
+
+        public function delete() {
+
+            $this->db->Query("DELETE FROM `".WPSG_TBL_ORDER_INVOICE."` WHERE `invoice_id` = '".intval($this->getId())."' ");
+            $this->db->Query("DELETE FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".intval($this->getId())."' ");
+
+            unlink($this->getFilePath());
+
+        }
+
+        /**
+         * @param int $order_id
+         * @return wpsg_invoice[]
+         */
+        public static function findByOrderId(int $order_id) {
+
+            $r = [];
+
+            foreach ($GLOBALS['wpsg_db']->fetchAssocField("SELECT `invoice_id` FROM `".WPSG_TBL_ORDER_INVOICE."` WHERE `order_id` = '".intval($order_id)."' ") as $invoice_id) {
+
+                $r[] = wpsg_invoice::getInstance(intval($invoice_id));
+
+            }
+
+            return $r;
+
+        }
+
 	}
Index: /mods/wpsg_mod_export.class.php
===================================================================
--- /mods/wpsg_mod_export.class.php	(revision 8213)
+++ /mods/wpsg_mod_export.class.php	(revision 8214)
@@ -1129,5 +1129,4 @@
 
                         $tag_product->appendChild($att);
-
 
                     } else {
Index: /mods/wpsg_mod_gutschein.class.php
===================================================================
--- /mods/wpsg_mod_gutschein.class.php	(revision 8213)
+++ /mods/wpsg_mod_gutschein.class.php	(revision 8214)
@@ -4,10 +4,11 @@
 	 * Dieses Modul erlaubt die Erstellung und Verwendung von Gutscheinen
 	 */
-	class wpsg_mod_gutschein extends wpsg_mod_basic
-	{
+	class wpsg_mod_gutschein extends wpsg_mod_basic	{
 
 		var $id = 160;
 		var $lizenz = 1;
 		var $hilfeURL = 'http://wpshopgermany.de/?p=455';
+
+        var $view = [];
 
 		/**
Index: /mods/wpsg_mod_productvars.class.php
===================================================================
--- /mods/wpsg_mod_productvars.class.php	(revision 8213)
+++ /mods/wpsg_mod_productvars.class.php	(revision 8214)
@@ -416,5 +416,5 @@
 				{
 	
-					$pVarsSet = explode(",", $this->db->fetchOne("SELECT `produktvars` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'"));
+					$pVarsSet = explode(",", $this->db->fetchOne("SELECT `produktvars` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'")??'');
 					foreach ($pVarsSet as $k => $v) { if (trim($v) == '') { unset($pVarsSet[$k]); } }
 	
@@ -746,5 +746,5 @@
 			$order_data = $this->shop->cache->loadOrder($order_id);
 			$arPVars = @unserialize($order_data['pvars']);
-			$arPVars = wpsg_getArray($arPVars[$product_index]);
+			$arPVars = $arPVars[$product_index]??[];
 			$arReturn = array();
 
Index: /mods/wpsg_mod_rechnungen.class.php
===================================================================
--- /mods/wpsg_mod_rechnungen.class.php	(revision 8213)
+++ /mods/wpsg_mod_rechnungen.class.php	(revision 8214)
@@ -96,13 +96,12 @@
 		} // public function install()
 		
-		public function delOrder($order_id) 
-		{ 
-			
-			// Rechnungen in der Datenbank lÃ¶schen
-			$this->db->Query("DELETE FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."'");
-
-			// Rechnungen im Dateisystem lÃ¶schen
-			$path = $this->getFilePath($order_id); wpsg_rrmdir($path);
-			
+		public function delOrder($order_id) {
+
+            foreach (\wpsg\wpsg_invoice::findByOrderId($order_id) as $oInvoice) {
+
+                $oInvoice->delete();
+
+            }
+
 		} // public function delOrder($order_id)
 		
@@ -127,9 +126,67 @@
 			
 		} // public function template_redirect()
-				 
+
+        public function systemcheck(&$arData) {
+
+            $nInvoiceToCorrect = $this->db->fetchOne("
+                SELECT COUNT(*) FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` > 0 OR `o_ids` != '' 
+            ");
+
+            if ($nInvoiceToCorrect > 0) {
+
+                $arData[] = array(
+                    'wpsg_mod_rechnungen_convert_order',
+                    wpsg_ShopController::CHECK_ERROR,
+                    wpsg_translate(
+                        __('Es gibt #1# Rechnungen die den Bestellungen falsch zugeordnet sind. Klicken Sie <a href="#2#">hier</a> um diese in die neue und optimierte Struktur zu ÃŒberfÃŒhren.', 'wpsg'),
+                        $nInvoiceToCorrect,
+                        WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Admin&modul=wpsg_mod_rechnungen&action=module&noheader=1&do=convert'
+                    )
+                );
+
+            }
+
+        }
+
 		public function be_ajax() {
-			
-			if ($_REQUEST['do'] == 'reset')
-			{
+
+            if (($_REQUEST['do']??'') === 'convert') {
+
+                $arInvoiceToCorrect = $this->db->fetchAssoc("
+                    SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` > 0 OR `o_ids` != '' 
+                ");
+
+                $nConvert = 0;
+
+                foreach ($arInvoiceToCorrect as $invoice_data) {
+
+                    $oInvoice = \wpsg\wpsg_invoice::getInstance(intval($invoice_data['id']));
+
+                    $arOrder = explode(',', $invoice_data['o_ids']);
+                    $arOrder[] = $invoice_data['o_id'];
+
+                    foreach ($arOrder as $order_id) {
+
+                        if (intval($order_id) > 0) {
+
+                            $oInvoice->setOrder(intval($order_id));
+
+                        }
+
+                    }
+
+                    $this->db->UpdateQuery(WPSG_TBL_RECHNUNGEN, [
+                        'o_id' => 0,
+                        'o_ids' => ''
+                    ], " `id` = '".intval($invoice_data['id'])."' ");
+
+                    $nConvert ++;
+
+                }
+
+                $this->shop->addBackendMessage(wpsg_translate(__('Es wurden #1# Rechnungen in die optimierte Datenstruktur ÃŒberfÃŒhrt.', 'wpsg'), $nConvert));
+                $this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Admin'); exit;
+
+            } else if ($_REQUEST['do'] == 'reset') {
 				
 				$this->resetAction();
@@ -212,15 +269,15 @@
 				} else if ($ending == "jpg" || $ending == "jpeg") {
 
-                    @unlink($this->getFilePath('').'wpsg_rechnungen_bp.jpg');
-                    @unlink($this->getFilePath('').'wpsg_rechnungen_bp.pdf');
+                    @unlink($this->getPaperPath().'wpsg_rechnungen_bp.jpg');
+                    @unlink($this->getPaperPath().'wpsg_rechnungen_bp.pdf');
 				    
-					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_bp.jpg');
+					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getPaperPath().'wpsg_rechnungen_bp.jpg');
 					
 				} else if ($ending == "pdf") {
 
-                    @unlink($this->getFilePath('').'wpsg_rechnungen_bp.jpg');
-                    @unlink($this->getFilePath('').'wpsg_rechnungen_bp.pdf');
-
-					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_bp.pdf');
+                    @unlink($this->getPaperPath().'wpsg_rechnungen_bp.jpg');
+                    @unlink($this->getPaperPath().'wpsg_rechnungen_bp.pdf');
+
+					move_uploaded_file($_FILES['wpsg_rechnungen_bp']['tmp_name'], $this->getPaperPath().'wpsg_rechnungen_bp.pdf');
                 
                 }
@@ -228,6 +285,6 @@
 			} else if ((array_key_exists('wpsg_rechnungen_bp_del', $_REQUEST)) && ($_REQUEST['wpsg_rechnungen_bp_del'] == "1")) {
 
-				@unlink($this->getFilePath('').'wpsg_rechnungen_bp.jpg');
-				@unlink($this->getFilePath('').'wpsg_rechnungen_bp.pdf');
+				@unlink($this->getPaperPath().'wpsg_rechnungen_bp.jpg');
+				@unlink($this->getPaperPath().'wpsg_rechnungen_bp.pdf');
 
 				$this->shop->addBackendMessage(__('Briefpapier wurde erfolgreich gelÃ¶scht.', 'wpsg'));
@@ -256,5 +313,5 @@
                     $_REQUEST['wpsg_rechnungen_logo_transparency'] = 100;
 				    
-					move_uploaded_file($_FILES['wpsg_rechnungen_logo']['tmp_name'], $this->getFilePath('').'wpsg_rechnungen_logo.jpg');
+					move_uploaded_file($_FILES['wpsg_rechnungen_logo']['tmp_name'], $this->getPaperPath().'wpsg_rechnungen_logo.jpg');
 					
 				}
@@ -262,5 +319,5 @@
 			} else if ((array_key_exists('wpsg_rechnungen_logo_del', $_REQUEST)) && ($_REQUEST['wpsg_rechnungen_logo_del'] == "1")) {
 
-				@unlink($this->getFilePath('').'wpsg_rechnungen_logo.jpg');
+				@unlink($this->getPaperPath().'wpsg_rechnungen_logo.jpg');
 
 				$this->shop->addBackendMessage(__('Logo wurde erfolgreich gelÃ¶scht.', 'wpsg'));
@@ -335,11 +392,11 @@
 		{
 						
-			if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.jpg'))
+			if (file_exists($this->getPaperPath().'wpsg_rechnungen_bp.jpg'))
 			{
-				$this->shop->view['bp'] = $this->getFilePath('', true).'wpsg_rechnungen_bp.jpg';
-			}
-			else if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.pdf'))
+				$this->shop->view['bp'] = $this->getPaperPath(true).'wpsg_rechnungen_bp.jpg';
+			}
+			else if (file_exists($this->getPaperPath().'wpsg_rechnungen_bp.pdf'))
 			{
-				$this->shop->view['bp'] = $this->getFilePath('', true).'wpsg_rechnungen_bp.pdf';
+				$this->shop->view['bp'] = $this->getPaperPath(true).'wpsg_rechnungen_bp.pdf';
 			}
 			else
@@ -348,7 +405,7 @@
 			}
 			
-			if (file_exists($this->getFilePath('').'wpsg_rechnungen_logo.jpg'))
+			if (file_exists($this->getPaperPath().'wpsg_rechnungen_logo.jpg'))
 			{
-				$this->shop->view['logo'] = $this->getFilePath('', true).'wpsg_rechnungen_logo.jpg';
+				$this->shop->view['logo'] = $this->getPaperPath(true).'wpsg_rechnungen_logo.jpg';
 			}
 			else
@@ -384,16 +441,16 @@
 			$strQuery = "
 				SELECT 
-				    * 
+				    I.* 
 				FROM 
-				    `".WPSG_TBL_RECHNUNGEN."` 
-				WHERE 
-					(
-						`o_id` = '".wpsg_q($order_id)."' OR 
-						FIND_IN_SET('".intval($order_id)."', `o_ids`)
-					) AND 
-					`storno` = '0000-00-00 00:00:00' AND 
-					`gnr` = '' 
+				    `".WPSG_TBL_RECHNUNGEN."` AS I
+				        LEFT JOIN `".WPSG_TBL_ORDER_INVOICE."` AS ORDER_INVOICE ON (I.`id` = ORDER_INVOICE.`invoice_id`)
+				WHERE  
+					ORDER_INVOICE.`order_id` = '".intval($order_id)."' AND
+				    I.`storno` = '0000-00-00 00:00:00' AND 
+					I.`gnr` = '' 
+				GROUP BY
+				    I.`id` 
 				ORDER BY 
-					`rnr` DESC
+					I.`rnr` DESC
 			";
 
@@ -402,16 +459,16 @@
 			$strQuery = "
 				SELECT 
-				    * 
+				    INVOICE.* 
 				FROM 
-					`".WPSG_TBL_RECHNUNGEN."` 
-				WHERE 
-					(
-						`o_id` = '".wpsg_q($order_id)."' OR 
-						FIND_IN_SET('".intval($order_id)."', `o_ids`)
-					) AND 
-					`storno` != '0000-00-00 00:00:00' AND 
-					`gnr` = '' 
+					`".WPSG_TBL_RECHNUNGEN."` AS INVOICE
+					    LEFT JOIN `".WPSG_TBL_ORDER_INVOICE."` AS ORDER_INVOICE ON (ORDER_INVOICE.`invoice_id` = INVOICE.`id`)
+				WHERE  
+					ORDER_INVOICE.`order_id` = '".intval($order_id)."' AND
+					INVOICE.`storno` != '0000-00-00 00:00:00' AND 
+					INVOICE.`gnr` = '' 
+				GROUP BY
+				    INVOICE.`id`
 				ORDER BY 
-					`rnr` DESC
+					INVOICE.`rnr` DESC
 			";
 			
@@ -420,16 +477,16 @@
 			$this->shop->view['mod_rechnungen']['arRechnungen_gesamt'] = $this->db->fetchAssoc("
 				SELECT 
-					*, 
-					UNIX_TIMESTAMP(`datum`) AS ts_datum,
-					UNIX_TIMESTAMP(`storno`) AS ts_storno
+					INVOICE.*, 
+					UNIX_TIMESTAMP(INVOICE.`datum`) AS ts_datum,
+					UNIX_TIMESTAMP(INVOICE.`storno`) AS ts_storno
 				FROM 
-					`".WPSG_TBL_RECHNUNGEN."` 
-				WHERE 
-					(
-						`o_id` = '".wpsg_q($order_id)."' OR 
-						FIND_IN_SET('".intval($order_id)."', `o_ids`)
-					) 
+					`".WPSG_TBL_RECHNUNGEN."` AS INVOICE
+					    LEFT JOIN `".WPSG_TBL_ORDER_INVOICE."` AS ORDER_INVOICE ON (INVOICE.`id` = ORDER_INVOICE.`invoice_id`)
+				WHERE  
+					ORDER_INVOICE.`order_id` = '".intval($order_id)."' 
+				GROUP BY
+				    INVOICE.`id`
 				ORDER BY 
-					`id` ASC
+					INVOICE.`id` ASC
 			");
 
@@ -484,11 +541,11 @@
 				wpsg_checkNounce('Admin', 'module', ['modul' => 'wpsg_mod_rechnungen', 'do' => 'orderAjax', 'module_action' => 'getBp']);
 				
-				if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.jpg')) {
-					
-					(new wpsg_header)->IMG($this->getFilePath('', false).'wpsg_rechnungen_bp.jpg');
-					
-				} else if (file_exists($this->getFilePath('').'wpsg_rechnungen_bp.pdf')) {
-					
-					wpsg_header::PDFPlugin($this->getFilePath('', false).'wpsg_rechnungen_bp.pdf');
+				if (file_exists($this->getPaperPath().'wpsg_rechnungen_bp.jpg')) {
+					
+					(new wpsg_header)->IMG($this->getPaperPath().'wpsg_rechnungen_bp.jpg');
+					
+				} else if (file_exists($this->getPaperPath().'wpsg_rechnungen_bp.pdf')) {
+					
+					wpsg_header::PDFPlugin($this->getPaperPath().'wpsg_rechnungen_bp.pdf');
 					
 				} else throw new \Exception('Kein Briefpapier definiert.');
@@ -498,7 +555,7 @@
 				wpsg_checkNounce('Admin', 'module', ['modul' => 'wpsg_mod_rechnungen', 'do' => 'orderAjax', 'module_action' => 'getLogo']);
 				
-				if (file_exists($this->getFilePath('').'wpsg_rechnungen_logo.jpg')) {
-					
-					(new wpsg_header)->IMG($this->getFilePath('', false).'wpsg_rechnungen_logo.jpg');
+				if (file_exists($this->getPaperPath().'wpsg_rechnungen_logo.jpg')) {
+					
+					(new wpsg_header)->IMG($this->getPaperPath().'wpsg_rechnungen_logo.jpg');
 					
 				} else throw new \Exception('Kein Logo definiert.');
@@ -543,8 +600,9 @@
 				
 				$rechnung = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($_REQUEST['r_id'])."'");
-				
-				if ($rechnung['id'] != $_REQUEST['r_id'] || ($_REQUEST['edit_id'] != $rechnung['o_id'] && !in_array($_REQUEST['edit_id'], explode(',', $rechnung['o_ids'])))) die(__("Rechnung existiert nicht oder passt nicht zur Bestellung!", "wpsg"));
-				
-				$this->shop->view['order'] = $this->shop->cache->loadOrder($rechnung['o_id']); 
+				$oInvoice = \wpsg\wpsg_invoice::getInstance(intval($_REQUEST['r_id']));
+
+				if ($rechnung['id'] != $_REQUEST['r_id'] || !in_array(intval($_REQUEST['edit_id']), explode(',', $oInvoice->getOrderIds()))) die(__("Rechnung existiert nicht oder passt nicht zur Bestellung!", "wpsg"));
+				
+				$this->shop->view['order'] = $this->shop->cache->loadOrder($oInvoice->getOrderIds()[0]);
 				
 				// Wurde die Bestellung in einer anderen Sprache ausgefÃŒhrt
@@ -555,37 +613,10 @@
 				$email = $this->shop->view['kunde']['email'];
 
+                $rn_file = $oInvoice->getFilePath();
+                $rn_file_copy = dirname($oInvoice->getFilePath()).DIRECTORY_SEPARATOR.'copy_'.basename($oInvoice->getFilePath());
+
 				// Nun schauen ob die Original Rechnung existiert				
-				if ($rechnung['gnr'] != "")
-				{
-					
-					if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf'))
-					{
-						
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['id'].'.pdf';
-						
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['gnr'].'.pdf'))
-					{
-					
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['gnr'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_G'.$rechnung['id'].'.pdf';
-						
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['id'].'.pdf'))
-					{
-						
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'G'.$rechnung['id'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_G'.$rechnung['id'].'.pdf';
-						
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['gnr'].'.pdf'))
-					{
-						
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['gnr'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['gnr'].'.pdf';
-						
-					} 
-					  
+				if ($rechnung['gnr'] != "") {
+
 					$strTitle = wpsg_translate(__('Zusendung einer Kopie fÃŒr Rechnungskorrektur #1# an #2#', 'wpsg'), $rechnung['gnr'], $email);
 					$this->shop->view['gnr'] = $rechnung['gnr'];
@@ -593,48 +624,6 @@
 					$nr = $rechnung['gnr'];
 					
-				}
-				else
-				{
-					
-					if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf'))
-					{
-					
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['id'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['id'].'.pdf';
-					
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['rnr'].'.pdf'))
-					{
-					
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['rnr'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_R'.$rechnung['id'].'.pdf';
-						
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['id'].'.pdf'))
-					{
-						
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).'R'.$rechnung['id'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_R'.$rechnung['id'].'.pdf';
-						
-					}
-					else if (file_exists($this->getFilePath($_REQUEST['edit_id']).$rechnung['rnr'].'.pdf'))					
-					{
-						
-						$rn_file = $this->getFilePath($_REQUEST['edit_id']).$rechnung['rnr'].'.pdf';
-						$rn_file_copy = $this->getFilePath($_REQUEST['edit_id']).'copy_'.$rechnung['rnr'].'.pdf';
-						
-					} else {
-
-						$oInvoice = \wpsg\wpsg_invoice::getInstance($rechnung['id']);
-						$rn_file = $oInvoice->getFilePath();
-
-						if (file_exists($rn_file)) {
-							
-							$rn_file_copy = dirname($rn_file).DIRECTORY_SEPARATOR.'copy_'.basename($rn_file);
-							
-						}
-
-					}
-					
+				} else {
+
 					$strTitle = wpsg_translate(__('Zusendung einer Kopie fÃŒr Rechnung #1# an #2#', 'wpsg'), $rechnung['rnr'], $email);
 					$this->shop->view['rnr'] = $rechnung['rnr'];
@@ -644,9 +633,9 @@
 				}
 				
-				$oInvoice = \wpsg\wpsg_invoice::getInstance(intval($_REQUEST['r_id']));
-				
-				if ($oInvoice->isMultiInvoice()) {
-
-					$rn_file = $oInvoice->getFilePath();
+				$oInvoiceOrigin = \wpsg\wpsg_invoice::getInstance(intval($_REQUEST['r_id']));
+				
+				if ($oInvoiceOrigin->isMultiInvoice()) {
+
+					$rn_file = $oInvoiceOrigin->getFilePath();
 				
 				} 
@@ -654,17 +643,4 @@
 				if (!file_exists($rn_file)) die(__("Die Originalrechnung existiert nicht im Dateisystem.", 'wpsg'));
 
-				/*
-				if (file_exists($rn_file_copy)) 
-				{
-					
-					header("Cache-Control: no-cache, must-revalidate");
-					header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); 
-					header('Content-type: application/pdf'); 
-						
-					die(file_get_contents($rn_file_copy));
-
-				}
-				*/
-				
 				require_once WPSG_PATH_LIB.'FPDF_1.81/fpdf.php';
 				require_once WPSG_PATH_LIB.'FPDI_2.2.0/autoload.php'; 
@@ -674,6 +650,5 @@
 				$pagecount = $pdf->setSourceFile($rn_file);
 
-				for ($i = 1; $i <= $pagecount; $i ++)
-				{
+				for ($i = 1; $i <= $pagecount; $i ++) {
 
 					$tplidx = $pdf->importPage($i, '/MediaBox');
@@ -700,12 +675,9 @@
 				$mail_text = $this->shop->render(WPSG_PATH_VIEW."/mods/mod_rechnungen/copymail.phtml", false);
  
-				if ($this->shop->get_option('wpsg_htmlmail') === '1')
-				{
+				if ($this->shop->get_option('wpsg_htmlmail') === '1') {
 					
 					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/copymail_html.phtml', false);
 					
-				}
-				else
-				{
+				} else {
 					
 					$mail_html = false;
@@ -715,11 +687,9 @@
 				$arFiles = array($rn_file_copy);
  				
-				if ($this->shop->get_option('wpsg_widerrufsformular_invoice') === '1' && wpsg_isSizedString($this->shop->get_option('wpsg_revocationform')))
-				{
-						
+				if ($this->shop->get_option('wpsg_widerrufsformular_invoice') === '1' && wpsg_isSizedString($this->shop->get_option('wpsg_revocationform'))) {
+
 					$revocationFile = WPSG_PATH_UPLOADS.'wpsg_revocation/'.$this->shop->get_option('wpsg_revocationform');
 						
-					if (file_exists($revocationFile) && is_file($revocationFile))
-					{
+					if (file_exists($revocationFile) && is_file($revocationFile)) {
 				
 						$arFiles[] = $revocationFile;
@@ -737,10 +707,14 @@
 				
 				// In Bestelllog eintragen
-				$this->db->ImportQuery(WPSG_TBL_OL, array(
-					"o_id" => $rechnung['o_id'],
-					"cdate" => "NOW()",
-					"title" => $strTitle,
-					"mailtext" => $mail_text
-				));
+                foreach ($oInvoiceOrigin->getOrderIds() as $order_id) {
+
+                    $invoice_id = $this->db->ImportQuery(WPSG_TBL_OL, array(
+                        "cdate" => "NOW()",
+                        "title" => $strTitle,
+                        "mailtext" => $mail_text,
+                        'o_id' => $order_id
+                    ));
+
+                }
 
                 ob_end_clean();
@@ -792,10 +766,4 @@
 		}
 
-        public function systemcheck(&$arData) {
-
-
-
-        }
-
 		public function admin_emailconf_save()
 		{
@@ -834,192 +802,5 @@
 
 		} // public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
-		
-		private function _writeGutschrift($order_id, $gnr_id, $storno_fee, $bPreview) {
-			
-			$this->shop->view['invoice'] = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($gnr_id)."' ");
-			
-			$this->shop->view['data'] = $this->db->fetchRow("
-				SELECT
-					O.*
-				FROM
-					`".WPSG_TBL_ORDER."` AS O
-				WHERE
-					O.`id` = '".wpsg_q($order_id)."'
-			");			
-
-			if (trim($this->shop->view['data']['language']) != '') $this->shop->setTempLocale($this->shop->view['data']['language']);
-			
-			$this->getAdresse($this->shop->view['data']['k_id']);
-			
-			$basket = new wpsg_basket();
-			$basket->initFromDB($order_id, true);
-			$this->shop->view['basket'] = $basket->toArray(true);
-		 
-			$this->shop->view['storno_fee'] = $storno_fee;
-			
-			if (wpsg_tf($storno_fee) > 0)
-			{
-			
-				if (strpos($storno_fee, '%') !== false)
-				{
-					
-					// % Betrag
-					if ($this->shop->getBackendTaxview() == WPSG_NETTO) $storno_fee_value_netto = $this->shop->view['basket']['sum']['preis_gesamt_netto'] / 100 * wpsg_tf($storno_fee);
-					else $storno_fee_value_brutto = $this->shop->view['basket']['sum']['preis_gesamt_brutto'] / 100 * wpsg_tf($storno_fee);
-					
-				}
-				else
-				{
-					
-					// Absoluter Betrag
-					if ($this->shop->getBackendTaxview() == WPSG_NETTO) $storno_fee_value_netto = wpsg_tf($storno_fee);
-					else $storno_fee_value_brutto = wpsg_tf($storno_fee); 
-					
-				}
-				
-				$storno_tax_key = $this->shop->get_option('wpsg_mod_rechnungen_gutschrifttax'); 
-				
-				if (in_array($storno_tax_key, array('a', 'b', 'c', 'd', 'e')))
-				{
-					
-					$country_id = $this->shop->view['basket']['land']['id'];
-					$oCountry = wpsg_country::getInstance($country_id);
-					//$defaultCountry = $this->shop->getDefaultCountry();
-					//$storno_fee_tax_value = $defaultCountry->getTax($storno_tax_key);
-					$storno_fee_tax_value = $oCountry->getTax($storno_tax_key);
-					
-					if ($this->shop->getBackendTaxview() === WPSG_NETTO) $storno_fee_value_brutto = wpsg_calculatePreis($storno_fee_value_netto, WPSG_BRUTTO, $storno_fee_tax_value);
-					else $storno_fee_value_netto = wpsg_calculatePreis($storno_fee_value_brutto, WPSG_NETTO, $storno_fee_tax_value);				
-					
-					$storno_fee_tax = $storno_fee_value_brutto - $storno_fee_value_netto;
-	
-					// In den Mehrwertsteuer Array einbauen
-					$bFound = false;
-					foreach ($this->shop->view['basket']['mwst'] as $tax_key_country => $tax)
-					{
-						
-						if ($tax['value'] == $storno_fee_tax_value)
-						{
-							
-							$bFound = true;
-							$this->shop->view['basket']['mwst'][$tax_key_country]['base_value'] -= $storno_fee_value_brutto;
-							$this->shop->view['basket']['mwst'][$tax_key_country]['sum'] -= $storno_fee_tax;
-							break;
-							
-						}
-						
-					}
-					
-					if ($bFound === false)
-					{
-						 
-						$this->shop->view['basket']['mwst'][$storno_tax_key.'_'.$country_id] = array(
-							'country' => $country_id,
-							'tax_key' => $storno_tax_key,
-							'sum' => -1 * $storno_fee_tax,
-							'name' => wpsg_ff($storno_fee_tax_value, '%'),
-							'value' => $storno_fee_tax_value,
-							'base_value' => $storno_fee_value_brutto							 							
-						);
-						
-					}
-					
-				}		
-				else 
-				{
-	
-					// TODO: Anteilig
-					
-				}		
-
-				// Jetzt von den Preisen abziehen
-				$this->shop->view['basket']['sum']['preis_netto'] -= $storno_fee_value_netto;
-				$this->shop->view['basket']['sum']['preis_gesamt_netto'] -= $storno_fee_value_netto;
-				$this->shop->view['basket']['sum']['preis_brutto'] -= $storno_fee_value_brutto;
-				$this->shop->view['basket']['sum']['preis_gesamt_brutto'] -= $storno_fee_value_brutto;
-				$this->shop->view['basket']['sum']['mwst'] -= $storno_fee_tax;
-					
-				if ($this->shop->getFrontendTaxview() === WPSG_NETTO)
-				{
-				
-					$this->shop->view['basket']['sum']['preis'] = $this->shop->view['basket']['sum']['preis_netto'];
-					$this->shop->view['basket']['sum']['preis_gesamt'] = $this->shop->view['basket']['sum']['preis_gesamt_netto'];
-					$this->shop->view['storno_fee_value'] = $storno_fee_value_netto;
-				
-				}
-				else
-				{
-				
-					$this->shop->view['basket']['sum']['preis'] = $this->shop->view['basket']['sum']['preis_brutto'];
-					$this->shop->view['basket']['sum']['preis_gesamt'] = $this->shop->view['basket']['sum']['preis_gesamt_brutto'];
-					$this->shop->view['storno_fee_value'] = $storno_fee_value_brutto;
-				
-				}
-				
-				$this->shop->view['storno_fee_tax_value'] = $storno_fee_tax_value;
-				$this->shop->view['storno_fee_tax'] = $storno_fee_tax;
-				$this->shop->view['storno_fee_value_netto'] = $storno_fee_value_netto;
-				$this->shop->view['storno_fee_value_brutto'] = $storno_fee_value_brutto;
-					
-			}
-									
-			$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['kunde']['land'])."'");
-			$this->shop->view['data']['shipping_land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['data']['shipping_land'])."'");
-			$this->shop->view['rDatum'] = date('d.m.Y');
-					
-
-			$this->shop->view['payment'] = $this->shop->getPaymentName($this->shop->view['data']['type_payment'], $order_id);
-			
-			$this->shop->view['fussText'] = false;
-						
-			// Beschreibung dazuladen
-			foreach ($this->shop->view['basket']['produkte'] as $k => $v)
-			{
-				
-				$produkt_id = $this->shop->getProduktID($v['id']);
-				
-				$this->shop->view['basket']['produkte'][$k]['beschreibung'] = $this->db->fetchOne("
-					SELECT
-						P.`beschreibung`
-					FROM
-						`".WPSG_TBL_PRODUCTS."` AS P
-					WHERE
-						P.`id` = '".wpsg_q($produkt_id)."'
-				");
-				
-			}
-						
-			$this->shop->view['preview'] = false;
-			$this->shop->view['rnr'] = $this->shop->view['invoice']['gnr'];	
-
-			if ($bPreview) $this->shop->view['rnr'] .= __(' - Vorschau', 'wpsg');
-			
-			$this->shop->view['filename'] = $gnr_id;
-			$this->shop->view['filename_out'] = $this->shop->view['invoice']['gnr'].'.pdf';
-			
-			$this->shop->view['output'] = true;			
-			$this->shop->view['preview'] = $bPreview;
-			
-			// Wenn Rechnungskorrektur und Option aktiviert dann die Rechnungsnummer hinter die Rechnungskorrektursnummer
-			if ($this->shop->get_option("wpsg_mod_rechnungen_showgutschriftrechnung") == "1")
-			{
-				
-				// Letzt Rechnungsnummer finden
-				$last_rnr = $this->db->fetchOne("SELECT `rnr` FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `gnr` = '' ORDER BY `datum` DESC LIMIT 1");
-			
-				$this->shop->view['rnr'] .= ' ('.__("RNr.", "wpsg").' '.$last_rnr.')';
-				
-			}
-						
-			$this->shop->view['oOrder'] = $this->shop->cache->loadOrderObject($order_id);
-			$this->shop->view['storno'] = true;
-			$this->shop->view['invoice'] = false;
-			
-			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_rechnungen/accounting_pdf.phtml');
-			
-			$this->shop->restoreTempLocale();
-						
-		} // private function writeGutschrift($order_id)
-		
+
 		private function writeGutschrift($order_id, $gnr_id, $storno_fee, $bPreview) {
 				
@@ -1132,4 +913,5 @@
 			
 			$arProduct = [];
+            $sum = [];
 			
 			$tax_view = WPSG_NETTO;
@@ -1246,5 +1028,7 @@
 				
 			}
-			
+
+            $oInvoice = null;
+
 			if (!$bPreview) {
 				
@@ -1269,4 +1053,5 @@
 			
 			$this->shop->view['filename'] = $gnr_id;
+			$this->shop->view['oInvoice'] = $oInvoice;
 			$this->shop->view['filename_out'] = $this->shop->view['invoice']['gnr'].'.pdf';
 			
@@ -1305,7 +1090,7 @@
 			
 			// Wurde die Bestellung in einer anderen Sprache gemacht
-			if (trim($this->shop->view['data']['language']) != '') $this->shop->setTempLocale($this->shop->view['data']['language']);
-			
-			$this->getAdresse($this->shop->view['data']['k_id']);
+			if (trim($this->shop->view['data']['language']??'') != '') $this->shop->setTempLocale($this->shop->view['data']['language']);
+			
+			$this->getAdresse($this->shop->view['data']['k_id']??0);
 			 
 			$oOrder = wpsg_order::getInstance($order_id);
@@ -1313,9 +1098,13 @@
 			$custom_data = @unserialize($this->shop->view['data']['custom_data']);
 		
-			$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['kunde']['land'])."'");
+			$this->shop->view['kunde']['land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q($this->shop->view['kunde']['land']??0)."'");
 			$this->shop->view['data']['shipping_land'] = $this->db->fetchRow("SELECT L.* FROM `".WPSG_TBL_LAND."` AS L WHERE L.`id` = '".wpsg_q(wpsg_getStr($this->shop->view['data']['shipping_land']))."'");
 
-			if (wpsg_checkInput($_REQUEST['wpsg_rechnungen_datum'], WPSG_SANITIZE_DATE_EN)) $this->shop->view['rDatum'] = date('Y-m-d', strtotime($_REQUEST['wpsg_rechnungen_datum']));
-			else throw \wpsg\Exception::getSanitizeException();
+            if (isset($_REQUEST['wpsg_rechnungen_datum'])) {
+
+                if (wpsg_checkInput($_REQUEST['wpsg_rechnungen_datum'], WPSG_SANITIZE_DATE_EN)) $this->shop->view['rDatum'] = date('Y-m-d', strtotime($_REQUEST['wpsg_rechnungen_datum']));
+                else throw \wpsg\Exception::getSanitizeException();
+
+            }
 		
 			if ($this->shop->hasMod('wpsg_mod_shippingadress') && $this->shop->callMod('wpsg_mod_shippingadress', 'check_different_shippingadress', array('k_id' => @$this->shop->view['data']['k_id'], 'o_id' => @$this->shop->view['data']['id']))) {
@@ -1348,5 +1137,5 @@
 			$this->shop->view['fussText'] = $this->shop->replaceUniversalPlatzhalter(wpsg_sinput("text_field", @$_REQUEST['wpsg_rechnungen_fusstext']), $order_id);
 			
-			if ($_REQUEST['wpsg_rechnungen_faelligkeit'] == '1') {
+			if (($_REQUEST['wpsg_rechnungen_faelligkeit']??'') == '1') {
 			    
 				if (wpsg_checkInput($_REQUEST['wpsg_rechnungen_faelligkeitsdatum'], WPSG_SANITIZE_DATE_EN)) $this->shop->view['faelligkeitdatum'] = $_REQUEST['wpsg_rechnungen_faelligkeitsdatum'];
@@ -1437,68 +1226,71 @@
 
 			$tax_view = WPSG_NETTO;
-			
-			foreach ($_REQUEST['invoice_products'] as $order_product_id => $order_product_info) {
-				
-				if ($order_product_info['set'] === '1') {
-					
-					$oOrderProduct = wpsg_order_product::getInstance($order_product_id, true);
-					 
-					$oCalculation->addProduct(
-						$oOrderProduct->getPrice($tax_view),
-						$tax_view,
-						$oOrderProduct->getProduct()->__get('mwst_key'),
-						$order_product_info['amount'],
-						$oOrderProduct->getProductKey(),
-						false,
-						$oOrderProduct->getId(),
-						(($oOrderProduct->getProduct()->data['euleistungsortregel'] === '1')?true:false)
-					);  
-					
-					$p = [
-						'oOrderProduct' => $oOrderProduct,
-						'id' => $oOrderProduct->getProductKey(),
-						'product_index' => $oOrderProduct->getProductIndex(),
-						'productkey' => $oOrderProduct->getProductKey(),
-						'menge' => $order_product_info['amount'],
-						'price' => $oOrderProduct->getPrice($tax_view),
-						'weight' => $oOrderProduct->weight,
-						'anr' => $oOrderProduct->getProduct()->getNr(), 
-						'mwst_value' => $oOrder->getInvoiceCountry()->getTax($oOrderProduct->getTaxKey()),
-						'preis_netto' => $oOrderProduct->getPrice(WPSG_NETTO),
-						'preis_brutto' => $oOrderProduct->getPrice(WPSG_BRUTTO),
-						'name' => $oOrderProduct->getProduct()->getProductName(false),
-						'detailname' => $oOrderProduct->getProduct()->getProductName(true),
-						'beschreibung' => $oOrderProduct->getDescription()						
-					];
-
-					$sum['weight_gesamt'] += $p['weight'];
-					
-					if ($oCalculationOrder->getTaxMode() === \wpsg\wpsg_calculation::TAXMODE_B2B) {
-						
-						$p['preis_brutto'] = $p['preis_netto'];
-						$p['mwst_value'] = 0;
-						
-					}
-					
-					// Ãbersetzung
-					if ($this->shop->isOtherLang()) {
-					
-						$produkt_trans = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PRODUCTS."` WHERE `lang_parent` = '".wpsg_q($oOrderProduct->getProduct()->getId())."' AND `lang_code` = '".wpsg_q($this->shop->getCurrentLanguageCode())."'");
-					
-						if ($produkt_trans['id'] > 0) {
-								
-							$p['name'] = $produkt_trans['name'];
-							$p['beschreibung'] = $produkt_trans['beschreibung'];
-							$p['detailname'] = $produkt_trans['detailname'];
-					
-						}
-					
-					}
-					
-					$arProduct[] = $p;
-					
-				}
-				
-			}
+
+            if (isset($_REQUEST['invoice_products'])) {
+                foreach ($_REQUEST['invoice_products'] as $order_product_id => $order_product_info) {
+
+                    if ($order_product_info['set'] === '1') {
+
+                        $oOrderProduct = wpsg_order_product::getInstance($order_product_id, true);
+
+                        $oCalculation->addProduct(
+                            $oOrderProduct->getPrice($tax_view),
+                            $tax_view,
+                            $oOrderProduct->getProduct()->__get('mwst_key'),
+                            $order_product_info['amount'],
+                            $oOrderProduct->getProductKey(),
+                            false,
+                            $oOrderProduct->getId(),
+                            (($oOrderProduct->getProduct()->data['euleistungsortregel'] === '1') ? true : false)
+                        );
+
+                        $p = [
+                            'oOrderProduct' => $oOrderProduct,
+                            'id' => $oOrderProduct->getProductKey(),
+                            'product_index' => $oOrderProduct->getProductIndex(),
+                            'productkey' => $oOrderProduct->getProductKey(),
+                            'menge' => $order_product_info['amount'],
+                            'price' => $oOrderProduct->getPrice($tax_view),
+                            'weight' => $oOrderProduct->weight,
+                            'anr' => $oOrderProduct->getProduct()->getNr(),
+                            'mwst_value' => $oOrder->getInvoiceCountry()->getTax($oOrderProduct->getTaxKey()),
+                            'preis_netto' => $oOrderProduct->getPrice(WPSG_NETTO),
+                            'preis_brutto' => $oOrderProduct->getPrice(WPSG_BRUTTO),
+                            'name' => $oOrderProduct->getProduct()->getProductName(false),
+                            'detailname' => $oOrderProduct->getProduct()->getProductName(true),
+                            'beschreibung' => $oOrderProduct->getDescription()
+                        ];
+
+                        $sum['weight_gesamt'] += $p['weight'];
+
+                        if ($oCalculationOrder->getTaxMode() === \wpsg\wpsg_calculation::TAXMODE_B2B) {
+
+                            $p['preis_brutto'] = $p['preis_netto'];
+                            $p['mwst_value'] = 0;
+
+                        }
+
+                        // Ãbersetzung
+                        if ($this->shop->isOtherLang()) {
+
+                            $produkt_trans = $this->db->fetchRow("SELECT * FROM `" . WPSG_TBL_PRODUCTS . "` WHERE `lang_parent` = '" . wpsg_q($oOrderProduct->getProduct()->getId()) . "' AND `lang_code` = '" . wpsg_q($this->shop->getCurrentLanguageCode()) . "'");
+
+                            if ($produkt_trans['id'] > 0) {
+
+                                $p['name'] = $produkt_trans['name'];
+                                $p['beschreibung'] = $produkt_trans['beschreibung'];
+                                $p['detailname'] = $produkt_trans['detailname'];
+
+                            }
+
+                        }
+
+                        $arProduct[] = $p;
+
+                    }
+
+                }
+
+            }
 
 			$oCalculation->setWeight($sum['weight_gesamt']);
@@ -1610,5 +1402,4 @@
 					array(
 						"rnr" => $rnr,
-						"o_id" => $order_id,
 						"datum" => "NOW()"
 					)
@@ -1616,4 +1407,5 @@
 				
 				$oInvoice = \wpsg\wpsg_invoice::getInstance($r_id);
+                $oInvoice->setOrder($order_id);
 				
 				$oInvoice->setMeta('basket_data', json_encode($this->shop->view['basket']));
@@ -1627,5 +1419,6 @@
 				
 			}
-			
+
+            $this->shop->view['oInvoice'] = $oInvoice;
 			$this->shop->view['filename'] = $r_id;
 			$this->shop->view['filename_out'] = $rnr.'.pdf';
@@ -1659,13 +1452,8 @@
 					
 					//Mail versenden
-					
-					/**
-					 * Damit alte Rechnungen noch versÃ€ndet werden
-					 */
-					if (file_exists($this->getFilePath($order_id).$r_id.'.pdf')) { $file = $this->getFilePath($order_id).$r_id.'.pdf'; }
-					else if (file_exists($this->getFilePath($order_id).$rnr.'.pdf')) { $file = $this->getFilePath($order_id).$rnr.'.pdf'; }
-					else if (file_exists($this->getFilePath($order_id).'R'.$r_id.'.pdf')) { $file = $this->getFilePath($order_id).'R'.$r_id.'.pdf'; }
-					else { $file = $this->getFilePath($order_id).'R'.$rnr.'.pdf'; }  
- 
+
+                    $oInvoice = \wpsg\wpsg_invoice::getInstance(intval($r_id));
+
+                    $file = $oInvoice->getFilePath();
 					$file = $this->copyTemp($file, $rnr);
 					
@@ -1676,6 +1464,5 @@
 					
 					$empfaenger = $_REQUEST['wpsg_rechnungen_email']; 
-													 
-					$header = "";
+
 					$arFiles = array($file);
 	 
@@ -1755,5 +1542,5 @@
 
 			// GET Faelligkeitsdatum
-			if ($_REQUEST['wpsg_Multirechnung_faelligkeit'] == '1') {
+			if (($_REQUEST['wpsg_Multirechnung_faelligkeit']??'') == '1') {
 	
 				if (wpsg_checkInput($_REQUEST['wpsg_Multirechnung_faelligkeitsdatum'], WPSG_SANITIZE_DATE_EN)) $this->shop->view['faelligkeitdatum'] = date('d.m.Y', strtotime($_REQUEST['wpsg_Multirechnung_faelligkeitsdatum']));
@@ -1883,11 +1670,17 @@
 					array(
 						"rnr" => $rnr,
-						"o_ids" => implode(',', $order_ids),
 						"datum" => "NOW()"
 					)
 				);
-								
-				$oInvoice = \wpsg\wpsg_invoice::getInstance($r_id);				
-				$oInvoice->setMeta('version', '3');
+
+				$oInvoice = \wpsg\wpsg_invoice::getInstance($r_id);
+
+                foreach ($order_ids as $order_id) {
+
+                    $oInvoice->setOrder($order_id);
+
+                }
+
+                $oInvoice->setMeta('version', '3');
 				
 				foreach ($order_ids as $o_id) {
@@ -2045,5 +1838,4 @@
 				
 				$g_id = $this->db->ImportQuery(WPSG_TBL_RECHNUNGEN, array(
-					"o_id" => $_REQUEST['edit_id'],
 					"datum" => "NOW()",
 					"rnr" => "",
@@ -2051,5 +1843,8 @@
 					"storno_fee" => wpsg_q($storno_fee)
 				));
-												
+
+                $oInvoice = \wpsg\wpsg_invoice::getInstance($g_id);
+                $oInvoice->setOrder(intval($_REQUEST['edit_id']));
+
 				$this->shop->update_option("wpsg_gutschrift_start", ($gnr_nr + 1));
 				
@@ -2082,5 +1877,7 @@
 				if (!$bPreview) {
 
-					$file = $this->getFilePath($_REQUEST['edit_id']).'/'.$g_id.'.pdf';						
+                    $oInvoice = \wpsg\wpsg_invoice::getInstance(intval($g_id));
+                    $file = $oInvoice->getFilePath();
+
 					$file = $this->copyTemp($file, $gnr);
 				
@@ -2173,20 +1970,6 @@
 		 */
 		public function getInvoiceToOrder($order_id) {
-			
-			$arReturn = [];
-			
-			$arInvoiceId = $this->db->fetchAssocField("SELECT `id` FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `o_id` = '".wpsg_q($order_id)."' ");
-			
-			foreach ($arInvoiceId as $invoice_id) {
-				
-				try {
-					
-					$arReturn[] = \wpsg\wpsg_invoice::getInstance($invoice_id);
-
-				} catch (\Exception $e) { } 
-				
-			}
-			
-			return $arReturn;
+
+            return \wpsg\wpsg_invoice::findByOrderId($order_id);
 			
 		}
@@ -2276,199 +2059,10 @@
         public function getDownloadFile($r_id) {
 
-            $rechnung = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` WHERE `id` = '".wpsg_q($r_id)."'");
-            $file_path_old = str_replace('/wpsg/', '/', $this->getFilePath('')).$rechnung['o_id'].'/';
-
-			if ($rechnung['o_id'] == '0') $multiRechnung = intval(explode(",",  $rechnung['o_ids'])[0]);
-			$file_path_multi = str_replace('//', '/', $this->getFilePath('')).date('Y').'/'.date('m').'/multi/';
-
-            if ($rechnung['gnr'] != "")
-            {
-
-                /**
-                 * Damit alte Rechnungskorrekturen noch angezeigt werden
-                 */
-                if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['gnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).$rechnung['gnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).'G'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).'G'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).'G'.$rechnung['gnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).'G'.$rechnung['gnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                } //
-                else if (file_exists($file_path_old.'/'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/R'.$rechnung['gnr'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/R'.$rechnung['gnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/R'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/R'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/'.$rechnung['gnr'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/'.$rechnung['gnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['gnr'].'.pdf"');
-
-                }
-
-            }
-            else {
-
-                /**
-                 * Damit alte Rechnungen noch angezeigt werden
-                 */
-                if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).'R'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).'R'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($rechnung['o_id']).'R'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($rechnung['o_id']).'R'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }                
-				else if (file_exists($file_path_old.'/'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/R'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/R'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_old.'/R'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_old.'/R'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-
-				/**
-                 * Damit Multirechnungen angezeigt werden
-                 */
-				if (file_exists($this->getFilePath($multiRechnung).$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($multiRechnung).$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-              
-				}
-                else if (file_exists($this->getFilePath($multiRechnung).$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($multiRechnung).$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-               
-				}
-                else if (file_exists($this->getFilePath($multiRechnung).'R'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($multiRechnung).'R'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($this->getFilePath($multiRechnung).'R'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $this->getFilePath($multiRechnung).'R'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_multi.'/'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_multi.'/'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }                
-				else if (file_exists($file_path_multi.'/'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $file_path_multi.'/'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_multi.'/R'.$rechnung['rnr'].'.pdf'))
-                {
-
-                    $file = $file_path_multi.'/R'.$rechnung['rnr'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-                else if (file_exists($file_path_multi.'/R'.$rechnung['id'].'.pdf'))
-                {
-
-                    $file = $file_path_multi.'/R'.$rechnung['id'].'.pdf';
-                    header('Content-Disposition: attachment; filename="'.$rechnung['rnr'].'.pdf"');
-
-                }
-
-            }
-
-            return $file;
+            $oInvoice = \wpsg\wpsg_invoice::getInstance($r_id);
+            $file_path = $oInvoice->getFilePath();
+
+            header('Content-Disposition: attachment; filename="'.$file_path.'"');
+
+            return $file_path;
 
         }
@@ -2505,73 +2099,5 @@
 			 
 		} // public function getFrontendLink($r_id)
-		
-		/**
-		 * Gibt false (Wenn keine Rechnung aktiv) oder den Datensatz der aktuellen Rechnung zurÃŒck
-		 */
-		public function getOrderInvoice($order_id) {
-			
-			$invoice_db = $this->db->fetchRow("
-				SELECT
-					R.*
-				FROM
-					`".WPSG_TBL_RECHNUNGEN."` AS R
-				WHERE
-					R.`o_id` = '".wpsg_q($order_id)."' AND
-					R.`storno` = '0000-00-00 00:00:00' AND
-					R.`gnr` = ''
-				ORDER BY
-					R.`datum` DESC
-				LIMIT
-					1
-			");
-			
-			if (!wpsg_isSizedArray($invoice_db) || $invoice_db['id'] > 0) {
-				
-				return $invoice_db;
-				
-			}
-			
-			return false;
-			
-		} // public function getOrderInvoice($order_id)
-		
-		/**
-		 * Gibt false zurÃŒck (Wenn keine Rechnungskorrektur geschrieben ist, oder eine aktuelle Rechnung vorhanden ist) 
-		 * Ansonsten den Satz aus der Datenbank
-		 */
-		public function getOrderCredit($order_id)
-		{
-			
-			if ($this->getOrderInvoice($order_id) === false)
-			{
-				
-				$credit_db = $this->db->fetchRow("
-					SELECT
-						R.* 
-					FROM 
-						`".WPSG_TBL_RECHNUNGEN."` AS R
-					WHERE
-						R.`o_id` = '".wpsg_q($order_id)."' AND
-						R.`rnr` = '' AND
-						R.`gnr` != ''
-					ORDER BY
-						R.`datum` DESC
-					LIMIT
-						1
-				");
-				
-				if ($credit_db['id'] > 0)
-				{
-					
-					return $credit_db;
-					
-				}
-				
-			}
-			
-			return false;			
-			
-		} // public function getOrderCredit($order_id)
-		
+
 		/**
 		 * Gibt die Rechnungstexte in der korrekten Sprache und mit ÃŒbersetzen Platzhaltern zurÃŒck
@@ -2647,75 +2173,27 @@
 			
 		} // function foottext_list()
-		
-        public function getFilePathWithFilename($order_id, $url = false) {
-		    
-		    $invoice_db = $this->getOrderInvoice($order_id);
-		    
-		    $file = $this->getFilePath($order_id, $url).$invoice_db['id'].'.pdf';
-		    
-		    return $file;
-		    
+
+        public function getPaperPath($url = false) {
+
+            if ($this->shop->isMultiBlog()) {
+
+                $path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
+                $url_content = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
+
+                if ($url) $strReturn = $url_content.'/';
+ 				else $strReturn = $path.'/';
+
+            } else {
+
+                $path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/';
+
+                if ($url) $strReturn = WPSG_URL_CONTENT.'uploads/wpsg/wpsg_rechnungen/';
+                else $strReturn = $path;
+
+            }
+
+            return $strReturn;
+
         }
-        
-		/*
-		 * Gibt den Absoluten Pfad zurÃŒck wo die Rechnungen gespeichert sind
- 		 * Ist der Parameter $url auf true so wird der relative Pfad fÃŒr die Ausgabe in URLs zurÃŒckgegeben
- 		 */
- 		public function getFilePath($order_id, $url = false) { 
- 		  	
- 			if ($order_id == '') {
- 			    
- 			    // Briefpapier/Logo
- 				if ($this->shop->isMultiBlog()) {
- 					
- 					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
- 					
- 					$url_content = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/';
- 					
- 					if ($url) $strReturn = $url_content.'/'.$order_id.'/';
- 					else $strReturn = $path.'/'.$order_id.'/';
- 					
- 				} else {
- 					
- 					$path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/';
- 					
- 					if ($url) $strReturn = WPSG_URL_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$order_id.'/';
- 					else $strReturn = $path.$order_id.'/';
- 					
- 				}
- 				
- 			} else {	
- 			    
- 			    // Rechnung aus Bestellung
-
- 				$deliverynote = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_RECHNUNGEN."` AS DN WHERE `o_id` = '".wpsg_q($order_id)."' ");
- 				$datum = $deliverynote['datum'];
- 				$ym = date('Y/m/', strtotime($datum));
- 				
- 				if ($this->shop->isMultiBlog()) {
- 					
- 					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/'.$ym;
- 					
- 					$url_content = WPSG_URL_CONTENT.WPSG_MB_UPLOADS.'/wpsg/wpsg_rechnungen/'.$ym;
- 					
- 					if ($url) $strReturn = $url_content.'/'.$order_id.'/';
- 					else $strReturn = $path.'/'.$order_id.'/';
- 					
- 				} else {
- 					
- 					$path = WPSG_PATH_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$ym;
- 					
- 					if ($url) $strReturn = WPSG_URL_CONTENT.'uploads/wpsg/wpsg_rechnungen/'.$ym.$order_id.'/';
- 					else $strReturn = $path.$order_id.'/';
- 					
- 				}
- 				
- 			} 			
-						
-			$this->shop->protectDirectory($path);
-						
-			return $strReturn;
-			 
- 		} // private function getFilePath($produkt_id, $url = false)
 
  		/**
Index: /views/mods/mod_kundenverwaltung/order.phtml
===================================================================
--- /views/mods/mod_kundenverwaltung/order.phtml	(revision 8213)
+++ /views/mods/mod_kundenverwaltung/order.phtml	(revision 8214)
@@ -23,12 +23,24 @@
 				<strong><?php echo __('Bestellstatus', 'wpsg'); ?>:</strong>&nbsp;
 					<?php echo $this->arStatus[$order['status']]; ?>
-					<?php if ($this->hasMod('wpsg_mod_rechnungen')) { ?>
-					
-						<?php if ($r = $this->callMod('wpsg_mod_rechnungen', 'getOrderInvoice', array($order['id']))) { ?>
-						<a href="<?php echo $this->callMod('wpsg_mod_rechnungen', 'getFrontendLink', array($r['id'])); ?>"><?php echo wpsg_translate(__('Rechnung #1#', 'wpsg'), $r['rnr']); ?></a>
-						<?php } else if ($r = $this->callMod('wpsg_mod_rechnungen', 'getOrderCredit', array($order['id']))) { ?>
-						<a href="<?php echo $this->callMod('wpsg_mod_rechnungen', 'getFrontendLink', array($r['id'])); ?>"><?php echo wpsg_translate(__('Rechnungskorrektur #1#', 'wpsg'), $r['gnr']); ?></a>
-						<?php } ?>
-						
+					<?php if ($this->hasMod('wpsg_mod_rechnungen')) {
+
+                        $arInvoice = \wpsg\wpsg_invoice::findByOrderId(intval($order['id']));
+
+                        ?>
+
+                        <?php foreach ($arInvoice as $oInvoice) { ?>
+
+                            <?php if ($oInvoice->isInvoice()) { ?>
+
+                                <a href="<?php echo $this->callMod('wpsg_mod_rechnungen', 'getFrontendLink', [$oInvoice->getId()]); ?>"><?php echo wpsg_translate(__('Rechnung #1#', 'wpsg'), $oInvoice->getNr()); ?></a>
+
+                            <?php } else if ($oInvoice->isStorno()) { ?>
+
+                                <a href="<?php echo $this->callMod('wpsg_mod_rechnungen', 'getFrontendLink', [$oInvoice->getId()]); ?>"><?php echo wpsg_translate(__('Rechnungskorrektur #1#', 'wpsg'), $oInvoice->getNr()); ?></a>
+
+                            <?php } ?>
+
+                        <?php } ?>
+
 					<?php } ?>
 				<br />
Index: /views/mods/mod_rechnungen/accounting_pdf.phtml
===================================================================
--- /views/mods/mod_rechnungen/accounting_pdf.phtml	(revision 8213)
+++ /views/mods/mod_rechnungen/accounting_pdf.phtml	(revision 8214)
@@ -10,5 +10,8 @@
   
 	global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top;
-	 
+
+    /** @var wpsg\wpsg_invoice|null $oInvoice */
+    $oInvoice = $this->view['oInvoice'];
+
 	// Positionierung der Absenderadresszeile
 	$absender_left				= 25;
@@ -48,22 +51,22 @@
 			$pdf->AddPage();
 			
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf"))
-			{
-				
-				$pagecount = $pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf"); 
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf"))
+			{
+				
+				$pagecount = $pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf");
 				$tplidx = $pdf->importPage(1, '/MediaBox'); 
 				$pdf->useTemplate($tplidx, 0, 0, 210); 
 				
 			}
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg"))
-			{
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
-			}
-			
-			
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg"))
-			{
-	
-				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg");
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg"))
+			{
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
+			}
+			
+			
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg"))
+			{
+	
+				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg");
 				
 				//wpsg_debug($width.":".$height);
@@ -72,5 +75,5 @@
 				$hPix = (25.4 * $height) / 96;  
 				
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg", 210 - $wPix, 0, $wPix, $hPix);
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg", 210 - $wPix, 0, $wPix, $hPix);
 				
 			}
@@ -888,12 +891,5 @@
 
 	}
-	
-	if (!file_exists($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id']))))
-	{
-		
-		mkdir($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id'])), 0777, true);
-		
-	}
-	
+
 	$this->callMods('wpsg_mod_rechnungen_pdf', array(&$pdf, &$this->view['data']['id'], &$this->view['preview'], &$this->view['invoice']));
 	
@@ -901,7 +897,4 @@
 
     ob_end_clean();
-
-	wpsg_debug($pdf->Output($filename, 'I'));
-	die();
 
 	if ($this->view['preview']) {
@@ -911,5 +904,5 @@
 	} else {
 		
-		$pdf->Output($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id'])).$filename, 'F');
+		$pdf->Output($oInvoice->getFilePath(), 'F');
 		
 		// Hier wird der Dateiname an FPD ÃŒbergeben. Er soll sich aus der Rechnungsnummer ergeben, auch wenn das Dokument ÃŒber die ID gespeichert ist.
Index: /views/mods/mod_rechnungen/invoice_pdf.phtml
===================================================================
--- /views/mods/mod_rechnungen/invoice_pdf.phtml	(revision 8213)
+++ /views/mods/mod_rechnungen/invoice_pdf.phtml	(revision 8214)
@@ -10,5 +10,8 @@
 	
 	global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top;
-	
+
+    /** @var \wpsg\wpsg_invoice|null $oInvoice */
+    $oInvoice = $this->view['oInvoice']??null;
+
 	// Positionierung der Absenderadresszeile
 	$absender_left				= 25;
@@ -48,20 +51,20 @@
 			$pdf->AddPage();
 
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf")) {
-				
-				$pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf");
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf")) {
+				
+				$pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf");
 				$tplidx = $pdf->importPage(1, '/MediaBox');
 				$pdf->useTemplate($tplidx, 0, 0, 210);
 				
-			} else if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg")) {
-				
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
-				
-			}
-
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg"))
-			{
-				
-				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg");
+			} else if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg")) {
+				
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
+				
+			}
+
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg"))
+			{
+				
+				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg");
 				
 				// Umrechnung von Inch zu Pixel
@@ -90,5 +93,5 @@
 				
 				$pdf->SetAlpha($alpha);
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg", $abscissa, $ordinate, $wPix, $hPix);
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg", $abscissa, $ordinate, $wPix, $hPix);
 				$pdf->SetAlpha(1);
 				
@@ -97,5 +100,5 @@
 			// Absenderadresszeile (Wird in der Konfiguration hinterlegt)
 			$pdf->SetFont('Arial', '', 6);
-			$pdf->Text($absender_left, $absender_top, $shop->replaceUniversalPlatzhalter(__($shop->get_option("wpsg_rechnungen_adresszeile"), 'wpsg'), $shop->view['data']['id']));
+			$pdf->Text($absender_left, $absender_top, $shop->replaceUniversalPlatzhalter(__($shop->get_option("wpsg_rechnungen_adresszeile"), 'wpsg'), $shop->view['data']['id']??0));
 			
 			if (wpsg_getStr($shop->view['kunde']['kuerzel']) != "") $shop->view['kunde']['kuerzel'] = $shop->view['kunde']['kuerzel'].'-';
@@ -103,8 +106,8 @@
 			// Adresse des Kunden
 			$pdf->SetFont('Arial', '', 12);
-			$pdf->Text($adress_left, $adress_top, $shop->view['kunde']['firma']);
-			$pdf->Text($adress_left, $adress_top + 5, $shop->view['kunde']['vname'].' '.$shop->view['kunde']['name']);
-			$pdf->Text($adress_left, $adress_top + 10, $shop->view['kunde']['strasse'].' '.wpsg_getStr($shop->view['kunde']['nr']));
-			$pdf->Text($adress_left, $adress_top + 15, $shop->view['kunde']['plz'].' '.$shop->view['kunde']['ort']);
+			$pdf->Text($adress_left, $adress_top, $shop->view['kunde']['firma']??'');
+			$pdf->Text($adress_left, $adress_top + 5, ($shop->view['kunde']['vname']??'').' '.($shop->view['kunde']['name']??''));
+			$pdf->Text($adress_left, $adress_top + 10, ($shop->view['kunde']['strasse']??'').' '.($shop->view['kunde']['nr']??''));
+			$pdf->Text($adress_left, $adress_top + 15, ($shop->view['kunde']['plz']??'').' '.($shop->view['kunde']['ort']??''));
 
 			if ($shop->get_option("wpsg_mod_rechnungen_hideCountry") == '0') $pdf->Text($adress_left, $adress_top + 20, strtoupper($shop->view['oOrder']->getInvoiceCountryName()));
@@ -901,11 +904,4 @@
 	}
 	
-	if (!file_exists($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id']))))
-	{
-		
-		mkdir($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id'])), 0777, true);
-		
-	}
-	
 	$this->callMods('wpsg_mod_rechnungen_pdf', array(&$pdf, &$this->view['data']['id'], &$this->view['preview'], &$this->view['invoice']));
 	
@@ -920,5 +916,5 @@
 	} else {
 		
-		$pdf->Output($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array($this->view['data']['id'])).$filename, 'F');
+		$pdf->Output($oInvoice->getFilePath(), 'F');
 		
 		// Hier wird der Dateiname an FPD ÃŒbergeben. Er soll sich aus der Rechnungsnummer ergeben, auch wenn das Dokument ÃŒber die ID gespeichert ist.
@@ -927,3 +923,2 @@
 	}
 
-?>
Index: /views/mods/mod_rechnungen/multi_invoice_pdf.phtml
===================================================================
--- /views/mods/mod_rechnungen/multi_invoice_pdf.phtml	(revision 8213)
+++ /views/mods/mod_rechnungen/multi_invoice_pdf.phtml	(revision 8214)
@@ -10,5 +10,5 @@
 	require_once WPSG_PATH_LIB.'wpsg_fpdf.class.php';
 	
-	global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top, $rhead_left, $rhead_top, $sum_multi_offset, $pdf;
+	global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top, $rhead_left, $rhead_top, $sum_multi_offset, $pdf, $data;
 	 
 	// Positionierung der Absenderadresszeile
@@ -34,9 +34,15 @@
 	// Anzahl an Produkten pro Seite
 	$prod_break					= $this->get_option('wpsg_rechnungen_pdfperpage');
-	
-	$arCalculation = $this->view['basket']['arCalculation'];
+
+    /*
+    $arCalculation = $this->view['basket']['arCalculation'];
     $data = $this->view['multi_data']['orders'][0]['data'];
     $sum = $this->view['multi_data']['orders'][0]['sum'];
-	
+	*/
+
+    $arCalculation = array_values($this->view['multi_data']['order_data'])[0]['arCalculation'];
+    $data = $this->view['data'];
+    $sum = $arCalculation['sum'];
+
 	if ($this->getFrontendTaxView() === WPSG_NETTO) $taxdisplay = 'netto';
 	else $taxdisplay = 'brutto';
@@ -46,26 +52,26 @@
 		function AddRechnungPage($shop, $pdf) {
 
-			global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top, $offset, $sum_multi_offset;
+			global $absender_left, $absender_top, $adress_left, $adress_top, $rdata_left, $rdata_top, $offset, $sum_multi_offset, $data;
 			
 			$pdf->AddPage();
             $sum_multi_offset = 0;
 			
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf")) {
-				
-				$pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.pdf");
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf")) {
+				
+				$pdf->setSourceFile($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.pdf");
 				$tplidx = $pdf->importPage(1, '/MediaBox');
 				$pdf->useTemplate($tplidx, 0, 0, 210);
 				
-			} else if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg")) {
-				
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
+			} else if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg")) {
+				
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_bp.jpg", 0, 0, 210, 297, 'jpg');
 				
 			}
 			
 			
-			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg"))
+			if (file_exists($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg"))
 			{
 				
-				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg");
+				list($width, $height, $type, $attr) = getimagesize($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg");
 				
 				// Umrechnung von Inch zu Pixel
@@ -94,10 +100,10 @@
 				
 				$pdf->SetAlpha($alpha);
-				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getFilePath', array(''))."wpsg_rechnungen_logo.jpg", $abscissa, $ordinate, $wPix, $hPix);
+				$pdf->image($shop->callMod('wpsg_mod_rechnungen', 'getPaperPath', array())."wpsg_rechnungen_logo.jpg", $abscissa, $ordinate, $wPix, $hPix);
 				$pdf->SetAlpha(1);
 				
 			}
-			
-			// Absenderadresszeile (Wird in der Konfiguration hinterlegt)
+
+            // Absenderadresszeile (Wird in der Konfiguration hinterlegt)
 			$pdf->SetFont('Arial', '', 6);
 			$pdf->Text($absender_left, $absender_top, $shop->replaceUniversalPlatzhalter(__($shop->get_option("wpsg_rechnungen_adresszeile"), 'wpsg'), $data['id']));
@@ -189,5 +195,5 @@
     $rhead_count = 1;
     $sum_multi_offset = 0;
-    $orders = $this->view['multi_data']['orders']; 
+    // $orders = $this->view['multi_data']['orders'];
 
 	// noMwSt
@@ -238,6 +244,4 @@
         $pdf->Text($rhead_left + 155, $rhead_top + $sum_multi_offset, __("Best. Nr.", "wpsg"));
         $pdf->Text($rhead_left + 155, $rhead_top + $sum_multi_offset + 6, $oOrder->getNr());
-        
-        $summe = 0;
 
         $bKopf = false; $pnr = 1; $offset = 0; $count = 0; 
@@ -469,7 +473,5 @@
             $pnr ++;
             $count ++;
-            
-            $summe += $p['price'] * $p['menge'];
-            
+
             if ($pdf->getY() > 220 || ($count >= $prod_break && sizeof($oOrder->getOrderProducts()) > ($pnr - 1))) {
                 
@@ -898,5 +900,4 @@
 	if ($this->view['preview']) {
 
-		//$pdf->Output($this->callMod('wpsg_mod_rechnungen', 'getFilePath', array('multi')).$filename, 'F');
 		$pdf->Output();
 		
Index: /views/mods/mod_rechnungen/order_view_orderdata_after.phtml
===================================================================
--- /views/mods/mod_rechnungen/order_view_orderdata_after.phtml	(revision 8213)
+++ /views/mods/mod_rechnungen/order_view_orderdata_after.phtml	(revision 8214)
@@ -203,9 +203,9 @@
 							
 							if (ok) {
-                                
+
 								if (event.target.getAttribute("id") === 'invoice_wpsg_rechnungen_submit') {
                                         
-                                    window.setTimeout(function() { location.href = '<?php 
-                                
+                                    window.setTimeout(function() { location.href = '<?php
+
                                         echo wpsg_admin_url('Order', 'view', ['edit_id' => $oOrder->getId()]);
                                     
Index: /views/order/view_general.phtml
===================================================================
--- /views/order/view_general.phtml	(revision 8213)
+++ /views/order/view_general.phtml	(revision 8214)
@@ -35,6 +35,9 @@
     <?php echo wpsg_drawForm_Checkbox('sendMail', __('Kunden informieren', 'wpsg'), 0); ?>
 
-    <?php if ($this->hasMod('wpsg_mod_rechnungen')) { $db_invoice = $this->callMod('wpsg_mod_rechnungen', 'getOrderInvoice', [$this->view['oOrder']->id]); ?>
-        <?php if (wpsg_isSizedInt($db_invoice['id'])) { ?>
+    <?php if ($this->hasMod('wpsg_mod_rechnungen')) {
+
+        $arInvoice = \wpsg\wpsg_invoice::findByOrderId($this->view['oOrder']->id);
+
+        if (sizeof($arInvoice) > 0) { ?>
             <script>
 
