<?php
/*
 *  This file is part of open3A.

 *  open3A is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.

 *  open3A is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  2007 - 2020, open3A GmbH - Support@open3A.de
 */
class GRLBM extends PersistentObject implements iCloneable, iRepeatable, iDeletable2 {

	public $AdresseObj = null;
	public $isCopy = false;
	protected $letterType = "";
	public $CustomizerTeilzahlungen = false;
	public $CustomizerPostenAddLabelInsertOrigin = true;
	protected $newPostenMessageBestand = "";
	public static $ignoreLock = false;
	public static $lockable = array("R", "G", "T");
	
	// <editor-fold defaultstate="collapsed" desc="getOnDeleteEvent">
	public function getOnDeleteEvent(){
		return "function() { contentManager.reloadFrameRight(); contentManager.reloadFrameLeft(); }";
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getOnDeleteQuestion">
	public function getOnDeleteQuestion(){
		return "Soll dieser Beleg und alle Positionen wirklich gelöscht werden?";
	}
	// </editor-fold>
	
	function __construct($ID, $parsers = true){
		#$this->myAdapterClass = "GRLBMAdapter";
		parent::__construct($ID);
		
		if($parsers){
			$this->setParser("datum","Util::CLDateParser");
			$this->setParser("lieferDatum","Util::CLDateParserE");
			#$this->setParser("rabatt","Util::CLNumberParserZ");
			#$this->setParser("rabattInW","Util::CLNumberParserZ");
			$this->setParser("leasingrate","Util::CLNumberParserZ");
			$this->setParser("payedWithSkonto","Util::CLNumberParserZ");
			$this->setParser("GRLBMpayedDate","Util::CLDateParserE");
			#$this->setParser("versandkosten", "Util::CLNumberParserZ");
			#$this->setParser("versandkostenMwSt", "Util::CLNumberParserZ");
		}
		
		$this->customize();
	}

	// <editor-fold defaultstate="collapsed" desc="makeAB">
	public function makeAB(){
		$this->changeA("isB", "1");
		$this->changeA("isA", "0");
		$this->changeA("isEMailedTime", "0");
		$this->changeA("isEMailed", "0");
		#$this->changeA("isPayed", "1");
		$this->changeA("prefix", Stammdaten::getActiveStammdaten()->getPrefix("B"));

		$T = new Textbausteine();
		$TBO = $T->getTBs("oben", "B", true);
		
		$T = new Textbausteine();
		$TBU = $T->getTBs("unten", "B", true);
		
		$T = new Textbausteine();
		$TBZ = $T->getTBs("zahlungsbedingungen", "B", true);
		
		$this->changeA("textbausteinObenID", isset($TBO[0][0]) ? $TBO[0][0] : 0);
		$this->changeA("textbausteinUntenID", isset($TBU[0][0]) ? $TBU[0][0] : 0);
		$this->changeA("zahlungsbedingungenID", isset($TBZ[0][0]) ? $TBZ[0][0] : 0);
		
		$Auftrag = new Auftrag($this->A("AuftragID"));
		if(Session::isPluginLoaded("Kunden") AND $Auftrag->A("kundennummer") > 0){
			$K = Kappendix::getKappendixToKundennummer($Auftrag->A("kundennummer"));
			if($K AND $K->A("BTextbausteinOben"))
				$this->changeA("textbausteinObenID", $K->A("BTextbausteinOben"));
			
			if($K AND $K->A("BTextbausteinUnten"))
				$this->changeA("textbausteinUntenID", $K->A("BTextbausteinUnten"));
			
			if($K AND $K->A("BZahlungsbedingungen"))
				$this->changeA("zahlungsbedingungenID", $K->A("BZahlungsbedingungen"));
		}
		$this->changeA("datum", Util::CLDateParser(time()));
		#$this->changeA("lieferDatum", Util::CLDateParser(time()));

		$this->saveMe(true, false);

		#$Auftrag = new Auftrag($this->A("AuftragID"));
		$Auftrag->updateStatus("B", true);
		
		// <editor-fold defaultstate="collapsed" desc="Aspect:jP">
		return Aspect::joinPoint("after", $this, __METHOD__, true);
		// </editor-fold>
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getRepeatableActions">
	public function getRepeatableActions(){
		$t = array("cloneForRepeatable" => "kopieren", "cloneAndMail" => "kopieren und per E-Mail an Kunde verschicken");
		#if($_SESSION["S"]->checkForPlugin("mDrucker")) {
		#	$t["cloneAndPrintOriginal"] = "kopieren und Original drucken";
		#	$t["cloneAndPrintWithCopy"] = "kopieren und Original und Kopie drucken";
		#}

		if(Session::isPluginLoaded("SP"))
			$t["cloneAndMailSigned"] = "kopieren und über signaturportal an Kunde verschicken";

		if(Session::isPluginLoaded("PL"))
			$t["cloneAndMailSigned"] = "kopieren und über PixelLetter an Kunde verschicken";
		
		return $t;
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getSumOfPosten">
	private $ges_netto;
	private $ges_brutto;
	private $ges_ek1;
	private $ges_mwst;
	private $mwst;
	public function getSumOfPosten($returnArray = false, $saveValues = false, $calcUpToPostenID = null){
		$this->loadMe();
		$aC = new mPosten();
		$aC->addAssocV3("GRLBMID", "=", $this->getID());
		
		$this->ges_netto = array();
		$this->ges_brutto = array();
		$this->ges_mwst = array();
		$this->ges_ek1 = 0;
		$this->mwst = array();
		$inAltTitle = false;
		$inRabattTitle = false;
		$inRabattTitleValue = 0;
		while($t = $aC->getNextEntry()){
			if($t->A("PostenAddLine") AND strpos($t->A("PostenAddLine"), "[") === 0 OR strpos($t->A("PostenAddLine"), "{") === 0){
				$titles = json_decode($t->A("PostenAddLine"));
				foreach($titles AS $Tit){
					if(isset($Tit->isalternative) AND $Tit->isalternative == "1")
						$inAltTitle = true;
					if(isset($Tit->isalternative) AND $Tit->isalternative == "0")
						$inAltTitle = false;
					
					if(isset($Tit->rabatt) AND $Tit->rabatt > 0){
						$inRabattTitle = true;
						$inRabattTitleValue = $Tit->rabatt;
					}
					if(isset($Tit->rabatt) AND ($Tit->rabatt == "" OR $Tit->rabatt == 0))
						$inRabattTitle = false;
				}
			}
			
			if($inRabattTitle AND $t->A("rabatt") == 0)
				$t->changeA("rabatt", $inRabattTitleValue);
			
			if($inAltTitle)
				$t->changeA("PostenIsAlternative", "3");
			
			if($t->A("PostenAddSum")){
				$inAltTitle = false;
				$inRabattTitle = false;
			}
			
			if($t->A("PostenIsAlternative") !== null AND $t->A("PostenIsAlternative") > 0)
				continue;
			
			$this->getSumOfPostenInt($t);
			
			
			
			if($calcUpToPostenID != null AND $calcUpToPostenID == $t->getID())
				break;
		}

		
		$rabatt = $this->A("rabatt");
		if($rabatt != 0){
			$aC = new mPosten();
			$aC->addAssocV3("PostenID", "=", "-9999999"); //don't load a thing!
			foreach($this->ges_netto as $key => $value)
				$aC->addVirtualPosten(1,"", "", "", $value * ($rabatt / 100) * -1, $key, 0);
			
			while($t = $aC->n())
				$this->getSumOfPostenInt($t);
			
		}
		
		/**
		 * VERSANDKOSTEN
		 */
		$Versand = $this->A("versandkosten") * 1;
		if($Versand != 0 AND $calcUpToPostenID == null){

			if(!isset($this->ges_brutto[$this->A("versandkostenMwSt")]))
				$this->ges_brutto[$this->A("versandkostenMwSt")] = 0;
			
			if(!isset($this->ges_netto[$this->A("versandkostenMwSt")]))
				$this->ges_netto[$this->A("versandkostenMwSt")] = 0;

			
			$this->ges_brutto[$this->A("versandkostenMwSt")] += $Versand * ((100 + $this->A("versandkostenMwSt")) / 100);
			$this->ges_netto[$this->A("versandkostenMwSt")] += $Versand;
			$this->ges_ek1 += $Versand;

			if(array_search($this->A("versandkostenMwSt"), $this->mwst) === false)
				$this->mwst[] = $this->A("versandkostenMwSt");
			
		}
		
		
		//Netto-Modus: fixes mwst and gros sum afterwards
		if($this->A("GRLBMCalcModeSum") == 1)
			foreach($this->ges_netto AS $key => $value){
				$ust = Util::kRound($value * ($key / 100));
				$this->ges_brutto[$key] = $value + $ust;
				$this->ges_mwst[$key] = $ust;
			}

		//Brutto-Modus: fixes mwst and net sum afterwards
		if($this->A("GRLBMCalcModeSum") == 0)
			foreach($this->ges_netto AS $key => $value){
				$ust = $this->ges_brutto[$key] - Util::kRound($this->ges_brutto[$key] / (1 + $key / 100));
				$this->ges_netto[$key] = $this->ges_brutto[$key] - $ust; //Fucks up with 2 items with 0,81 net each: net result is 1,61 //20190816: seems to work with altered ust calculation (from gros)
				$this->ges_mwst[$key] = $ust;
			}

		
		if($this->A("isAbschlussrechnung") == "1" AND $calcUpToPostenID == null){
			$oC = anyC::get("GRLBM");
			$oC->addAssocV3("AuftragID", "=", $this->A("AuftragID"));
			$oC->addAssocV3("GRLBMID", "!=", $this->getID());
			$oC->addAssocV3("isR", "=", "1");
			$oC->addAssocV3("isPayed", "!=", "2"); //storniert
			$oC->addAssocV3("isAbschlussrechnung", "=", "0"); //keine anderen Abschlussrechnungen!
			
			while($r = $oC->getNextEntry()){
				$subSum = $r->getSumOfPosten(true);
				
				if($r->A("GRLBMTeilzahlungenSumme") !== null AND $r->A("GRLBMTeilzahlungenSumme") > 0){
					$mwst = array_keys($subSum[5])[0];
					
					$this->ges_brutto[$mwst] -= $r->A("GRLBMTeilzahlungenSumme");
					$netto = Util::kRound($r->A("GRLBMTeilzahlungenSumme") / ((100 + $mwst) / 100));
					$this->ges_netto[$mwst] -= $netto;
					$this->ges_mwst[$mwst] -= $r->A("GRLBMTeilzahlungenSumme") - $netto;
					
					continue;
				}
				
				#$subSum = $r->getSumOfPosten(true);
				
				foreach($subSum[5] AS $mwst => $value)
					$this->ges_brutto[$mwst] -= $value;
				
				foreach($subSum[6] AS $mwst => $value)
					$this->ges_netto[$mwst] -= $value;
				
				foreach($subSum[7] AS $mwst => $value)
					$this->ges_mwst[$mwst] -= $value;
				
				$this->ges_ek1 -= $subSum[4];
				
			}
		}
		
		$ges_brutto = array_sum($this->ges_brutto);
		$ges_brutto = Aspect::joinPoint("alterGesBrutto", $this, __METHOD__, array($ges_brutto), $ges_brutto);
		$this->ges_mwst = Aspect::joinPoint("alterGesMwSt", $this, __METHOD__, array($this->ges_mwst), $this->ges_mwst);
		
		
		if($saveValues) {
			$this->changeA("nettobetrag", array_sum($this->ges_netto));
			$this->changeA("bruttobetrag", Util::kRound($ges_brutto));
			$this->changeA("steuern", array_sum($this->ges_mwst));
			$this->changeA("ek1betrag", $this->ges_ek1);
			$this->saveMe();
		}
		

		if(!$returnArray)
			return $ges_brutto;
		
		return array(
			array_sum($this->ges_netto), 
			array_sum($this->ges_mwst), #1
			$ges_brutto, 
			$this->mwst, #3 
			$this->ges_ek1, 
			$this->ges_brutto, #5
			$this->ges_netto, 
			$this->ges_mwst); #7
	}
	
	private function getSumOfPostenInt($t){
		$prices = $t->prices($this);
		
		if(!isset($this->ges_netto[$t->A("mwst")]))
			$this->ges_netto[$t->A("mwst")] = 0;
		
		if(!isset($this->ges_brutto[$t->A("mwst")]))
			$this->ges_brutto[$t->A("mwst")] = 0;
		
		if(!isset($this->ges_mwst[$t->A("mwst")]))
			$this->ges_mwst[$t->A("mwst")] = 0;
		
		
		$this->ges_netto[$t->A("mwst")] += $prices["nettoGesamt"];
		$this->ges_brutto[$t->A("mwst")] += $prices["bruttoGesamt"];
		$this->ges_mwst[$t->A("mwst")] += $prices["mwstBetragGesamt"];
		$this->ges_ek1 += $prices["ek1Gesamt"];
		
		
		if(array_search($t->A("mwst"), $this->mwst) === false)
			$this->mwst[] = $t->A("mwst");
		
		/*if($t->A("steuer") !== null){
			if(!isset($this->artikelsteuern[$t->A("steuer")]))
				$this->artikelsteuern[$t->A("steuer")] = 0;

			$this->artikelsteuern[$t->A("steuer")] += $nettopreis * ($t->A("steuer") / 100);
		}*/

	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneForRepeatable">
	public function cloneForRepeatable(Repeatable $R){
		$this->loadMe();

		$_SESSION["BPS"]->registerClass("cloneGRLBM");
		$_SESSION["BPS"]->setACProperty("datum", date("d.m.Y", $R->getNextDate()));
		$_SESSION["BPS"]->setACProperty("lieferDatum", date("d.m.Y", $R->getNextDate()));
		if($R->A("RepeatableInterval") == "1Month")
			$_SESSION["BPS"]->setACProperty("GRLBMCustomField3", date("m/Y", $R->getNextDate()));
		if($R->A("RepeatableInterval") == "1Year")
			$_SESSION["BPS"]->setACProperty("GRLBMCustomField3", date("Y", $R->getNextDate()));

		$this->changeA("GRLBMReferenz", "Repeatable:".$R->getID());
		
		return $this->cloneMe(true);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="printMe">
	private function printMe($copy){
		if($this->A == null) $this->loadMe();
		
		$Auftrag = new AuftragGUI($this->A->AuftragID);
		$Auftrag->loadMe();
		#$_SESSION["BPS"]->registerClass("GRLBMGUI");
		#$_SESSION["BPS"]->setACProperty("myID", $this->ID);
		
		$_SESSION["BPS"]->registerClass("mGRLBMGUI");
		$_SESSION["BPS"]->setACProperty("type", $this->getMyPrefix());
		
		$Auftrag->printLetter($this->ID, $copy ? "true" : "false");
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneAndPrintOriginal">
	public function cloneAndPrintOriginal(Repeatable $R){
		$newID = $this->cloneForRepeatable($R);

		$G = new GRLBM($newID);
		$G->printMe(false);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneAndMail">
	public function cloneAndMail(Repeatable $R){
		$newID = $this->cloneForRepeatable($R);

		#$_SESSION["BPS"]->setProperty("Brief","GRLBMID",$newID);

		$G = new GRLBM($newID);

		$A = new AuftragGUI($G->A("AuftragID"));
		try {
			$A->sendViaEmail($newID, "", "", "", false);
		} catch(Exception $e){
			return "ERROR: ".$e->getMessage()."\n";
		}
		
		return $newID;
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneAndMailSigned">
	public function cloneAndMailSigned(Repeatable $R){
		$newID = $this->cloneForRepeatable($R);

		$_SESSION["BPS"]->setProperty("Brief","GRLBMID",$newID);

		$G = new GRLBM($newID);

		$A = new AuftragGUI($G->A("AuftragID"));
		try {
			$A->sendGRLBMToCustomer($newID, "sign", false);
		} catch(Exception $e){
			return "ERROR: ".$e->getMessage()."\n";
		}
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneAndPrintWithCopy">
	public function cloneAndPrintWithCopy(Repeatable $R){
		$newID = $this->cloneForRepeatable($R);
		
		$G = new GRLBM($newID);
		$G->printMe(false);
		$G->printMe(true);
	}
	//  </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="cloneMe">
	function cloneMe($quiet = false, $AuftragID = null, $date = null, $updatePrices = false){
		if($this->A == null) 
			$this->loadMe();
		
		$_SESSION["BPS"]->setActualClass("clone".get_class($this));
		$bps = $_SESSION["BPS"]->getAllProperties();
		if(count($bps) > 0 AND $bps != -1)
			foreach($bps AS $key => $value)
				if(isset($this->A->$key))
					$this->A->$key = $value;
		
		
		if($AuftragID !== null)
			$this->A->AuftragID = $AuftragID;
		$this->A->nummer = mStammdaten::getNextNumberFor($this->getMyPrefix(), new Auftrag($this->A("AuftragID")));
		if(!isset($bps["datum"]))
			$this->A->datum = Util::CLDateParser(time());#date("d.m.Y");
		
		if($date)
			$this->A->datum = Util::CLDateParser($date);
		
		if(!isset($bps["lieferDatum"]))
			$this->A->lieferDatum = Util::CLDateParser(time());#date("d.m.Y");
		
		$this->A->isPrinted = 0;
		$this->A->isPrintedCopy = 0;
		$this->A->isPayed = 0;
		$this->A->isEMailed = 0;
		
		if($this->A("isB") == "1"){
			$this->A->isB = 0;
			$this->A->isA = 1;
		}
		$oldGRLBMID = $this->ID;


		$Auftrag = new Auftrag($this->A->AuftragID);
		$Auftrag->updateDatum($this->hasParsers ? Util::CLDateParser($this->A("datum"), "store") : $this->A("datum"));

		if(isset($this->A->zahlungsziel) AND $Auftrag->A("kundennummer") > 0){
			$Kappendix = Kappendix::getKappendixToKundennummer($Auftrag->A("kundennummer"));
			if($Kappendix){
				$this->A->zahlungsziel = time() + $Kappendix->A("KappendixZahlungsziel") * 3600 * 24;

				if($this->hasParser("zahlungsziel"))
					$this->A->zahlungsziel = Util::CLDateParser ($this->A->zahlungsziel);
			}
		}

		$newGRLBMID = $this->newMe();
		
		$_SESSION["BPS"]->registerClass("clonePosten");
		$_SESSION["BPS"]->setACProperty("GRLBMID",$newGRLBMID);
		
		Posten::$recalcBeleg = false;
		$mP = new mPosten();
		$mP->cloneAllToGRLBM($oldGRLBMID, $updatePrices, $Auftrag->A("kundennummer"));
		if(!$quiet)
			echo $this->A->AuftragID;
		Posten::$recalcBeleg = true;
		
		return $newGRLBMID;
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="deleteMe">
	function deleteMe(){
		$ps = mUserdata::getPluginSpecificData("Auftraege");
		if(isset($ps["pluginSpecificCantRemoveBelegOthers"])){
			$Auftrag = new Auftrag($this->A("AuftragID"));
			if($Auftrag->A("UserID") != Session::currentUser()->getID())
				Red::alertD("Sie dürfen nur eigene Belege löschen!");
		}
		if(isset($ps["pluginSpecificCantRemoveBeleg"]))
			Red::alertD("Sie dürfen keine Belege löschen!");
		
		$mP = new anyC();
		$mP->setCollectionOf("Posten");
		$mP->addAssocV3("GRLBMID","=",$this->ID);
		#$mP->lCV3();
		
		/*if($mP->numLoaded() > 0)
			die("alert:AuftraegeMessages.A001");*/
		
		$forceDelete = false;
		if($this->getMyPrefix() == "B")
			$forceDelete = true;
		Posten::$recalcBeleg = false;
		while($t = $mP->getNextEntry())
			$t->deleteMe($forceDelete);
		Posten::$recalcBeleg = true;
		
		if(Session::isPluginLoaded("mStammdaten")){
			try {
			$S = Stammdaten::getActiveStammdaten();
			$Auftrag = new Auftrag($this->A("AuftragID"));
			if($Auftrag->A("AuftragStammdatenID") > 0)
				$S = new Stammdaten($Auftrag->A("AuftragStammdatenID"));
			
			if($S->A("templateReNr") == "BelegnummernEditor")
				BelegnummernEditor::rewind($this, $Auftrag, $S);
			
			if($S->A("templateReNr") == "BelegnummernEditor2")
				BelegnummernEditor2::rewind($this, $Auftrag, $S);
			
			} catch (Exception $e){ }
		}
		
		$Auftrag = new Auftrag($this->A("AuftragID"));
		parent::deleteMe();
		
		if($this->A("isM"))
			$this->updateGebuehren();
		
		$Auftrag->updateStatus("-", true);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getA">
	function getA(){
		if($this->A == null) $this->loadMe();
		return $this->A;
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="updateTBs">
	function updateTBs($o, $u, $zb){
		$this->A->textbausteinOben = $o;
		$this->A->textbausteinUnten = $u;
		$this->A->zahlungsbedingungen = $zb;
		$this->saveMe();
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getProvisionCopy">
	protected function getProvisionCopy($ProvisionID){
		$p = new Posten(-1);
		$p->newFromProvision($ProvisionID,$this->ID);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="getPostenCopy">
	public function getPostenCopy($ArtikelID, $menge = 1, $beschreibung = null, $kundennummer = null, $preis = null){
		if($this->isLocked())
			Red::errorD ("Es können keine Posten mehr hinzugefügt werden, der Beleg wurde gesperrt!");
			
		#$_SESSION["messages"]->addMessage("creating Posten for Auftrag ".$this->ID." of Artikel $ArtikelID");
		$p = new Posten(-1);
		$id = $p->newFromArtikel($ArtikelID, $this->ID, $menge, $beschreibung, $kundennummer, $preis);
		$this->newPostenMessageBestand = $p->messageBestand;
		return $id;
	}
	// </editor-fold>

	protected function copyPostenFromMulti($GRLBMIDs){
		if(count($GRLBMIDs) == 0)
			return;
		
		Aspect::joinPoint("before", $this, __METHOD__, array($GRLBMIDs));
		self::$copySortOrderFind = false;
		foreach($GRLBMIDs AS $GRLBMID)
			$this->copyPostenFrom($GRLBMID, [], false);
	}
	
	private static $copySortOrderFind = true;
	public static $copySortOrder = 0;
	public $copyPostenFromPostenIDs = array();
	// <editor-fold defaultstate="collapsed" desc="copyPostenFrom">
	public function copyPostenFrom($fromId, $skipIDs = [], $restValueIDs = []){
		T::load(__DIR__, "Auftraege");
		
		if($this->isLocked())
			Red::errorD("Es können keine Posten mehr hinzugefügt werden, der Beleg wurde gesperrt!");
		
		$this->copyPostenFromPostenIDs = array();
		
		$GRLBM = new GRLBM($fromId);
		$this->copyBelegDataFrom($GRLBM);
		
		$P = new Posten(-1);
		$P->loadMeOrEmpty();
		if(self::$copySortOrderFind AND $P->A("PostenSortOrder") !== null){
			$AC = anyC::get("Posten", "GRLBMID", $this->getID());
			$AC->addOrderV3("PostenSortOrder", "DESC");
			$AC->setLimitV3("1");
			$L = $AC->n();
			if($L)
				self::$copySortOrder = $L->A("PostenSortOrder") + 1;
		}
		
		
		$ps = anyC::get("Posten", "GRLBMID", $fromId);
		if($P->A("PostenSortOrder") !== null)
			$ps->addOrderV3("PostenSortOrder");
		$ps->addOrderV3("PostenID");
		
		Aspect::joinPoint("alter", $this, __METHOD__, array($ps));
		
		$i = 0;
		while(($t = $ps->n())){
			if(is_array($skipIDs) AND in_array($t->getID(), $skipIDs))
				continue;
			
			$A = $t->getA();
			
			if(is_array($restValueIDs) AND in_array($t->getID(), $restValueIDs)){
				$AC = anyC::get("Posten", "PostenByPostenID", $t->getID());
				$AC->addAssocV3("GRLBMID", ">", 0);
				$AC->setFieldsV3(["SUM(preis) AS bisher"]);
				$PC = $AC->n();
				
				$POrig = new Posten($t->getID(), false);
				
				$A->preis = $POrig->A("preis") - $PC->A("bisher");
				if($A->preis <= 0)
					continue;
			}
			
			$A->GRLBMID = $this->getID();
			if(isset($A->PostenSortOrder))
				$A->PostenSortOrder = self::$copySortOrder++;#+= $addToSort;
			
			if($i == 0 AND isset($A->PostenAddLine) AND $this->getMyPrefix() != "A" AND $this->CustomizerPostenAddLabelInsertOrigin){
				$oldGRLBM = new GRLBM($fromId);
				if($oldGRLBM->A("AuftragID") == $this->A("AuftragID"))
					$A->PostenAddLine = Aspect::joinPoint("alterCopyLabel", $this, __METHOD__, array($oldGRLBM), T::_("Aus")." ".T::_(Stammdaten::getLongType($oldGRLBM->getMyPrefix()))." ".$oldGRLBM->A("nummer")." ".T::_("vom")." ".$oldGRLBM->A("datum"));
			}
			
			if($this->getMyPrefix() == "O" AND $t->A("oldArtikelID") != "0"){
				$nP = new Posten(-1, false);
				$this->copyPostenFromPostenIDs[] = $nP->newFromArtikel($t->A("oldArtikelID"), $this->getID(), $A->menge);
			} else {
				$nP = new Posten(-1, false);
				$nP->recalcNetto = false;
				$nP->setA($A);
				
				$A->PostenByPostenID = $t->getID();
				
				if(Session::isPluginLoaded("mSeriennummer") AND Seriennummer::has($t->A("oldArtikelID"))){
					$m = new stdClass();
					$m->type = "warning";
					
					if($this->getMyPrefix() == Lagerbestand::updateOn($t->A("oldArtikelID"))){
						$m->message = "Die Menge wurde durch Kopieren auf Null (vorher ".Util::CLNumberParser($A->menge).") gesetzt!";
						$A->menge = 0;
						$A->PostenUsedSerials = "";
					}
					
					$A->message = json_encode($m, JSON_UNESCAPED_UNICODE);
				}
				
				if(Session::isPluginLoaded("mLagerbestandWare") AND LagerbestandWare::has($t->A("oldArtikelID"))){
					$m = new stdClass();
					$m->type = "warning";
					
					if($this->getMyPrefix() == Lagerbestand::updateOn($t->A("oldArtikelID"))){
						$m->message = "Die Menge wurde durch Kopieren auf Null (vorher ".Util::CLNumberParser($A->menge).") gesetzt!";
						$A->menge = 0;
						$A->PostenUsedCharge = "";
					}
					
					$A->message = json_encode($m, JSON_UNESCAPED_UNICODE);
				}
				
				$temp = Posten::$recalcBeleg;
				Posten::$recalcBeleg = false;
				$this->copyPostenFromPostenIDs[] = $newID = $nP->newMe(true, false, true); //changed 3rd parameter to true on 20161220 because Lagerbestand was not updated on copy
				
				
				if(Session::isPluginLoaded("mPostenKalkulation")){
					$AC = anyC::get("PostenKalkulation", "PostenKalkulationPostenID", $t->getID());
					while($PK = $AC->n()){
						$PK->changeA("PostenKalkulationPostenID", $newID);
						$PK->newMe();
					}
				}
				
				Posten::$recalcBeleg = $temp;
			}
			
			$i++;
		}
		
			
		$this->saveMe();
		
		$G = new GRLBM($this->getID(), false);
		$G->getSumOfPosten(false, true);
		
		return Aspect::joinPoint("after", $this, __METHOD__, $fromId);
	}
	// </editor-fold>

	public function copyBelegDataFrom(GRLBM $GRLBM){
		if($GRLBM->A("AuftragID") != $this->A("AuftragID"))
			return;
		
		if($GRLBM->getMyPrefix() == "B" AND $this->getMyPrefix() != "B")
			if($this->getMyPrefix() == "L")
				$this->changeA("datum", $GRLBM->A("lieferDatum"));
			else
				$this->changeA("lieferDatum", $GRLBM->A("lieferDatum"));

		if($GRLBM->getMyPrefix() == "L" AND $this->getMyPrefix() == "R")
			$this->changeA("lieferDatum", $GRLBM->A("datum"));

		if($GRLBM->getMyPrefix() == "A" AND $this->getMyPrefix() == "B")
			$this->changeA("lieferDatum", $GRLBM->A("lieferDatum"));
		
		if($GRLBM->getMyPrefix() == "A" OR $this->getMyPrefix() == "T")
			$this->changeA("rabatt", $this->hasParsers ? Util::CLNumberParserZ($GRLBM->A("rabatt")) : $GRLBM->A("rabatt"));
		
		for($i = 1;$i < 20; $i++)
			if($GRLBM->A("GRLBMCustomField$i") !== null)
				$this->changeA("GRLBMCustomField$i", $GRLBM->A("GRLBMCustomField$i"));
			
		Aspect::joinPoint("after", $this, __METHOD__, array($GRLBM));
	}
	
	// <editor-fold defaultstate="collapsed" desc="deleteAllPosten">
	public function deleteAllPosten(){
		$ac = new anyC();
		$ac->setCollectionOf("Posten");
		$ac->addAssocV3("GRLBMID", "=", $this->ID);

		while($t = $ac->getNextEntry())
			$t->deleteMe();
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="addPosten">
	public function addPosten($artikelName, $einheit, $anzahl, $preis, $mwst = null, $beschreibung = "", $isBrutto = false, $oldArtikelID = null, $EK1 = 0, $EK2 = 0, $options = array()){
		$preis = $preis * 1;
		$P = new Posten(-1, false);
		$A = $P->newAttributes($mwst === null ? $this : null);
		
		$A->GRLBMID = $this->ID;
		$A->name = $artikelName;
		$A->gebinde = $einheit;
		$A->preis = $preis;
		if($mwst !== null)
			$A->mwst = $mwst;
		$A->menge = $anzahl;
		$A->beschreibung = $beschreibung;
		$A->EK1 = $EK1;
		$A->EK2 = $EK2;
		
		$A->bruttopreis = $preis * ((100 + $mwst) / 100);
		
		if(property_exists($A, "PostenSortOrder")) //Fix unsorted new Posten after sorting
			$A->PostenSortOrder = 999999;
		
		if($oldArtikelID != null) $A->oldArtikelID = $oldArtikelID;

		if($isBrutto == false AND isset($A->isBrutto))
			$A->isBrutto = "0";
		
		if($isBrutto AND isset($A->isBrutto)){
			$A->isBrutto = "1";
			$A->bruttopreis = $preis;
			$A->preis = $preis / ((100 + $mwst) / 100);
			$P->recalcNetto = false;
		}

		if(isset($options["PostenLeistungszeitraum"]))
			$A->PostenLeistungszeitraum = $options["PostenLeistungszeitraum"];

		$P->setA($A);
		return $P->newMe(false);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="addPersonal">
	public function addPersonal($PersonalID, $stunden = 1){
		#$this->getPostenCopy($ArtikelID, $menge, $beschreibung, $kundennummer);
		$P = new Personal($PersonalID);
		
		$Preis = 0;
		if($P->A("LohngruppeID") != "0"){
			$L = new Lohngruppe($P->A("LohngruppeID"));
			$Preis = $L->calcNettoPrice(60);
		}
		
		$mwst = 0;
		$M = Kategorien::getDefault("mwst");
		#$AC = anyC::get("Kategorie", "type", "mwst");
		#$AC->addAssocV3("isDefault", "=", "1");
		#$M = $AC->getNextEntry();
		if($M != null)
			$mwst = Util::parseFloat("de_DE",str_replace("%","",$M));
		
		$this->addPosten($P->A("vorname")." ".$P->A("nachname"), "Stunde(n)", $stunden, $Preis, $mwst, "", 0, 0);
	}
	// </editor-fold>
	
	// <editor-fold defaultstate="collapsed" desc="addArtikel">
	public function addArtikel($ArtikelID, $menge = 1, $beschreibung = null, $kundennummer = null, $preis = null){
		return $this->getPostenCopy($ArtikelID, $menge, $beschreibung, $kundennummer, $preis);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="setTextbaustein">
	public function setTextbaustein($type, $text, $save = true){
		if($type != "textbausteinUnten" AND $type != "textbausteinOben" AND $type != "zahlungsbedingungen") return;
		$tID = $type."ID";

		$this->loadMe();

		$this->A->$tID = 0;
		$this->A->$type = $text;
		
		if($save) $this->saveMe();
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="setLieferdatum">
	public function setLieferdatum($newDatum, $save = true){
		$this->loadMe();

		$this->A->lieferDatum = $newDatum;

		if($save) $this->saveMe();
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="copyPostenByTypeAndNumber">
	protected function copyPostenByTypeAndNumber($fromNumber, $fromType){
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		if(isset($pSpecData["pluginSpecificCantCreate$fromType"]))
			Red::errorD ("Belegart unzulässig");
		
		$version = null;
		if(strpos($fromNumber, "-") !== false AND $fromType == "A" AND $this->A("GRLBMVersion") !== null){
			$ex = explode("-", $fromNumber);
			#$fromNumber = $ex[0];
			if(is_numeric($ex[count($ex) - 1])){
				$version = $ex[count($ex) - 1];
				unset($ex[count($ex) - 1]);
				$fromNumber = implode("-", $ex);
			}
		}
		
		try {
			$ac = anyC::get("GRLBM");
			$ac->addAssocV3("is$fromType","=","1");
			$ac->addAssocV3("nummer","=",$fromNumber);
			if($version)
				$ac->addAssocV3 ("GRLBMVersion", "=", $version);
			
			$id = $ac->getNextEntry();
		} catch(FieldDoesNotExistException $e){
			$ac = anyC::get("GRLBM");
			$ac->addAssocV3("isWhat","=","$fromType");
			$ac->addAssocV3("nummer","=",$fromNumber);
			if($version)
				$ac->addAssocV3 ("GRLBMVersion", "=", $version);
			
			$id = $ac->getNextEntry();
		}

		
		if($id == null)
			Red::errorD ("Dieser Typ mit dieser Nummer existiert nicht!");
		
		if($ac->numLoaded() > 1) 
			Red::errorD ("Diese Nummer wurde mehr als einmal gefunden!");
		
		$this->copyPostenFrom($id->getID());
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="markMeAsUnprinted">
	protected function markMeAsUnprinted(){
		if($this->A == null) $this->loadMe();
		$this->A->isPrinted = 0;
		$this->saveMe();
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="markMeAsPrinted">
	public function markMeAsPrinted($copy = false){
		$this->resetParsers();

		#if($this->A == null) $this->loadMe();
		#$this->A->isPrinted = 1;
		#$this->saveMe();
		
		$this->changeA("isPrinted".($copy ? "Copy" : ""), "1");
		$this->changeA("isPrinted".($copy ? "Copy" : "")."Time", time());
		$this->saveMe(true, false, false);

		if(Session::isPluginLoaded("mNextcloudUser")){
			$NU = NextcloudUser::getUser();
			if($NU AND $NU->A("NextcloudUserAutoupload"))
				$NU->getFileForUpload("Auftrag", $this->A("AuftragID"), $this->getID(), true);
		}
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="setPayed">
	public function setPayed($p, $skonto = "0,00", $datum = "0", $isTeilzahlung = "false", $TeilzahlungBetrag = "", $save = true, $checkPermission = true){
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		
		if($checkPermission AND !isset($pSpecData["pluginSpecificCanSetPayed"])) 
			Red::errorD ("Sie haben keine Berechtigung, eine Rechnung als bezahlt zu markieren!");

		if($p == "true")
			mUserdata::setUserdataS("lastPayedStatusChange", time());
		
		$this->loadMe();
		if($isTeilzahlung == "false"){
			$this->A->isPayed = $p == "true" ? 1 : 0;
			$this->A->GRLBMpayedDate = $datum;#Util::CLDateParser($datum,"store");
			$this->A->payedWithSkonto = Util::parseFloat("de_DE", $skonto);
		} else {
			$betrag = !is_numeric($TeilzahlungBetrag) ? Util::CLNumberParser($TeilzahlungBetrag, "store") : $TeilzahlungBetrag;
			$this->A->GRLBMTeilzahlungen .= $betrag.";".Util::CLDateParser($datum,"store")."\n";
			$this->A->GRLBMTeilzahlungenSumme += $betrag;
		}
		
		if($save) 
			$this->saveMe();
		
		if(Session::isPluginLoaded("mSync") AND strpos($this->A("GRLBMReferenz"), "Sync:") === 0){
			$SID = str_replace("Sync:", "", $this->A("GRLBMReferenz"));
			$S = new SyncGet($SID);
			$S->callback($this->A("GRLBMReferenznummer"));
		}
		
		// <editor-fold defaultstate="collapsed" desc="Aspect:jP">
		$args = func_get_args();
		Aspect::joinPoint("after", $this, __METHOD__, $args);
		// </editor-fold>
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="deleteTeilzahlung">
	public function deleteTeilzahlung($zeile){
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		
		if(!isset($pSpecData["pluginSpecificCanSetPayed"])) Red::errorD("Sie haben keine Berechtigung, eine Rechnung als bezahlt zu markieren!");
		
		$t = trim($this->A("GRLBMTeilzahlungen"));
		$t2 = "";
		$s = explode("\n",$t);
		for($i = 0; $i < count($s); $i++){
			if($zeile != $i){
				$t2 .= $s[$i]."\n";
			} else {
				$b = explode(";",$s[$i]);
				$this->A->GRLBMTeilzahlungenSumme -= $b[0] * 1;
			}
		}
		$this->A->GRLBMTeilzahlungen = $t2;
		$this->saveMe(true, true);
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="saveMe">
	public function saveMe($checkuserdata = true, $output = false, $checkPayed = true){
		$oldMe = new GRLBM($this->ID);
		
		if($this->A("isPrinted") != $oldMe->A("isPrinted") 
			OR $this->A("isEMailed") != $oldMe->A("isEMailed") 
			OR $this->A("isEMailedTime") != $oldMe->A("isEMailedTime"))
			$print = true;
		else
			$print = false;
		
		$type = null;
		if($this->A("isR") == "1")
			$type = "isR";
		
		if($this->A("isG") == "1")
			$type = "isG";
		
		if($type != null){
			$AC = anyC::get("GRLBM", $type, "1");
			$AC->addAssocV3("GRLBMID", "!=", $this->getID());
			$AC->addAssocV3("nummer", "=", $this->A("nummer"));
			
			$E = $AC->getNextEntry();
			if($E != null)
				Red::alertD ("Die Belegnummer ".$this->A("nummer")." wurde bereits vergeben!");
		}
		
		if(Session::isPluginLoaded("Provisionen") AND $this->A("isPayed") != $oldMe->A("isPayed") AND $this->getMyPrefix() == "R")
			Provisionen::zuweisen($this, $this->A("isPayed") == "1");
		
		if($checkPayed AND !self::$ignoreLock AND $this->A("isPayed") == "1" AND ($this->A("isR") == "1"/* OR $this->A("isB") == "1"*/) AND $oldMe->A("isPayed") == "1" AND !$print)
			Red::alertD ("Dieser Beleg kann nicht mehr bearbeitet werden!");
	
		$Auftrag = new Auftrag($this->A("AuftragID"));
		$Adresse = new Adresse($Auftrag->A("AdresseID"));
		
		if($this->A("textbausteinObenID") != null AND $this->A("textbausteinObenID") != "0")
			$this->changeA("textbausteinOben", Textbaustein::getTextOf($this->A("textbausteinObenID"), $Adresse->A("AdresseSpracheID")));
		
		if($this->A("textbausteinUntenID") != null AND $this->A("textbausteinUntenID") != "0")
			$this->changeA("textbausteinUnten", Textbaustein::getTextOf($this->A("textbausteinUntenID"), $Adresse->A("AdresseSpracheID")));
		
		if($this->A("zahlungsbedingungenID") != null AND $this->A("zahlungsbedingungenID") != "0")
			$this->changeA("zahlungsbedingungen", Textbaustein::getTextOf($this->A("zahlungsbedingungenID"), $Adresse->A("AdresseSpracheID")));
		
		$this->changeA("GRLBMSkonto", json_encode(array("tage" => 0, "prozent" => 0)));
		if(is_numeric($this->A("GRLBMpayedVia")) AND Session::isPluginLoaded("mZahlungsart")){
			$Zahlungsart = new Zahlungsart($this->A("GRLBMpayedVia"));
			$this->changeA("GRLBMSkonto", json_encode(array("tage" => $Zahlungsart->A("ZahlungsartSkontoTage"), "prozent" => $Zahlungsart->A("ZahlungsartSkontoProzent"))));
		}
				

		Aspect::joinPoint("after", $this, __METHOD__, array($this->getA()));
		
		parent::saveMe($checkuserdata, false);
		
		$vk = $this->A("versandkosten");
		if($this->hasParsers)
			$vk = Util::CLNumberParserZ ($this->A("versandkosten"), "store");
		
		if($this->A("isPayed") != "1" AND $oldMe->A("versandkosten") != $this->A("versandkosten")){
			$G = new GRLBM($this->getID());
			$G->getSumOfPosten(false, true);
		}
		
		$date = $this->A("datum");
		if($this->hasParsers)
			$date = Util::CLDateParser ($this->A("datum"), "store");
		
		if($this->getMyPrefix() != "M" AND !$this->isLocked())
			$Auftrag->updateDatum($date);
		
		if($this->A("isM"))
			$this->updateGebuehren();
		
		if($output)
			Red::messageSaved();
	}
	// </editor-fold>

	private function updateGebuehren(){
		$AC = anyC::get("GRLBM", "AuftragID", $this->A("AuftragID"));
		$AC->addAssocV3("isM", "=", "1");
		$AC->setFieldsV3(array("SUM(gebuehren) AS gesamt"));
		$T = $AC->n();
		$value = 0;
		if($T)
			$value = $T->A("gesamt");

		$refG = new GRLBM($this->A("AuftragID"), false);
		$refG->changeA("gebuehren", $value);
		$refG->saveMe(true, false, false);
	}
	
	public function isLocked(){
		// <editor-fold defaultstate="collapsed" desc="Aspect:jP">
		try {
			$MArgs = func_get_args();
			return Aspect::joinPoint("around", $this, __METHOD__, $MArgs);
		} catch (AOPNoAdviceException $e) {}
		Aspect::joinPoint("before", $this, __METHOD__, $MArgs);
		// </editor-fold>
		$pSpecData = mUserdata::getPluginSpecificData("Auftraege");
		if(isset($pSpecData["pluginSpecificRLocksAuftrag"]) AND $this->getMyPrefix() != "R"){
			$AC = anyC::get("GRLBM", "AuftragID", $this->A("AuftragID"));
			$AC->addAssocV3("isR", "=", "1");
			$AC->setLimitV3(1);
			$R = $AC->n();
			if($R)
				return true;
		}
		
		if($this->A("isPayed") == "1")
			return true;
		
		$isProcessed = ($this->A("isPrinted") == "1" OR $this->A("isPrintedCopy") == "1" OR $this->A("isEMailed") == "1");
		
		if(in_array($this->getMyPrefix(), self::$lockable) AND $isProcessed)
			return true;
		
		return false;
		
		#return $this->A("isPayed") == "1";
	}
	
	public function unlock(){
		Aspect::joinPoint("before", $this, __METHOD__, array());

		$this->changeA("isPrinted", "0");
		$this->changeA("isPrintedCopy", "0");
		$this->changeA("isEMailed", "0");
		
		$this->setPayed("false");
	}
	
	// <editor-fold defaultstate="collapsed" desc="getMyPrefix">
	public function getMyPrefix($forceB = false){
		if($this->A == null)
			$this->loadMe();

		if($this->A->isR == "1") return "R";
		if($this->A->isL == "1") return "L";
		if($this->A->isB == "1") return "B";
		if($this->A->printAB == "1" AND (Auftrag::getBelegArten("B") OR $forceB)) return "B";
		if($this->A->isA == "1") return "A";
		if($this->A->isG == "1") return "G";
		if($this->A->isM == "1") return "M";
		if($this->A->isWhat != "") return $this->A->isWhat;
		
		return "-1";
	}
	// </editor-fold>

	public static function getPaymentVia($t = null, $limitTo = null, $onlyDefaults = false, $addKonto = false){
		$ts = array("cash" => "Bar", "debit" => T::_("Lastschrift"), "transfer" => T::_("Überweisung"), "paypal" => T::_("PayPal"), "cashing" => T::_("Inkasso"), "creditcard" => T::_("Kreditkarte"));
		
		if(Session::isPluginLoaded("mZahlungsart") AND !$onlyDefaults){
			$AC = anyC::get("Zahlungsart");
			$AC->addAssocV3("ZahlungsartStammdatenID", "=", Stammdaten::getActiveStammdaten()->getID());
			#$AC->addAssocV3("ZahlungsartUseFor", "=", "");
			
			while($Z = $AC->getNextEntry()){
				if($Z->A("ZahlungsartUseFor") == "")
					$ts[$Z->getID()] = $Z->A("ZahlungsartName").(($addKonto AND $Z->A("ZahlungsartKonto") != 0) ? " (".$Z->A("ZahlungsartKonto").")" : "");
				else
					$ts[$Z->A("ZahlungsartUseFor")] = T::_($Z->A("ZahlungsartName")).(($addKonto AND $Z->A("ZahlungsartKonto") != 0) ? " (".$Z->A("ZahlungsartKonto").")" : "");
			}
		}
		
		if($limitTo !== null){
			if(!is_array($limitTo))
				$limitTo = array($limitTo);
			
			$ts2 = array();
			
			foreach($limitTo AS $v)
				$ts2[$v] = $ts[$v];
			
			$ts = $ts2;
		}
		
		if($t != null)
			return $ts[$t];
		
		return $ts;
	}
	
	public function getEtiketten(){
		$Auftrag = new Auftrag($this->A("AuftragID"));
		$Adresse = new Adresse($Auftrag->A("AdresseID"));

		$Stammdaten = Stammdaten::getActiveStammdaten();

		return array(array(
			$Stammdaten->A("firmaLang").", ".$Stammdaten->A("strasse")." ".$Stammdaten->A("nr").", ".$Stammdaten->A("plz")." ".$Stammdaten->A("ort").(ISO3166::getCountryToCode($Stammdaten->A("land")) != $Adresse->A("land") ? ", ".ISO3166::getCountryToCode($Stammdaten->A("land")) : ""), 
			$Adresse->getFormattedAddress(),
			trim($Stammdaten->A("firmaLang")."\n".$Stammdaten->A("strasse")." ".$Stammdaten->A("nr")."\n".$Stammdaten->A("plz")." ".$Stammdaten->A("ort").(ISO3166::getCountryToCode($Stammdaten->A("land")) != $Adresse->A("land") ? "\n".ISO3166::getCountryToCode($Stammdaten->A("land")) : ""))));
	}
	
	public function updateTodo(){
		if(!Session::isPluginLoaded("mTodo") OR !Session::isPluginLoaded("mKalender"))
			return;
	}
	
	public function getCalendarTitle(){
		$Auftrag = new Auftrag($this->A("AuftragID"));
		$Adresse = new Adresse($Auftrag->A("AdresseID"));
		
		return Stammdaten::getLongType($this->getMyPrefix())." ".$Adresse->getShortAddress()." (".$this->A("nummer").")";
	}
	
	public function getBankingData(){
		$Auftrag = new Auftrag($this->A("AuftragID"));
		$Adresse = new Adresse($Auftrag->A("AdresseID"));
		$Kappendix = Kappendix::getKappendixToKundennummer($Auftrag->A("kundennummer"));
		
		$rep = array("ä", "ö", "ü", "Ä", "Ö", "Ü");
		$repWith = array("ae", "oe", "ue", "Ae", "Oe", "Ue");
		
		$sepa = new stdClass();
		if($this->A("GRLBMSEPAData") != "" AND $this->A("GRLBMSEPAData") != "[]")
			$sepa = json_decode($this->A("GRLBMSEPAData"));

		return array(
			"name" => str_replace($rep, $repWith, $Kappendix->A("KappendixSameKontoinhaber") ? trim($Adresse->getShortAddress()) : $Kappendix->A("KappendixKontoinhaber")),
			"BLZ" => $Kappendix->A("KappendixBLZ"), 
			"konto" => $Kappendix->A("KappendixKontonummer"),
			"BIC" => isset($sepa->BIC) ? $sepa->BIC : $Kappendix->A("KappendixSWIFTBIC"),
			"IBAN" => isset($sepa->IBAN) ? $sepa->IBAN : $Kappendix->A("KappendixIBAN"),
			"mandatDatum" => isset($sepa->MandateDate) ? $sepa->MandateDate : $Kappendix->A("KappendixIBANMandatDatum"),
			"referenz" => isset($sepa->MandateID) ? $sepa->MandateID : $this->A("prefix").$this->A("nummer"),
			"betrag" => Util::kRound($this->A("bruttobetrag")),
			"zweck" => $this->A("prefix").$this->A("nummer")." vom ".$this->A("datum"),
			"kontoID" => 0);
	}
	
	public function completed(){
		#$this->changeA("EingangsbelegBezahltAm", time());
		#$this->saveMe();
	}
}
?>