diff --git a/phpwf/plugins/class.yui.php b/phpwf/plugins/class.yui.php index 0c8e38b3..660f7729 100644 --- a/phpwf/plugins/class.yui.php +++ b/phpwf/plugins/class.yui.php @@ -1870,13 +1870,21 @@ class YUI { if($waehrung=="") { // schaue ob es gebuchte positionen gibt dann diese waehrung - $waehrung = $this->app->DB->Select("SELECT waehrung FROM $table WHERE $module='$id' LIMIT 1"); + + $waehrung = ""; + if (!is_null($table)) { + if ($this->app->DB->Select("SHOW COLUMNS FROM `$table` LIKE 'waehrung'")) { + $waehrung = $this->app->DB->Select("SELECT waehrung FROM $table WHERE $module='$id' LIMIT 1"); + } + } if($waehrung==""){ $waehrung = $this->app->erp->GetStandardWaehrung($projekt); } - if($waehrung!="") $this->app->DB->Update("UPDATE $module SET waehrung='$waehrung' WHERE id='$id' AND waehrung='' LIMIT 1"); + if ($this->app->DB->Select("SHOW COLUMNS FROM `$module` LIKE 'waehrung'")) { + if($waehrung!="") $this->app->DB->Update("UPDATE $module SET waehrung='$waehrung' WHERE id='$id' AND waehrung='' LIMIT 1"); + } } $umsatzsteuer = $articleArr['umsatzsteuer'];//$this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id='$artikel_id' LIMIT 1"); @@ -14504,7 +14512,8 @@ source: "index.php?module=ajax&action=filter&filtername=' . $filter . $extendurl if ($module == "lieferschein" || $module == "retoure") { $table->headings[6] = 'ausgeliefert'; - $zwischensumme = $this->app->DB->Select("SELECT sum(menge*preis) FROM $module"."_position WHERE $module = '$id'"); +// $zwischensumme = $this->app->DB->Select("SELECT sum(menge*preis) FROM $module"."_position WHERE $module = '$id'"); +// lieferschein has no preis } else if($module == "anfrage" || $module == "preisanfrage" ) { $table->headings[6] = 'Aktion'; diff --git a/www/lib/class.erpapi.php b/www/lib/class.erpapi.php index 4f09ec24..5f6bdc60 100644 --- a/www/lib/class.erpapi.php +++ b/www/lib/class.erpapi.php @@ -33069,7 +33069,9 @@ function MailSendFinal($from,$from_name,$to,$to_name,$betreff,$text,$files="",$p $this->app->DB->Update("UPDATE firmendaten_werte SET wert = '".$this->app->DB->real_escape_string($value)."' WHERE id = '".$check['id']."'"); } } - $this->app->DB->Update("UPDATE firmendaten SET " . $field . "='$value' WHERE id='" . $firmendatenid . "'"); + else { + $this->app->DB->Update("UPDATE firmendaten SET " . $field . "='$value' WHERE id='" . $firmendatenid . "'"); + } $db = $this->app->Conf->WFdbname; if(!empty($this->firmendaten[$db])) { $this->firmendaten[$db][$field] = $value; @@ -33087,11 +33089,14 @@ function MailSendFinal($from,$from_name,$to,$to_name,$betreff,$text,$files="",$p if(strpos($field,'next') !== false) { $firmendatenid = (int)$this->app->DB->Select('SELECT MAX(id) FROM firmendaten LIMIT 1'); - $firmendaten_value = $this->app->DB->Select( - sprintf( - 'SELECT `%s` FROM firmendaten WHERE id = %d LIMIT 1', - $field, $firmendatenid) - ); + + if ($this->app->DB->Select("SHOW COLUMNS FROM firmendaten LIKE '$field'")) { + $firmendaten_value = $this->app->DB->Select( + sprintf( + 'SELECT `%s` FROM firmendaten WHERE id = %d LIMIT 1', + $field, $firmendatenid) + ); + } if(!$this->app->DB->error()) { return $firmendaten_value; } @@ -44997,6 +45002,10 @@ function Firmendaten($field,$projekt="") } } + if(is_null($rabatt)) { + $rabatt = 0; + } + if(!$guenstigste_vk) { $vkarr = $this->app->DB->SelectArr("SELECT v.*,if((v.adresse > 0 OR v.gruppe > 0),v.preis,(v.preis*(100-$rabatt))/100.0) as rabattpreis FROM verkaufspreise v WHERE diff --git a/www/lib/dokumente/class.briefpapier.php b/www/lib/dokumente/class.briefpapier.php index 2f9d85be..2c8f955f 100644 --- a/www/lib/dokumente/class.briefpapier.php +++ b/www/lib/dokumente/class.briefpapier.php @@ -1,4346 +1,4369 @@ -setStyleData($styleData); - //$orientation='P';$unit='mm';$format='A4'; - //parent::PDF_EPS($orientation,$unit,$format); - $this->projekt = $projekt; - - $this->app=$app; - $this->absender = ''; - $this->firmendatenid = $this->app->DB->Select("SELECT MAX(id) FROM firmendaten LIMIT 1"); - $this->parameter = ''; - - $viernachkommastellen_belege = $this->getStyleElement('viernachkommastellen_belege'); - if($viernachkommastellen_belege=='1') - { - $this->anzahlkomma=4; - } else { - $this->anzahlkomma=2; - } - - $this->ust_spalteausblende=false; - - if($this->getStyleElement('kleinunternehmer')=='1') - { - $this->ust_befreit=1; - $this->ust_spalteausblende=true; - } - - - $hintergrund = $this->getStyleElement('hintergrund'); - - if(!empty(erpAPI::Ioncube_Property('isdevelopmentversion'))) { - $this->setDevelopmentVersionBackground(); - } - elseif($this->app->erp->BriefpapierHintergrunddisable) - { - } - else if($hintergrund=='logo') - { - $logo = $this->app->erp->getSettingsFile('logo'); - $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_logo.jpg'; - if ($handle = fopen($filename, 'w')) { - fwrite($handle, $logo); - fclose($handle); - } - $this->logofile = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_logo.jpg'; - $this->briefpapier=''; - } - else if($hintergrund=='briefpapier') - { - $briefpapier = $this->app->erp->getSettingsFile('briefpapier'); - $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier.pdf'; - if ($handle = fopen($filename, 'w')) { - fwrite($handle, $briefpapier); - fclose($handle); - } - - $this->briefpapier=$this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier.pdf'; - $this->logofile = ''; - - $briefpapier2vorhanden = $this->getStyleElement('briefpapier2vorhanden'); - $this->briefpapier2vorhanden = $briefpapier2vorhanden; - if($briefpapier2vorhanden > 0) - { - $briefpapier2 = $this->app->erp->getSettingsFile('briefpapier2'); - $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier2.pdf'; - if ($handle = fopen($filename, 'w')) { - fwrite($handle, $briefpapier2); - fclose($handle); - } - - $this->briefpapier2=$this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier2.pdf'; - } - } - else { - $this->logofile = ''; - $this->briefpapier=''; - } - - if(isset($this->app->Conf->WFtestmode) && $this->app->Conf->WFtestmode==true) - { - $this->briefpapier='./lib/dokumente/briefpapier_testmodus.pdf'; - $this->briefpapier2='./lib/dokumente/briefpapier_testmodus.pdf'; - } - - $this->knickfalz = $this->getStyleElement('knickfalz'); - $this->abseite2y = $this->getStyleElement('abseite2y'); - - $footersichtbar = $this->getStyleElement('footersichtbar'); - if($footersichtbar==1) { - $this->nichtsichtbar_footer = false; - } else { - $this->nichtsichtbar_footer = true; - } - - $seite_von_sichtbar = $this->getStyleElement('seite_von_sichtbar'); - if($seite_von_sichtbar==1) { - $this->seite_von_sichtbar = false; - } else { - $this->seite_von_sichtbar = true; - } - - $this->seite_von_ausrichtung = $this->getStyleElement('seite_von_ausrichtung'); - - - $this->abstand_adresszeileoben = $this->getStyleElement('abstand_adresszeileoben'); - $this->abstand_boxrechtsoben = $this->getStyleElement('abstand_boxrechtsoben'); - $this->abstand_boxrechtsoben_lr = $this->getStyleElement('abstand_boxrechtsoben_lr'); - $this->abstand_betreffzeileoben = $this->getStyleElement('abstand_betreffzeileoben'); - $this->abstand_artikeltabelleoben = $this->getStyleElement('abstand_artikeltabelleoben'); - - $this->boxausrichtung = $this->getStyleElement('boxausrichtung'); - - $sichtbar = $this->getStyleElement('sichtbar'); - if($sichtbar==1) { - $this->nichtsichtbar_zeileabsender = false; - } else { - $this->nichtsichtbar_zeileabsender =true; - } - - - $this->barcode_sichtbar = $this->getStyleElement('barcode'); - $this->barcode_x = $this->getStyleElement('barcode_x'); - $this->barcode_y = $this->getStyleElement('barcode_y'); - $this->barcode_x_header = $this->getStyleElement('barcode_x_header'); - $this->barcode_y_header = $this->getStyleElement('barcode_y_header'); - - $projekt = $this->projekt; - - - $this->waehrung=$this->getStyleElement('waehrung'); - - - - // kann man herausfinden was fuer ein projekt angegeben ist??? - $speziallieferschein = $this->app->DB->Select("SELECT speziallieferschein FROM projekt WHERE id='$projekt' LIMIT 1"); - $speziallieferscheinbeschriftung = $this->app->DB->Select("SELECT speziallieferscheinbeschriftung FROM projekt WHERE id='$projekt' LIMIT 1"); - $eigenesteuer = $this->app->DB->Select("SELECT eigenesteuer FROM projekt WHERE id='$projekt' LIMIT 1"); - if($eigenesteuer=='1'){ - $this->waehrung = $this->app->DB->Select("SELECT waehrung FROM projekt WHERE id='$projekt' LIMIT 1"); - } - if($speziallieferschein>0) - { - if(!$this->app->erp->BriefpapierHintergrunddisable) - { - $seite1 = $this->app->DB->Select("SELECT ds.datei FROM datei_stichwoerter ds INNER JOIN datei d ON d.id=ds.datei AND IFNULL(d.geloescht,0)=0 WHERE ds.subjekt LIKE 'Briefpapier1' AND ds.objekt LIKE 'Projekt' AND ds.parameter='$projekt' LIMIT 1"); - $seite2 = $this->app->DB->Select("SELECT ds.datei FROM datei_stichwoerter ds INNER JOIN datei d ON d.id=ds.datei AND IFNULL(d.geloescht,0)=0 WHERE ds.subjekt LIKE 'Briefpapier2' AND ds.objekt LIKE 'Projekt' AND ds.parameter='$projekt' LIMIT 1"); - } - - if(!empty($seite1) && is_file($this->app->erp->GetDateiPfad($seite1))){ - $this->briefpapier = $this->app->erp->GetDateiPfad($seite1); - } - if(!empty($seite2) && is_file($this->app->erp->GetDateiPfad($seite2))){ - $this->briefpapier2 = $this->app->erp->GetDateiPfad($seite2); - } - - if($seite2>0 && is_file($this->app->erp->GetDateiPfad($seite2))){ - $this->briefpapier2vorhanden = 1; - } - - $this->logofile = ''; - - if($speziallieferscheinbeschriftung!=1){ - $this->nichtsichtbar_zeileabsender = true; - $this->nichtsichtbar_footer = true; - $this->nichtsichtbar_rechtsoben = true; - } - } - - $this->nichtsichtbar_rechtsoben = true; - $this->nichtsichtbar_summe = false; - $this->nichtsichtbar_box=false; - $this->nichtsichtbar_empfaenger=false; - } - - /** - * set Development-watermark as pdf-background - * - * @return void - */ - protected function setDevelopmentVersionBackground(): void - { - $this->briefpapier = $this->app->erp->GetTMP().'development_version.pdf'; - $this->briefpapier2 = ''; - $this->logofile = ''; - if(is_file($this->briefpapier)) { - return; - } - $waterMarkPdf = new SuperFPDF('P', 'mm', 'A4'); - $waterMarkPdf->filename = $this->briefpapier; - $waterMarkPdf->AddPage(); - $waterMarkPdf->SetTextColor(200); - $waterMarkPdf->SetFont( - ($this->app->erp->Firmendaten('schriftart') ? $this->app->erp->Firmendaten('schriftart') : 'Arial'), - 'B', - 45 - ); - $waterMarkPdf->Rotate(45, 45, 180); - $waterMarkPdf->Text(45, 180, 'DEVELOPMENT VERSION'); - $waterMarkPdf->Rotate(0); - $waterMarkPdf->SetTextColor(0); - file_put_contents($waterMarkPdf->filename, $waterMarkPdf->displayAnhaenge('S')); - } - - /** - * @param string $language - * - * @return string - */ - public function getLanguageCodeFrom($language) { - if(empty($language)) { - return ''; - } - $languages = $this->app->DB->SelectArr("SELECT * FROM sprachen WHERE aktiv = 1 AND iso <> ''"); - if(empty($languages)) { - return ''; - } - foreach($languages as $languagesRow) { - if(in_array( - $language, - [ - $languagesRow['iso'], - $languagesRow['alias'], - $languagesRow['bezeichnung_de'], - $languagesRow['bezeichnung_en' - ] - ] - )) { - return $languagesRow['iso']; - } - } - - return ''; - } - - public function GetChargeMHDSNString($type,$doctype,$doctypeid,$posid, $returnSimpleString = false) - { - $lieferschein_posid = 0; - $auftrag_position_id = 0; - $lieferschein = 0; - if($doctype === 'rechnung'){ - $lieferschein = $this->app->DB->Select("SELECT lieferschein FROM rechnung WHERE id = '$doctypeid' LIMIT 1"); - } - if($doctype === 'rechnung' && !$lieferschein){ - $lieferschein = $this->app->DB->Select("SELECT id FROM lieferschein WHERE rechnungid = '$doctypeid' LIMIT 1"); - } - if($doctype === 'rechnung' && !$lieferschein) - { - $auftrag = $this->app->DB->Select("SELECT auftragid FROM rechnung WHERE id = '$doctypeid' LIMIT 1"); - if($auftrag){ - $lieferschein = $this->app->DB->Select("SELECT id FROM lieferschein WHERE auftragid = '$auftrag' LIMIT 1"); - } - } - if($doctype === 'lieferschein'){ - $lieferschein_posid = $posid; - } - if($doctype === 'rechnung'){ - $auftrag_position_id = $this->app->DB->Select("SELECT auftrag_position_id FROM rechnung_position WHERE id='$posid'"); - } - if($doctype === 'gutschrift'){ - $auftrag_position_id = $this->app->DB->Select("SELECT gutschrift_position_id FROM rechnung_position WHERE id='$posid'"); - } - if($doctype === 'rechnung') - { - if(!empty($auftrag_position_id) && $auftrag_position_id > 0){ - $lieferschein_posid = $this->app->DB->Select("SELECT id FROM lieferschein_position WHERE auftrag_position_id='$auftrag_position_id' AND auftrag_position_id <> 0 ORDER BY lieferschein = '$lieferschein' DESC LIMIT 1"); - } - if(!$lieferschein_posid) - { - $lieferschein_posarr = $this->app->DB->SelectArr("SELECT lieferschein_position_id FROM `sammelrechnung_position` WHERE rechnung_position_id = '$posid' AND lieferschein_position_id <> 0 AND menge <> 0"); - if(!empty($lieferschein_posarr)) - { - $lieferschein_posid = null; - foreach($lieferschein_posarr as $v) - { - $lieferschein_posid[] = $v['lieferschein_position_id']; - } - if(!empty($lieferschein_posid) && count($lieferschein_posid) === 1) - { - $lieferschein_posid = reset($lieferschein_posid); - if($lieferschein_posid){ - $lieferschein = $this->app->DB->Select("SELECT lieferschein FROM lieferschein_position WHERE id = '$lieferschein_posid' LIMIT 1"); - } - } - } - } - }else{ - if(!empty($auftrag_position_id) && $auftrag_position_id > 0){ - $lieferschein_posid = $this->app->DB->Select("SELECT id FROM lieferschein_position WHERE auftrag_position_id='$auftrag_position_id' AND auftrag_position_id <> 0 LIMIT 1"); - } - } - if($type === 'sn' && ($doctype === 'lieferschein' || $doctype === 'rechnung' || $doctype === 'gutschrift')) - { - if(!empty($tmp)) - { - $ctmp = count($tmp); - for($i=0;$i<$ctmp;$i++) - { - $tmp_string[]=$tmp[$i]['seriennummer']; - } - } - } - - $belegPosCharge = $this->getStyleElement('beleg_pos_charge'); - $belegPosMhd = $this->getStyleElement('beleg_pos_mhd'); - if($returnSimpleString) { - $belegPosCharge = 1; - $belegPosMhd = 1; - } - if($belegPosCharge=='1' - && $belegPosMhd =='1') { - if($type === 'mhd') - { - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' - GROUP by wert,wert2"); - if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) - { - if(is_array($lieferschein_posid)) - { - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND pos in (".implode(', ',$lieferschein_posid ).") - GROUP by wert,wert2"); - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' - GROUP by wert,wert2"); - } - } - - }elseif($type === 'charge') - { - if($returnSimpleString) { - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - WHERE bc1.type='$type' AND bc1.doctype='$doctype' AND bc1.doctypeid='$doctypeid' AND bc1.pos='$posid' - GROUP by bc1.wert"); - } - else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - LEFT JOIN beleg_chargesnmhd bc2 - ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz - AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert - WHERE bc1.type='$type' AND bc1.doctype='$doctype' AND bc1.doctypeid='$doctypeid' AND bc1.pos='$posid' AND isnull(bc2.id) - GROUP by bc1.wert"); - } - if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) - { - if($returnSimpleString) { - if(is_array($lieferschein_posid)){ - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND - bc1.pos in ('" . implode(', ', $lieferschein_posid) . "') - GROUP by bc1.wert"); - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.doctypeid='$lieferschein' - AND bc1.pos='$lieferschein_posid' - GROUP by bc1.wert"); - } - } - else{ - if(is_array($lieferschein_posid)){ - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - LEFT JOIN beleg_chargesnmhd bc2 - ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz - AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert - WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.pos in ('" . implode(', ', $lieferschein_posid) . "') AND isnull(bc2.id) - GROUP by bc1.wert"); - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert - FROM beleg_chargesnmhd bc1 - LEFT JOIN beleg_chargesnmhd bc2 - ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz - AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert - WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.doctypeid='$lieferschein' AND bc1.pos='$lieferschein_posid' AND isnull(bc2.id) - GROUP by bc1.wert"); - } - } - } - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' - GROUP by wert"); - if(empty($tmp) && $lieferschein && $lieferschein_posid) - { - if(is_array($lieferschein_posid)) - { - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND pos in ('".implode(', ',$lieferschein_posid )."') - GROUP by wert"); - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' - GROUP by wert"); - } - } - } - if(!empty($tmp)){ - $ctmp = count($tmp); - for ($i = 0; $i < $ctmp; $i++) { - if($type === 'mhd' && $tmp[$i]['wert'] != ""){ - $tmp[$i]['wert'] = ($i > 0 ? $this->app->erp->Beschriftung('dokument_mhd') . ': ' : '') . date('d.m.Y', strtotime($tmp[$i]['wert'])); - if($tmp[$i]['wert2'] != '' && $tmp[$i]['type2'] === 'charge') { - $tmp[$i]['wert'] .= ' ' . $this->app->erp->Beschriftung('dokument_charge') . ': ' . $tmp[$i]['wert2']; - } - }elseif($type === 'charge'){ - if($i > 0) { - $tmp[$i]['wert'] = $this->app->erp->Beschriftung('dokument_charge') . ': ' . $tmp[$i]['wert']; - } - }elseif($type === 'sn'){ - if($i > 0) { - $tmp[$i]['wert'] = $this->app->erp->Beschriftung('dokument_seriennummer') . ': ' . $tmp[$i]['wert']; - } - } - if($tmp[$i]['menge'] > 1) { - $tmp[$i]['menge'] = ' (' . (float)$tmp[$i]['menge'] . ')'; - }else { - $tmp[$i]['menge'] = ''; - } - $tmp_string[] = $tmp[$i]['wert'] . $tmp[$i]['menge']; - } - } - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' - GROUP by wert"); - if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) - { - if(is_array($lieferschein_posid)) - { - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND pos in ('".implode(', ',$lieferschein_posid )."') - GROUP by wert"); - }else{ - $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 - FROM beleg_chargesnmhd - WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' - GROUP by wert"); - } - } - - if(!empty($tmp)){ - $ctmp = count($tmp); - for ($i = 0; $i < $ctmp; $i++) { - if($type === 'mhd' && $tmp[$i]['wert'] != ''){ - $tmp[$i]['wert'] = - ($i > 0 && !$returnSimpleString ? $this->app->erp->Beschriftung('dokument_mhd') . ': ' : '') . - date('d.m.Y', strtotime($tmp[$i]['wert'])); - } - elseif($type === 'charge'){ - if($i > 0) { - $tmp[$i]['wert'] = (!$returnSimpleString?$this->app->erp->Beschriftung('dokument_charge') . ': ':'') . $tmp[$i]['wert']; - } - } - elseif($type === 'sn'){ - if($i > 0) { - $tmp[$i]['wert'] = (!$returnSimpleString?$this->app->erp->Beschriftung('dokument_seriennummer') . ': ':'') . $tmp[$i]['wert']; - } - } - if($tmp[$i]['menge'] > 1) { - $tmp[$i]['menge'] = ' (' . (float)$tmp[$i]['menge'] . ')'; - } - else { - $tmp[$i]['menge'] = ''; - } - $tmp_string[] = $tmp[$i]['wert'] . $tmp[$i]['menge']; - } - } - } - - if(!empty($tmp_string)){ - if($returnSimpleString) { - return implode(', ', $tmp_string); - } - return implode("\r\n",$tmp_string); - } - return ''; - } - - function CheckPosition($value,$doctype,$doctypeid,$posid) - { - // ean - if($this->getStyleElement('beleg_pos_ean')=='1') - { - $ean = $this->app->DB->Select("SELECT ean FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); - if($ean!='') { - $tmpvalue['ean'] = $this->app->erp->Beschriftung('dokument_ean').': '.$ean; - } - } - - // zolltarif // check ust id - $ust_befreit = $this->app->DB->Select("SELECT ust_befreit FROM $doctype WHERE id='$doctypeid' LIMIT 1"); - if(($ust_befreit==2 && ($doctype=='rechnung' || $doctype=='gutschrift')) || - ($doctype!='proformarechnung' && $this->getStyleElement('beleg_pos_zolltarifnummer')=='1')) - { - if($value['zolltarifnummer']=='' || $value['zolltarifnummer']==0) { - $value['zolltarifnummer'] = $this->app->DB->Select("SELECT zolltarifnummer FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); - } - if($value['herkunftsland']=='' || $value['herkunftsland']==0) { - $value['herkunftsland'] = $this->app->DB->Select("SELECT herkunftsland FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); - } - } else { - $value['zolltarifnummer']=''; - $value['herkunftsland']=''; - } - - if($this->getStyleElement('beleg_pos_herkunftsland')=='1') - { - $value['herkunftsland']=''; - } - - $this->mhd[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('mhd',$doctype,$doctypeid,$posid); - // mhd - if($this->getStyleElement('beleg_pos_mhd')=='1') - { - $mhd=$this->mhd[$doctype][$doctypeid][$posid];//$this->GetChargeMHDSNString('mhd',$doctype,$doctypeid,$posid); - if(strpos($value['beschreibung'], '{MHD}') !== false) { - $value['beschreibung'] = str_replace( - '{MHD}', - $mhd, - $value['beschreibung'] - ); - } - if($mhd!='') { - $tmpvalue['mhd'] = $this->app->erp->Beschriftung('dokument_mhd').': '.$mhd; - } - } - - $this->charge[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('charge',$doctype,$doctypeid,$posid); - // charge - if($this->getStyleElement('beleg_pos_charge')=='1') - { - $charge=$this->charge[$doctype][$doctypeid][$posid]; - if(strpos($value['beschreibung'], '{CHARGE}') !== false) { - $value['beschreibung'] = str_replace( - '{CHARGE}', - $charge, - $value['beschreibung'] - ); - } - if($charge!='') { - $tmpvalue['charge'] = $this->app->erp->Beschriftung('dokument_charge').': '.$charge; - } - } - - $this->sn[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('sn',$doctype,$doctypeid,$posid); - // sn - if($this->getStyleElement('beleg_pos_sn')=='1') - { - $seriennr=$this->sn[$doctype][$doctypeid][$posid]; - if(strpos($value['beschreibung'], '{SN}') !== false) { - $value['beschreibung'] = str_replace( - '{SN}', - $seriennr, - $value['beschreibung'] - ); - } - if($seriennr!='') { - $tmpvalue['sn'] = $this->app->erp->Beschriftung('dokument_seriennummer').': '.$seriennr; - $value['seriennummer']=''; - } - } - - if(!empty($tmpvalue)) { - if($value['beschreibung']!=''){ - $value['beschreibung'] = $value['beschreibung'] . "\r\n" . implode("\r\n", $tmpvalue); - } - else{ - $value['beschreibung'] = implode("\r\n", $tmpvalue); - } - } - return $value; - } - - - - - public function addItem($rdata){ - // add rabatt - if($rdata['price']!='-'){ - if($rdata['rabatt'] == 100){ - $rdata['tprice'] = round($rdata['amount'] * ((double)$rdata['price'] - (double)($rdata['price'] / 100.00 * (double)$rdata['rabatt'])), 13); - }else{ - $rdata['tprice'] = $rdata['amount'] * ((double)$rdata['price'] - (double)($rdata['price'] / 100.00 * (double)$rdata['rabatt'])); - } - } - else { - $rdata['tprice']='-'; - } - $this->items[]=$rdata; - } - - public function setSender($rdata){ - $this->sender['enterprise'] = $this->app->erp->ReadyForPDF($rdata[0]); - $this->sender['firstname'] = $this->app->erp->ReadyForPDF($rdata[1]); - $this->sender['familyname'] = $this->app->erp->ReadyForPDF($rdata[2]); - $this->sender['address1'] = $this->app->erp->ReadyForPDF($rdata[3]); - $this->sender['areacode'] = $this->app->erp->ReadyForPDF($rdata[4]); - $this->sender['city'] = $this->app->erp->ReadyForPDF($rdata[5]); - if(isset($rdata[6])){ - $this->sender['country'] = $this->app->erp->ReadyForPDF($rdata[6]); - } - } - - function setRecipientRechnung($id) - { - - - } - - - function setRecipientLieferadresse($id,$table) - { - $this->id = $id; - $this->table = $table; - - if($table == 'serviceauftrag'){ - $adressid = $this->app->DB->Select("SELECT adresse FROM serviceauftrag WHERE id = '$id' LIMIT 1"); - if($adressid != "" && $adressid > 0){ - $tmp = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$adressid' LIMIT 1"); - } - }else{ - $tmp = $this->app->DB->SelectArr("SELECT * FROM $table WHERE id='$id' LIMIT 1"); - } - - $titelansprechpartner=""; - $titelname=""; - - if($tmp[0]['ansprechpartner']!='' && $tmp[0]['titel']!='') - { - $titelansprechpartner = $tmp[0]['titel'].' '; - } - else if ($tmp[0]['titel']!='') { - $titelname = $tmp[0]['titel'].' '; - } - - if($table != 'serviceauftrag'){ - if($tmp[0]['typ']==''){ - $tmp[0]['typ'] = $this->app->DB->Select("SELECT typ FROM adresse WHERE id='" . $tmp[0]['adresse'] . "' LIMIT 1"); - } - } - - $check = $this->app->DB->Select("SELECT bezeichnung FROM adresse_typ WHERE type='".$tmp[0]['typ']."' LIMIT 1"); - - if($check!="") - $this->recipient['anrede'] = $this->app->erp->ReadyForPDF($check); - else - $this->recipient['anrede'] = $this->app->erp->ReadyForPDF(ucfirst($tmp[0]['typ'])); - - - if($tmp[0]['typ']!="person") - { - $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($titelname.$tmp[0]['name']); - - - if($tmp[0]['abteilung']!='' && strlen($tmp[0]['abteilung']) >1){ - $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['abteilung']); - } - - if($tmp[0]['ansprechpartner']!='' && strlen($tmp[0]['ansprechpartner'])>1){ - $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($titelansprechpartner . $tmp[0]['ansprechpartner']); - } - - if(($table=='rechnung' || $table=='gutschrift') && $this->getStyleElement('rechnung_gutschrift_ansprechpartner')!='1'){ - $this->recipient['firstname'] = ''; - } - else if(($table=='angebot' || $table=='auftrag' || $table=='bestellung') && $this->getStyleElement('angebot_auftrag_bestellung_ansprechpartner')!='1'){ - $this->recipient['firstname'] = ''; - } - - - if($tmp[0]['unterabteilung']!=''){ - $this->recipient['address3'] = $this->app->erp->ReadyForPDF($tmp[0]['unterabteilung']); - } - - if($tmp[0]['adresszusatz']!=''){ - $this->recipient['address4'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); - } - - } - - else { - $vorname = ''; - if(isset($tmp[0]['vorname']) && $tmp[0]['vorname']!='' && strlen(trim($tmp[0]['vorname']))>0){ - $vorname = $tmp[0]['vorname'] . ' '; - } - - $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($vorname.$tmp[0]['name']); - $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); - } - - - $this->recipient['address1'] = $this->app->erp->ReadyForPDF($tmp[0]['strasse']); - $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($tmp[0]['plz']); - $this->recipient['city'] = $this->app->erp->ReadyForPDF($tmp[0]['ort']); - //if($this->recipient['city']!="") - $this->recipient['country'] = $this->app->erp->ReadyForPDF($tmp[0]['land']); - } - - - function setRecipientDB($adresse) - { - $tmp = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$adresse' LIMIT 1"); - if($tmp[0]['typ']!="person") - { - $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($tmp[0]['name']); - - if($tmp[0]['abteilung']!='' && strlen($tmp[0]['abteilung'])>1){ - $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['abteilung']); - } - - - $tmp[0]['anrede'] = $this->app->DB->Select("SELECT anrede FROM adresse WHERE id='".$tmp[0]['id']."' LIMIT 1"); - $check = $this->app->DB->Select("SELECT bezeichnung FROM adresse_typ WHERE type='".$tmp[0]['anrede']."' LIMIT 1"); - - if($check!=''){ - $this->recipient['anrede'] = $this->app->erp->ReadyForPDF($check); - } - else{ - $this->recipient['anrede'] = $this->app->erp->ReadyForPDF(ucfirst($tmp[0]['anrede'])); - } - - - if(($this->table=='rechnung' || $this->table=='gutschrift') && $this->getStyleElement('rechnung_gutschrift_ansprechpartner')=='1') - { - if($tmp[0]['ansprechpartner']!=''){ - $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($tmp[0]['ansprechpartner']); - } - } - else if(($this->table=='angebot' || $this->table=='auftrag' || $this->table=='bestellung') && $this->getStyleElement("angebot_auftrag_bestellung_ansprechpartner")=='1') - { - if($tmp[0]['ansprechpartner']!=''){ - $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($tmp[0]['ansprechpartner']); - } - } - - - if($tmp[0]['unterabteilung']!=''){ - $this->recipient['address3'] = $this->app->erp->ReadyForPDF($tmp[0]['unterabteilung']); - } - - if($tmp[0]['adresszusatz']!=''){ - $this->recipient['address4'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); - } - - } - - else { - $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($tmp[0]['name']); - $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); - } - - - $this->recipient['address1'] = $this->app->erp->ReadyForPDF($tmp[0]['strasse']); - $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($tmp[0]['plz']); - $this->recipient['city'] = $this->app->erp->ReadyForPDF($tmp[0]['ort']); - //if($this->recipient['city']!="") - $this->recipient['country'] = $this->app->erp->ReadyForPDF($tmp[0]['land']); - } - - - public function setRecipient($rdata){ - $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($rdata[0]); - $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($rdata[1]); - $this->recipient['familyname'] = $this->app->erp->ReadyForPDF($rdata[2]); - $this->recipient['address1'] = $this->app->erp->ReadyForPDF($rdata[3]); - $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($rdata[4]); - $this->recipient['city'] = $this->app->erp->ReadyForPDF($rdata[5]); - if(isset($rdata[3]))$this->recipient['country'] = $this->app->erp->ReadyForPDF($rdata[6]); - } - - public function setCorrDetails($rdata, $onlyData = false){ - if($onlyData) { - $this->corrDetails = $rdata; - return; - } - - if($this->getStyleElement("projektnummerimdokument")=='1'){ - $rdata[$this->app->erp->Beschriftung("dokument_projekt")] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='" . $this->projekt . "' LIMIT 1"); - } - - if($this->getStyleElement("internetnummerimbeleg")=='1') - { - switch($this->doctype) - { - case "rechnung": - case "lieferschein": - $internetnummer = $this->app->DB->Select("SELECT a.internet FROM auftrag a LEFT JOIN ".$this->doctype." b ON b.auftragid=a.id WHERE b.id='".$this->doctypeid."' LIMIT 1"); - break; - case "gutschrift": - $internetnummer = $this->app->DB->Select("SELECT a.internet FROM gutschrift g LEFT JOIN rechnung r ON r.id=g.rechnungid LEFT JOIN auftrag a ON a.id=r.auftragid WHERE g.id='".$this->doctypeid."' LIMIT 1"); - break; - case "auftrag": - $internetnummer = $this->app->DB->Select("SELECT internet FROM auftrag WHERE id='".$this->doctypeid."' LIMIT 1"); - break; - default: - $internetnummer = ''; - - } - //$rdata[$this->getStyleElement("beschriftunginternetnummer")]=$internetnummer; - $rdata[$this->app->erp->Beschriftung("beschriftunginternetnummer")]=$internetnummer; - } - if($this->doctype=="rechnung"||$this->doctype=="lieferschein"||$this->doctype=="gutschrift"||$this->doctype=="auftrag"||$this->doctype=="angebot"||$this->doctype=="lieferschein") - { - if($this->doctype=='lieferschein'){ - $tabelle='lieferschein'; - }else { - $tabelle=$this->doctype; - } -// $bearbeiteremail = $this->app->DB->Select("SELECT b.email FROM ".$this->doctype." a LEFT JOIN adresse adr ON a.adresse=adr.id LEFT JOIN adresse b ON b.id=adr.innendienst WHERE a.id='".$this->doctypeid."' LIMIT 1"); - // $bearbeitertelefon = $this->app->DB->Select("SELECT b.telefon FROM ".$this->doctype." a LEFT JOIN adresse adr ON a.adresse=adr.id LEFT JOIN adresse b ON b.id=adr.innendienst WHERE a.id='".$this->doctypeid."' LIMIT 1"); - - $bearbeiteremail = $this->app->DB->Select("SELECT b.email FROM ".$tabelle." a LEFT JOIN adresse b ON b.id=a.bearbeiterid WHERE a.id='".$this->doctypeid."' LIMIT 1"); - $bearbeitertelefon = $this->app->DB->Select("SELECT b.telefon FROM ".$tabelle." a LEFT JOIN adresse b ON b.id=a.bearbeiterid WHERE a.id='".$this->doctypeid."' LIMIT 1"); - } - - if($this->getStyleElement('bearbeiteremailimdokument')=='1'){ - $rdata[$this->app->erp->Beschriftung('dokument_email')] = $bearbeiteremail; - } - if($this->getStyleElement('bearbeitertelefonimdokument')=='1'){ - $rdata[$this->app->erp->Beschriftung('dokument_telefon')] = $bearbeitertelefon; - } - - - //$rdata[$this->getStyleElement("beschriftungbearbeiteremail")]=$internetnummer; - //$rdata[$this->getStyleElement("beschriftungbearbeitertelefonnummer")]=$internetnummer; - - $this->corrDetails = $rdata; - } - public function setBoldCorrDetails($rdata){ - $this->boldCorrDetails = $rdata; - } - - public function setItalicBoldCorrDetails($rdata){ - $this->italicBoldCorrDetails = $rdata; - } - - public function setItalicCorrDetails($rdata){ - $this->italicCorrDetails = $rdata; - } - - public function setTextDetails($rdata){ - $this->textDetails = $rdata; - } - - - public function setTotals($rdata){ - $this->totals = $rdata; - } - - // Briefpapier festlegen - public function setStationery($stationeryfile) { - $this->setSourceFile($stationeryfile); - $tplidx = $this->ImportPage(1); - $this->useTemplate($tplidx); - } - /* - public function setLogo($logofile) { - $this->logofile = "./lib/pdf/images/".$logofile; - } - */ - - // label settings - public function setBarcode($barcode) { - $barcode = preg_replace('/[^0-9a-zA-Z\-]/', '', $barcode); - if($this->barcode_sichtbar) - $this->barcode = $barcode; - else $this->barcode=""; - - } - - - public function Header() { - if($this->knickfalz!='1'){ - $this->Line(0,105,5,105); - $this->Line(0,148,7,148); - $this->Line(0,210,5,210); - } - if($this->logofile!='') - $this->Image($this->logofile,15,10,110); - - if($this->barcode!='' && $this->briefpapier==''){ - //$this->Rotate(90); - $this->Code39($this->barcode_x, $this->barcode_y, $this->barcode, 1, 3); - //$this->Rotate(0); - } - - if($this->briefpapier!='' && $this->PageNo()<=1) - $this->setStationery($this->briefpapier); - - // wenn - if($this->PageNo() > 1 && $this->briefpapier2!='' && $this->briefpapier2vorhanden=='1'){ - if($this->doctype != 'produktion'){ - $this->setStationery($this->briefpapier2); - } - } - else if ( $this->PageNo() > 1 && $this->briefpapier!=''){ - $this->setStationery($this->briefpapier); - } - - - if($this->PageNo() > 1) - { - $this->SetY($this->abseite2y); - } - } - - public function Footer() { - $differenz=12; - $this->SetXY(12,$this->getStyleElement("abstand_seiten_unten")*-1); - $this->SetFont($this->GetFont(),'',8); - - - if($this->seite_von_sichtbar!="1") - { - if($this->getStyleElement("seite_von_ausrichtung_relativ")=="1")// && $this->seite_von_ausrichtung=="C") - { - $this->SetX($this->getStyleElement("abstand_seitenrandlinks")); - $differenz = $this->getStyleElement("abstand_seitenrandlinks"); - } - - $tmp = $this->rMargin; - if($this->getStyleElement("abstand_seitenrandrechts")>0) - $this->rMargin=$this->getStyleElement("abstand_seitenrandrechts"); - else - $this->rMargin=$this->getStyleElement("abstand_seitenrandlinks"); - - $tmpc = $this->cMargin; - if($this->seite_von_ausrichtung=="R") - $this->cMargin=-3; - - if($this->getStyleElement("seite_belegnr")) - $this->Cell(0,8,$this->app->erp->Beschriftung("dokument_seite").' '.$this->PageNo().' '.$this->app->erp->Beschriftung("dokument_seitevon").' {nb} '.$this->zusatzfooter,0,0,$this->seite_von_ausrichtung); - else - $this->Cell(0,8,$this->app->erp->Beschriftung("dokument_seite").' '.$this->PageNo().' '.$this->app->erp->Beschriftung("dokument_seitevon").' {nb}',0,0,$this->seite_von_ausrichtung); - - $this->cMargin = $tmpc; - - $this->rMargin=$tmp; - } - - if($this->nichtsichtbar_footer!=true) - { - - $footerarr = $this->app->DB->SelectArr("SELECT * FROM firmendaten WHERE id='".$this->firmendatenid."' LIMIT 1"); - $firmendaten_extra = $this->app->DB->SelectArr("SELECT * FROM firmendaten_werte"); - if($firmendaten_extra) - { - foreach($firmendaten_extra as $v) - { - if(!isset($footerarr[0][$v['name']]))$footerarr[0][$v['name']] = $v['wert']; - } - } - $footerarr = $footerarr[0]; - - foreach($footerarr as $key=>$value) - $footerarr[$key] = utf8_decode($value); - - $this->SetXY(10,-26); - $this->SetDrawColor($this->getStyleElement("footer_farbe")); - $this->SetTextColor($this->getStyleElement("footer_farbe")); - - $this->SetFont($this->GetFont(),'',7); - - - if($this->getStyleElement("footer_zentriert")!=1) - { - $this->MultiCell($footerarr['footer_breite1'],3,utf8_encode(" ".$footerarr['footer_0_0']."\n ".$footerarr['footer_0_1']."\n ".$footerarr['footer_0_2']."\n ".$footerarr['footer_0_3']."\n ".$footerarr['footer_0_4']."\n ".$footerarr['footer_0_5'].""),'','L'); - $this->SetXY($footerarr['footer_breite1'] + 10,-26); // Breite 1 + 10 - $this->MultiCell($footerarr['footer_breite2'],3,utf8_encode(" ".$footerarr['footer_1_0']."\n ".$footerarr['footer_1_1']."\n ".$footerarr['footer_1_2']."\n ".$footerarr['footer_1_3']."\n ".$footerarr['footer_1_4']."\n ".$footerarr['footer_1_5'].""),'','L'); - $this->SetXY($footerarr['footer_breite1'] + $footerarr['footer_breite2'] + 10,-26); //breite 1 + breite 2 + 10 - $this->MultiCell($footerarr['footer_breite3'],3,utf8_encode(" ".$footerarr['footer_2_0']."\n ".$footerarr['footer_2_1']."\n ".$footerarr['footer_2_2']."\n ".$footerarr['footer_2_3']."\n ".$footerarr['footer_2_4']."\n ".$footerarr['footer_2_5'].""),'','L'); - $this->SetXY($footerarr['footer_breite1'] + $footerarr['footer_breite2'] + $footerarr['footer_breite3'] + 10,-26); //breite 1 + breite 2 + breite 3 + 10 - $this->MultiCell($footerarr['footer_breite4'],3,utf8_encode(" ".$footerarr['footer_3_0']."\n ".$footerarr['footer_3_1']."\n ".$footerarr['footer_3_2']."\n ".$footerarr['footer_3_3']."\n ".$footerarr['footer_3_4']."\n ".$footerarr['footer_3_5'].""),'','L'); - } else { - $this->MultiCell(0,3,utf8_encode(" ".$footerarr['footer_0_0']."\n ".$footerarr['footer_0_1']."\n ".$footerarr['footer_0_2']."\n ".$footerarr['footer_0_3']."\n ".$footerarr['footer_0_4']."\n ".$footerarr['footer_0_5'].""),'','C'); - - - } - } - } - - /** - * @param string $parameter - * - * @return array|null - */ - protected function getOldDocument(string $parameter): ?array - { - return $this->app->DB->SelectRow( - "SELECT * - FROM `pdfarchiv` - WHERE `table_id` = '".$this->id."' - AND `table_name` = '".$this->table."' - AND `doctype` = '".$this->app->DB->real_escape_string($this->doctype)."' - AND `doctypeorig` = '".$this->app->DB->real_escape_string($this->doctypeOrig)."' - AND CHAR_LENGTH(`belegnummer`) > 2 - AND `belegnummer` <> 'SAB' - AND `parameter` = '$parameter' - AND `keinhintergrund` = '".($this->app->erp->BriefpapierHintergrunddisable?'1':'0')."' - ORDER BY `zeitstempel` DESC - LIMIT 1" - ); - } - - /** - * @param string $path - * - * @return bool - */ - protected function checkAndUpdateDocumentName(string $path): bool - { - if(!file_exists($path)){ - return false; - } - $pathInfos = explode('_', basename($path),3); - $md5 = md5_file($path); - if($md5 === $pathInfos[0]){ - return false; - } - - return $this->updateDocumentEntry($pathInfos, $md5,$path); - } - - /** - * @param array $fileInfos - * @param string $md5 - * @param string $filePath - */ - protected function updateDocumentEntry(array $fileInfos, string $md5, string $filePath): bool - { - $fileName = basename($filePath); - $dir = dirname($filePath); - $newFileName = $md5 . '_' . explode('_', basename($filePath),2)[1]; - $newFilePath = $dir . '/' . $newFileName; - $tableId = $fileInfos[1]; - if(file_exists($newFilePath)){ - $this->checkAndUpdateDocumentName($newFilePath); - } - if(file_exists($newFilePath)){ - return false; - } - - $this->updatePdfArchiveEntry((int)$tableId, $md5, $newFileName, $fileName); - rename($dir . '/' . $fileName, $newFilePath); - - return true; - } - - /** - * @param int $tableId - * @param string $md5 - * @param string $newFileName - * @param string $oldFilename - */ - protected function updatePdfArchiveEntry(int $tableId, string $md5, string $newFileName, string $oldFilename): void - { - $this->app->DB->Update( - "UPDATE `pdfarchiv` - SET `checksum` = '{$md5}', `dateiname` = '{$newFileName}' - WHERE `dateiname` = '{$oldFilename}' AND `table_id` = {$tableId} AND `table_name` = '{$this->table}'" - ); - } - - /** - * @param string $checkSum - * @param string $fileName - * @param string $documentNumber - * @param string $parameter - * - * @return int - */ - protected function createPdfArchiveEntry( - string $checkSum, string $fileName, string $documentNumber, string $parameter = '' - ): int - { - $userName = $this->app->DB->real_escape_string($this->app->User->GetName()); - $documentType = $this->app->DB->real_escape_string($this->doctype); - $originalDocumentType = $this->app->DB->real_escape_string($this->doctypeOrig); - $documentNumber = $this->app->DB->real_escape_string($documentNumber); - $parameter = $this->app->DB->real_escape_string($parameter); - $noBackGround = $this->app->erp->BriefpapierHintergrunddisable ? 1 : 0; - $this->app->DB->Insert( - "INSERT INTO `pdfarchiv` - ( - `schreibschutz`, `zeitstempel`, `checksum`, `table_id`, `table_name`, `bearbeiter`, - `erstesoriginal`, `doctype`, `doctypeorig`, `dateiname`, - `belegnummer`, `keinhintergrund`, `parameter` - ) - VALUES - ( - 1, NOW(), '{$checkSum}', '{$this->id}', '{$this->table}', '{$userName}', - 0, '{$documentType}', '{$originalDocumentType}', '{$fileName}', - '{$documentNumber}', '{$noBackGround}', '{$parameter}' - )" - ); - - return (int)$this->app->DB->GetInsertID(); - } - - /** - * @param false $schreibschutz - * @param false $force - * @param string $parameter - */ - public function ArchiviereDocument($schreibschutz = false, $force = false, $parameter = ''): void - { - if(!$schreibschutz){ - $schreibschutz = (bool)$this->app->DB->Select( - "SELECT `schreibschutz` FROM `{$this->table}` WHERE `id` = '{$this->id}' LIMIT 1" - ); - } - - if($parameter == ''){ - $parameter = $this->parameter; - } - - if($this->ausarchiv){ - return; - } - - $isDraft = $this->app->DB->Select( - "SELECT `id` FROM `{$this->table}` WHERE `id` = '{$this->id}' AND `belegnr` <> '' AND `belegnr` <> '0' LIMIT 1" - ) === null; - - if($isDraft){ - return; - } - - if($force) { - $this->app->DB->Update("UPDATE `{$this->table}` SET `schreibschutz` = 1 WHERE `id` = '{$this->id}' LIMIT 1"); - $schreibschutz = true; - } - - if(!$schreibschutz){ - return; - } - - $this->filename = $this->app->erp->Dateinamen($this->filename); - $dir = rtrim($this->app->Conf->WFuserdata, '/') . '/pdfarchiv/' . $this->app->Conf->WFdbname . '/' . $this->table; - if(!is_dir($dir) && !mkdir($dir, 0700,true) && !is_dir($dir)){ - $this->app->erp->LogFile('Fehler beim erstellen von '.$dir); - return; - } - - $dir = dirname(Briefpapier::getPDFfolder($dir, $this->id, $this->id . '_' . $this->filename, false, true)); - $absoluteFilePath = $dir . '/' .$this->id . '_' . $this->filename; - - $oldDocument = $this->getOldDocument((string)$parameter); - $isOldDocumentFileExists = !empty($oldDocument['dateiname']) && is_file($dir . '/' . $oldDocument['dateiname']); - $hasOldDocumentFileMd5Sum = $isOldDocumentFileExists - && !empty($oldDocument['checksum']) - && strpos($oldDocument['dateiname'], $oldDocument['checksum']) ===0; - if($hasOldDocumentFileMd5Sum) { - $oldFile = $dir . '/' . $oldDocument['dateiname']; - if($this->checkAndUpdateDocumentName($oldFile)) { - $oldDocument = $this->getOldDocument((string)$parameter); - $isOldDocumentFileExists = !empty($oldDocument['dateiname']) && is_file($dir . '/' . $oldDocument['dateiname']); - } - } - $oldFile = $isOldDocumentFileExists ? $dir . '/' . $oldDocument['dateiname'] : null; - if($oldFile !== null && !$force) { - return; - } - $documentNumber = str_ireplace('.pdf', '', substr($this->filename, strrpos($this->filename, '_') + 1)); - // If the current document file does not exist - if(!file_exists($absoluteFilePath)){ - // save this document to file - $this->Output($absoluteFilePath, 'F'); - if(empty($oldDocument) || $oldDocument['dateiname'] !== basename($absoluteFilePath)) { - $this->createPdfArchiveEntry( - md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter - ); - } - $this->resetToArchiveFlag(); - return; - } - // create a new temp file - $tempFilePath = $dir . '/' .$this->id . '_temp' . $this->filename; - $this->Output($tempFilePath, 'F'); - if($oldFile !== null && $this->areFilesEqualExceptCreationDate($oldFile, $tempFilePath)) { - unlink($tempFilePath); - $this->resetToArchiveFlag(); - return; - } - $md5CurrentFile = md5_file($absoluteFilePath); - // and compare with existing file - if($this->areFilesEqualExceptCreationDate($absoluteFilePath, $tempFilePath)){ - //if($md5CurrentFile === md5_file($tempFilePath)){ - // If same, delete temp file and - unlink($tempFilePath); - $this->resetToArchiveFlag(); - return; - } - // build the file name with md5_hash - $md5FileName = $dir . '/' . $md5CurrentFile . '_' . $this->id . '_' . $this->filename; - // check if the file exists - $this->checkAndUpdateDocumentName($md5FileName); - if(!file_exists($md5FileName)){ - rename($absoluteFilePath, $md5FileName); - $this->updatePdfArchiveEntry($this->id, $md5CurrentFile, basename($md5FileName), basename($absoluteFilePath)); - - rename($tempFilePath, $absoluteFilePath); - $this->createPdfArchiveEntry( - md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter - ); - $this->resetToArchiveFlag(); - return; - } - if($this->areFilesEqualExceptCreationDate($absoluteFilePath, $md5FileName)){ - rename($tempFilePath, $absoluteFilePath); - $this->createPdfArchiveEntry( - md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter - ); - $this->resetToArchiveFlag(); - return; - } - - unlink($tempFilePath); - $this->resetToArchiveFlag(); - } - - /** - * resolve to-archive request for document, after creating new pdf-file - */ - public function resetToArchiveFlag(): void - { - if(empty($this->id) || empty($this->table)) { - return; - } - $this->app->DB->Update("UPDATE `{$this->table}` SET `zuarchivieren` = 0 WHERE `id` = {$this->id} LIMIT 1"); - } - - /** - * @param string $firstFilePath - * @param string $secondFilePath - * @return bool - */ - public function areFilesEqualExceptCreationDate(string $firstFilePath, string $secondFilePath) - { - if(!file_exists($firstFilePath) || !file_exists($secondFilePath)){ - return false; - } - - $pattern = '#CreationDate \(D:[0-9]+\)#'; - - $contentFirstFile = preg_replace($pattern, '', @file_get_contents($firstFilePath)); - $contentSecondFile = preg_replace($pattern, '', @file_get_contents($secondFilePath)); - - return md5($contentFirstFile) === md5($contentSecondFile); - } - - public function DocumentArchiviert() - { - $this->filename = $this->app->erp->Dateinamen($this->filename); - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname; - if(!is_dir($dir)){ - return false; - } - if(!is_dir($dir.'/'.$this->table)){ - return false; - } - - $md5alt = false; - $altesdokument = $this->app->DB->SelectRow("SELECT * from pdfarchiv where table_id = '".$this->id."' and table_name = '".$this->table."' AND doctype = '".$this->app->DB->real_escape_string($this->doctype)."' AND doctypeorig = '".$this->app->DB->real_escape_string($this->doctypeOrig)."' AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND parameter = '".$this->parameter."' ORDER BY zeitstempel DESC LIMIT 1"); - if(empty($altesdokument)){ - return false; - } - - $md5alt = $altesdokument['checksum']; - if(!file_exists($dir.'/'.$this->table.'/'.$md5alt.'_'.$this->id.'_'.$this->filename)) { - $file = Briefpapier::getPDFfolder($dir.'/'.$this->table, $this->id,$md5alt.'_'.$this->id.'_'.$this->filename); - if(!file_exists($file)){ - return false; - } - } - - $this->Output($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename,'F'); - $md5sum_tmp = md5_file($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename); - unlink($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename); - return $md5sum_tmp == $md5alt; - } - - - public function archiveDocument($parameter = '') - { - if($this->table && $this->id) - { - $this->ArchiviereDocument($this->app->DB->Select('SELECT schreibschutz FROM `'.trim($this->app->DB->real_escape_string($this->table))."` WHERE id = '".(int)$this->id."' LIMIT 1")?true:false,false, $parameter); - }else{ - $this->ArchiviereDocument(); - } - } - - public static function getPDFfolder($folder, $tableid, $file = '', $forcenew = false, $createfolder = false) - { - if($file === '') { - $file = $folder; - $folder = dirname($folder); - $file = substr($file, strlen($folder)+1); - } - if(!$forcenew && file_exists($folder.'/'.$file)) { - return $folder.'/'.$file; - } - $tableida = str_split($tableid, 1); - $newfolder = $folder. '/'.implode('/',$tableida); - if(!$createfolder) { - return $newfolder.'/'.$file; - } - - if(!is_dir($newfolder) && !mkdir($newfolder,0700,true) && !is_dir($newfolder)){ - return $folder.'/'.$file; - } - - return $newfolder.'/'.$file; - } - - public function inlineDocument($from_archiv = false) { - //$from_archiv=false; - //$filenameprefix = substr($this->filename,9,2); - $content = null; - if($from_archiv && !empty($this->table) && !empty($this->id)) { - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; - if(is_dir($dir)) { - if($this->table === 'rechnung') { - $filenameprefix = substr($this->filename,9,2); - $mirror = $this->app->DB->Select( - "SELECT dateiname - FROM pdfarchiv - WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' - ORDER BY zeitstempel DESC - LIMIT 1" - ); - } - else{ - $mirror = $this->app->DB->Select( - "SELECT dateiname - FROM pdfarchiv - WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' - ORDER BY zeitstempel DESC - LIMIT 1" - ); - } - if(!empty($mirror)) { - $file = Briefpapier::getPDFfolder($dir,$this->id, $mirror); - //if(is_file($dir.'/'.$mirror)) - if(is_file($file)) { - //$content = file_get_contents($dir.'/'.$mirror); - $content = file_get_contents($file); - if(!empty($content)) { - header('Content-type: application/pdf'); - echo $content; - $this->app->ExitXentral(); - } - } - } - } - } - - $this->renderDocument(); - $this->archiveDocument(); - header('Content-type: application/pdf'); - $this->Output(); - - $this->app->ExitXentral(); - } - - /** - * @param int $tableid - * @param string $tablename - * - * @return bool - */ - public function zuArchivieren($tableid, $tablename) - { - if($tablename) { - $check = $this->app->DB->Select("SELECT zuArchivieren FROM `$tablename` WHERE id = '$tableid'"); - } - if($check){ - return true; - } - $mirrors = $this->app->DB->SelectArr( - "SELECT * - FROM pdfarchiv - WHERE table_id = '".$tableid."' AND `table_name` = '".$tablename."' AND erstesoriginal = 0 - AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND parameter = '".$this->parameter."' - AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' - ORDER BY zeitstempel DESC" - ); - if(empty($mirrors)) { - return true; - } - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$tablename; - if(!is_dir($dir)) { - return true; - } - foreach($mirrors as $k => $mirror) { - $dateipfad = Briefpapier::getPDFfolder($dir,$tableid,$mirror['dateiname']); - if(!empty($mirror['dateiname']) && file_exists($dateipfad)) { - return false; - } - } - - return true; - } - - /** - * @param int $id - */ - public function movePDFArchiv($id) - { - - $mirrors = $id <=0?null:$this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM pdfarchiv WHERE id = %d', - $id - ) - ); - - if(empty($mirrors) || empty($mirrors['dateiname'])) { - return; - } - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$mirrors['table_name']; - if(!is_file($dir.'/'.$mirrors['dateiname'])) { - return; - } - $newfile = self::getPDFfolder($dir,$mirrors['table_id'],$mirrors['dateiname'],true,true); - if($newfile != $dir.'/'.$mirrors['dateiname'] && !is_file($newfile)) { - @rename($dir.'/'.$mirrors['dateiname'], $newfile); - } - } - - /** - * @param int $tableid - * @param string $tablename - * - * @return array|bool - */ - public function getArchivedFiles($tableid, $tablename) - { - $mirrors = $this->app->DB->SelectArr("SELECT * from pdfarchiv where table_id = '".$tableid."' and table_name = '".$tablename."' AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND keinhintergrund = 0 ORDER BY zeitstempel DESC"); - if(!$mirrors){ - return false; - } - - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$tablename; - if(!is_dir($dir)) { - return false; - } - - foreach($mirrors as $k => $mirror) { - $dateipfad = Briefpapier::getPDFfolder($dir,$tableid,$mirror['dateiname']); - if(!$mirror['dateiname'] || !file_exists($dateipfad)) { - unset($mirrors[$k]); - } - else{ - $mirrors[$k]['file'] = $mirror['dateiname']; - } - } - - if(empty($mirrors)) { - return false; - } - - return $mirrors; - } - - public function getArchivedFiles_alt($tableid, $tablename) - { - - $mirrors = $this->app->DB->SelectArr("SELECT * from pdfmirror_md5pool where table_id = '".$tableid."' and table_name = '".$tablename."' ORDER BY zeitstempel DESC"); - - if(!$mirrors)return false; - - $dir = $this->app->Conf->WFuserdata."/pdfmirror/".$this->app->Conf->WFdbname.'/'.$tablename; - if(is_dir($dir)) - { - - - $files = glob($dir.'/*.pdf'); - if(!$files)return false; - - foreach($files as $file) - { - $path_parts = pathinfo($file); - foreach($mirrors as $k => $mirror) - { - if($mirror['checksum']) - { - - if(strpos($path_parts['basename'],$mirror['checksum'])=== 0) - { - $mirrors[$k]['file'] = $path_parts['basename']; - } - - } else { - if(strpos($path_parts['filename'], $tableid.'_') === 0){ - $mirrors[$k]['file'] = $path_parts['basename']; - } - - } - - } - } - foreach($mirrors as $k => $mirror) - { - if(!isset($mirror['file']))unset($mirrors[$k]); - } - - if(!isset($mirrors) || count($mirrors) < 1)return false; - - return $mirrors; - } - return false; - } - - /** - * @param int $id - * - * @return bool|array - */ - public function getArchivByID($id) - { - $id = (int)$id; - if($id <= 0) { - return false; - } - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname; - if(!is_dir($dir)) { - return false; - } - $mirror = $this->app->DB->SelectRow(sprintf('SELECT * FROM pdfarchiv WHERE id = %d LIMIT 1', $id)); - if(empty($mirror)){ - return false; - } - - if(empty($mirror['dateiname'])) { - return false; - } - $file = Briefpapier::getPDFfolder($dir.'/'.$mirror['table_name'], $mirror['table_id'], $mirror['dateiname']); - - if(!file_exists($file)) { - return false; - } - - $tmpr['belegnr'] = $mirror['belegnummer']; - $tmpr['file'] = file_get_contents($file); - - return $tmpr; - } - - public function getArchivByID_alt($id) - { - $id = (int)$id; - if(!$id)return false; - $dir = $this->app->Conf->WFuserdata."/pdfmirror/".$this->app->Conf->WFdbname; - if(!is_dir($dir))return false; - $mirror = $this->app->DB->SelectArr("SELECT * from pdfmirror_md5pool where id = '$id' LIMIT 1"); - if(!$mirror)return false; - $mirror = reset($mirror); - $mirrors = $this->getArchivedFiles_alt($mirror['table_id'], $mirror['table_name']); - if(!$mirrors)return false; - foreach($mirrors as $mirror) - { - //echo "."; - if($mirror['id'] == $id) - { - //echo ":"; - if(file_exists($dir."/".$mirror['table_name']."/".$mirror['file'])) - { - //echo ";"; - $tmpr['belegnr'] = str_replace('.pdf','',$mirror['file']); - $tmpr['belegnr'] = substr($tmpr['belegnr'],strrpos($tmpr['belegnr'],'_')+1); - $tmpr['file'] = file_get_contents($dir."/".$mirror['table_name']."/".$mirror['file']); - return $tmpr; - } - return false; - } - } - return false; - } - - /** - * @param bool $from_archiv - */ - public function displayDocument($from_archiv = false) { - //$from_archiv=false; - if($from_archiv) { - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; - if($this->table && $this->id && is_dir($dir)) { - if($this->table === 'rechnung') { - $filenameprefix = substr($this->filename,9,2); - $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); - } - else{ - $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); - } - if($mirror) { - $file = Briefpapier::getPDFfolder($dir, $this->id, $mirror); - //if(is_file($dir.'/'.$mirror)) - if(is_file($file)) { - //$content = file_get_contents($dir.'/'.$mirror); - $content = file_get_contents($file); - if(!empty($content)) { - $this->filename = $this->app->erp->Dateinamen($this->filename); - header('Content-type: application/pdf'); - header('Content-Disposition: attachment; filename="'.$this->filename.'"'); - echo $content; - $this->app->ExitXentral(); - } - } - } - } - } - $this->filename = $this->app->erp->Dateinamen($this->filename); - - $this->renderDocument(); - $this->archiveDocument(); - $this->Output($this->filename,'D'); - $this->app->ExitXentral(); - } - - public function displayTMP($from_archiv = false) { - //if(!$from_archiv && $this->table && $this->id)$from_archiv = $this->app->DB->Select("SELECT schreibschutz FROM `".$this->table."` WHERE id = '".$this->id."' LIMIT 1"); - if($from_archiv) { - $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; - if($this->table && $this->id && is_dir($dir)) { - if($this->table === 'rechnung') { - $filenameprefix = substr($this->filename,9,2); - $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); - } - else{ - $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); - } - if($mirror){ - $mirror2 = Briefpapier::getPDFfolder($dir,$this->id, $mirror); - if(is_file($mirror2)) { - $mirror = substr($mirror2, strlen($dir)+1); - } - if(is_file($dir.'/'.$mirror)){ - $this->filename = $this->app->erp->Dateinamen($this->filename); - $content = file_get_contents($dir.'/'.$mirror); - if($content != '' && file_put_contents($this->app->erp->GetTMP().$this->filename,$content)){ - if($this->addpdf){ - $files[] = $this->app->erp->GetTMP().$this->filename; - foreach($this->addpdf as $file){ - $files[] = $file; - } - $content = $this->app->erp->MergePDF($files); - file_put_contents($this->app->erp->GetTMP().$this->filename,$content); - } - $this->ausarchiv = true; - return $this->app->erp->GetTMP().$this->filename; - } - } - } - } - } - - $this->renderDocument(); - $this->archiveDocument(); - $this->filename = $this->app->erp->Dateinamen($this->filename); - $this->Output($this->app->erp->GetTMP().$this->filename,'F'); - - return $this->app->erp->GetTMP().$this->filename; - } - - public function sendDocument($from_archiv = false) { - $this->renderDocument(); - $this->archiveDocument(); - $this->filename = $this->app->erp->Dateinamen($this->filename); - $this->Output($this->filename,'S'); - $this->app->ExitXentral(); - } - - /*********************************** - * public functions - ***********************************/ - // setup relevant data for a invoice - public function setupTax() { - // full taxrate - // define("USTV",0.19); - // reduced taxrate - // define("USTR",0.07); - } - - - public function calcTotals() { - $total=$totalFullTax=$totalReducedTax=0; - $citems = !empty($this->items)?count($this->items):0; - for($i=0;$i<$citems;$i++) { - $total += $this->items[$i]['tprice']; - if($this->items[$i]['tax']=="USTV") { - $totalFullTax+= $this->items[$i]['tprice']*USTV; - } - else { - $totalReducedTax+= $this->items[$i]['tprice']*USTR; - } - } - return array($total,$totalFullTax,$totalReducedTax); - } - - function GetFont() - { - if($this->getStyleElement('schriftart')!=''){ - return $this->getStyleElement('schriftart'); - } - - return 'Arial'; - } - - public function setStyleData($styleData){ - $this->styleData = $styleData; - } - - private function getStyleElement($key){ - if(isset($this->styleData[$key]) && !empty($this->styleData[$key])) return $this->styleData[$key]; - - return $this->app->erp->Firmendaten($key); - } - - public function renderDocument() { - // prepare page details - parent::__construct('P','mm','A4'); - $this->app->erp->RunHook('briefpapier_render_document_hook1', 1, $this); - - - // if($this->getStyleElement("schriftart")!="") - // $this->SetFont($this->getStyleElement("schriftart")); - - $font = $this->getStyleElement('schriftart'); - - if(!in_array($font, ['', 'Arial', 'Courier', 'Helvetica', 'Times'])){ - $this->AddFont($font,'',strtolower($font).'.php'); - - if(is_file("lib/pdf/font/".strtolower($font).'i.php')) - $this->AddFont($font,'I',strtolower($font).'i.php'); - else - $this->AddFont($font,'I',strtolower($font).'.php'); - - if(is_file("lib/pdf/font/".strtolower($font).'b.php')) - $this->AddFont($font,'B',strtolower($font).'b.php'); - else - $this->AddFont($font,'B',strtolower($font).'.php'); - - if(is_file("lib/pdf/font/".strtolower($font).'bi.php')) - $this->AddFont($font,'BI',strtolower($font).'bi.php'); - else - $this->AddFont($font,'BI',strtolower($font).'.php'); - - } - - // invoke Header() and Footer() by adding a new page - $this->AddPage(); - //$this->setStationery("/home/eproo/eproo-master/app/main/www/lib/dokumente/demo.pdf"); - $this->SetDisplayMode("real","single"); - - if($this->getStyleElement("abstand_seitenrandrechts")=="") - $this->getStyleElementSet("abstand_seitenrandrechts",$this->getStyleElement("abstand_seitenrandlinks")); - - $this->SetMargins($this->getStyleElement("abstand_seitenrandlinks"),50,$this->getStyleElement("abstand_seitenrandrechts")); - $this->SetAutoPageBreak(true,$this->getStyleElement("abstand_umbruchunten")); - $this->AliasNbPages('{nb}'); - - // render document top to bottom - if(!$this->nichtsichtbar_empfaenger) - { - if(!empty($this->recipient)) - $this->renderRecipient(); - } - - if($this->doctype=="lieferschein" && !empty($this->barcode)) - { - if($this->barcode_y_header!=0) - $y = $this->barcode_y_header; - else - $y = $this->GetY(); - $this->Code39($this->barcode_x_header, $y+1, $this->barcode, 1, 5); - } - - if($this->barcode!="" && $this->briefpapier!=""){ - $this->Code39($this->barcode_x, $this->barcode_y, $this->barcode, 1, 3); - } - - //if(!empty($this->sender)) - $this->renderSender(); - - if(!$this->nichtsichtbar_box) - { - if(!empty($this->corrDetails) || !empty($this->boldCorrDetails) || !empty($this->italicCorrDetails) - || !empty($this->italicBoldCorrDetails)) - $this->renderCorrDetails(); - } - - $this->renderDoctype(); - if($this->doctype=="brief") - { - $this->SetY(95); - $this->textDetails['body']=$this->letterDetails['body']; - } - - $this->renderText(); - if(!empty($this->items)) { - $this->renderItems(); - $this->SetTextColor(0,0,0); - if($this->doctype!="lieferschein" && $this->doctype!="preisanfrage" && !$this->nichtsichtbar_summe) { - $this->renderTotals(); - } else $this->Cell(1,5,'',0); - } - $this->renderFooter(); - $this->logofile = ""; - $this->briefpapier=""; - $this->briefpapier2=""; - if($this->addpdf) - { - foreach($this->addpdf as $addpdf) - { - $filename = $addpdf; - $this->AddPage(); - $this->SetXY(0,0); - $anz = $this->setSourceFile($filename); - for($i = 1; $i <= $anz; $i++) - { - if($i > 1) - { - $this->AddPage(); - $this->SetXY(0,0); - } - $tplidx = $this->ImportPage($i); - $this->useTemplate($tplidx); - } - } - } - $this->app->erp->RunHook('briefpapier_render_document_hook2', 1, $this); - } - - - public function renderRecipient(){ - // $this->SetY(50); - $this->SetY(50+$this->abstand_adresszeileoben); - $this->SetFont($this->GetFont(),'',10); - - $schriftgroesse = $this->getStyleElement('schriftgroesse'); - if($schriftgroesse>0) - $this->SetFont($this->GetFont(),'',$schriftgroesse); - - if($this->recipient['anrede']!="" && $this->getStyleElement('typimdokument')) - { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['anrede'],0,1); - } - - $this->SetMargins($this->getStyleElement("abstand_adresszeilelinks"),50); - if($this->recipient['enterprise']) { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $charlimit=40; - if(strlen($this->recipient['enterprise'])>$charlimit + 15) - { - $array = explode( "\n", wordwrap($this->recipient['enterprise'], $charlimit)); - foreach($array as $row) - { - $this->Cell(80,5,$this->app->erp->ReadyForPDF($row),0,1); - } - } else { - $this->Cell(80,5,$this->app->erp->ReadyForPDF($this->recipient['enterprise']),0,1); - } - - } - - - if($this->recipient['firstname']!="") - { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['firstname'],0,1); - } - - if($this->recipient['address2']!="") { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['address2'],0,1); - } - - if($this->recipient['address3']!="") - { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['address3'],0,1); - } - - if($this->recipient['address4']!="") - { - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['address4'],0,1); - } - - - //$this->Cell(80,5,$this->recipient['firstname']." ".$this->recipient['familyname'],0,1); - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,$this->recipient['address1'],0,1); - - - $this->SetFont($this->GetFont(),'',10); - if($schriftgroesse>0) - $this->SetFont($this->GetFont(),'',$schriftgroesse); - - - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $inland = $this->getStyleElement("land"); - if($this->recipient['country']!=$inland) - { - //$this->Cell(80,5,$this->recipient['country']."-".$this->recipient['areacode']." ".$this->recipient['city'],0,1); - - if(function_exists('mb_strtoupper')) - $this->Cell(80,5,mb_strtoupper($this->recipient['areacode']." ".$this->recipient['city'],"UTF-8"),0,1); - else - $this->Cell(80,5,strtoupper($this->recipient['areacode']." ".$this->recipient['city']),0,1); - - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - $this->Cell(80,5,strtoupper($this->app->erp->UmlauteEntfernen($this->app->GetLandLang($this->recipient['country'],$this->sprache))),0,1); - - } - else { - $this->Cell(80,5,$this->recipient['areacode']." ".$this->recipient['city'],0,1); - } - //$this->SetFont($this->GetFont(),'',9); - //if(isset($this->recipient['country'])) $this->Cell(80,5,$this->recipient['country'],0,1); - - - //FREITEXT1 - $freitext1aktiv = $this->getStyleElement('freitext1aktiv'); - if($freitext1aktiv){ - $freitext1inhalt = $this->app->erp->Beschriftung("freitext1inhalt"); - if($freitext1inhalt=="") $freitext1inhalt = $this->getStyleElement('freitext1inhalt'); - - $freitext1inhalt = $this->app->erp->ParseUserVars($this->table,$this->id,$freitext1inhalt); - $freitext1inhalt = $this->app->erp->ReadyForPDF($freitext1inhalt); - $freitext1schriftgroesse = $this->getStyleElement('freitext1schriftgroesse'); - $freitext1y = $this->getStyleElement('freitext1y'); - $freitext1x = $this->getStyleElement('freitext1x'); - $freitext1breite = $this->getStyleElement('freitext1breite'); - $this->SetFont($this->GetFont(),'',$freitext1schriftgroesse); - $this->SetY($freitext1y); - $this->SetX($freitext1x); - $this->MultiCell($freitext1breite, 5, $this->WriteHTML($freitext1inhalt), 0, 'L'); - } - - - //FREITEXT2 - $freitext2aktiv = $this->getStyleElement('freitext2aktiv'); - if($freitext2aktiv){ - $freitext2inhalt = $this->app->erp->Beschriftung("freitext2inhalt"); - if($freitext2inhalt=="") $freitext1inhalt = $this->getStyleElement('freitext2inhalt'); - - $freitext2inhalt = $this->app->erp->ParseUserVars($this->table,$this->id,$freitext2inhalt); - $freitext2inhalt = $this->app->erp->ReadyForPDF($freitext2inhalt); - $freitext2schriftgroesse = $this->getStyleElement('freitext2schriftgroesse'); - $freitext2y = $this->getStyleElement('freitext2y'); - $freitext2x = $this->getStyleElement('freitext2x'); - $freitext2breite = $this->getStyleElement('freitext2breite'); - $this->SetFont($this->GetFont(),'',$freitext2schriftgroesse); - $this->SetY($freitext2y); - $this->SetX($freitext2x); - $this->MultiCell($freitext2breite, 5, $this->WriteHTML($freitext2inhalt), 0, 'L'); - } - - - $this->SetMargins($this->getStyleElement("abstand_seitenrandlinks"),50,$this->getStyleElement("abstand_seitenrandrechts")); - } - - public function setAbsender($sender) - { - $this->absender = $sender; - - } - - public function renderSender() { - $monthlu = array("", "Januar", "Februar", "M�rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"); - $monthnom = date("n"); - $month = $monthlu[$monthnom]; - $date = date("j").". ".$month." ".date("Y"); - - - if($this->nichtsichtbar_zeileabsender!=true) - { - - //abstand_adresszeileoben - // line above address field - $absender = (($this->absender!='') ? $this->absender : $this->getStyleElement('absender')); - $schriftgroesse = $this->getStyleElement('schriftgroesseabsender'); - $this->SetY(43+$this->abstand_adresszeileoben); - $this->SetFont($this->GetFont(),'',$schriftgroesse); - //$cellStr = $this->sender['enterprise']." � ".$this->sender['address1']." � ".$this->sender['areacode']." ".$this->sender['city']; - $cellStr = $this->app->erp->ReadyForPDF($absender); - - $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); - - if($this->getStyleElement("absenderunterstrichen")=="1") - $this->Cell($this->GetStringWidth($cellStr)+2,5,$cellStr,'B'); - else - $this->Cell($this->GetStringWidth($cellStr)+2,5,$cellStr,''); - } - - if($this->nichtsichtbar_rechtsoben!=true) - { - // detailed sender data - $lineHeight = 4; - $xOffset = 131; - $absatz = 3; - - $this->SetXY($xOffset,10); - $this->SetFont($this->GetFont(),'',9); - $this->Cell(30,$lineHeight,"Name der Gesellschaft: ",0,0,'R'); - $this->SetFont($this->GetFont(),'B',9); - $this->Cell(60,$lineHeight,$this->sender['enterprise'],0,2); - if(isset($this->sender['enterprise2'])) - $this->Cell(60,$lineHeight,$this->sender['enterprise2'],0,2); - - $this->SetXY($xOffset,$this->GetY()); - $this->SetFont($this->GetFont(),'',9); - $this->Cell(30,$lineHeight,"Sitz der Gesellschaft: ",0,0,'R'); - $this->SetFont($this->GetFont(),'B',9); - $this->Cell(60,$lineHeight,$this->sender['address1'],0,2); - if(isset($this->sender['address2'])) - $this->Cell(60,$lineHeight,$this->sender['address2'],0,2); - $this->Cell(60,$lineHeight,$this->sender['areacode']." ".$this->sender['city'],0,2); - - $this->SetXY($xOffset,$this->GetY()+$absatz); //abstand - $this->SetFont($this->GetFont(),'',9); - if(isset($this->sender['phone1'])) { - $this->Cell(30,$lineHeight,"Fon: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['phone1'],0,2); - } - - if(isset($this->sender['fax'])) { - $this->SetXY($xOffset,$this->GetY()); - $this->Cell(30,$lineHeight,"Fax: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['fax'],0,2); - } - - - $this->SetXY($xOffset, $this->GetY()+$absatz); //abstand - if(isset($this->sender['email'])) { - $this->Cell(30,$lineHeight,"Mail: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['email'],0,2); - } - - if(isset($this->sender['web'])) { - $this->SetXY($xOffset,$this->GetY()); - $this->Cell(30,$lineHeight,"Web: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['web'],0,2); - } - - $this->SetXY($xOffset, $this->GetY()+$absatz); //abstand - if(isset($this->sender['ustid'])) { - $this->Cell(30,$lineHeight,"UST-ID: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['ustid'],0,2); - } - if(isset($this->sender['taxnr'])) { - $this->SetXY($xOffset,$this->GetY()); - $this->Cell(30,$lineHeight,"Steuer-Nr.: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['taxnr'],0,2); - } - if(isset($this->sender['hreg'])) { - $this->SetXY($xOffset,$this->GetY()); - $this->Cell(30,$lineHeight,"Handelsregister: ",0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['hreg'],0,2); - } - - $this->SetXY($xOffset,$this->GetY()); - $this->Cell(30,$lineHeight,utf8_encode("Gesch�ftsf�hrung: "),0,0,'R'); - $this->Cell(60,$lineHeight,$this->sender['firstname'].' '.$this->sender['familyname'],0,2); - - //$this->SetXY($xOffset, $this->GetY()+$absatz+2); //abstand - //$this->Cell(30,$lineHeight,"Datum: ",0,0,'R'); - //$this->Cell(60,$lineHeight,utf8_encode($date),0,2); - } - } - - - // kundennummer rechnungsnummer und datum - public function renderCorrDetails() { - - $breite_spalte_rechts = 30; - - $recht_links_verschieben = $this->abstand_boxrechtsoben_lr; - - $startpos_links_rechts = -83 + $recht_links_verschieben; - - $boldTitleStr = $boldValueStr = $titleStr = $valueStr = ""; - $italicTitleStr = $italicValueStr = ''; - $italicBoldTitleStr = $italicBoldValueStr = ''; - if(isset($this->boldCorrDetails)){ - foreach($this->boldCorrDetails as $title => $value) { - $boldTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; - $boldValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; - } - } - if(!empty($this->italicCorrDetails)) { - foreach($this->italicCorrDetails as $title => $value) { - $italicTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; - $italicValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; - } - } - - if(!empty($this->italicBoldCorrDetails)) { - foreach($this->italicBoldCorrDetails as $title => $value) { - $italicBoldTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; - $italicBoldValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; - } - } - - if(isset($this->corrDetails)){ - foreach($this->corrDetails as $title => $value) { - if($value!="") - { - $titleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; - $valueStr .= $this->app->erp->ReadyForPDF($value)."\n"; - } - } - } - - if($this->boxausrichtung=="") $this->boxausrichtung="R"; - - $pos = strpos($this->boxausrichtung, ';'); - if($pos > 0) - { - $tmp_box = explode(";",$this->boxausrichtung); - $this->boxausrichtung = $tmp_box[0]; - $this->box_breite1 = $tmp_box[1]; - $this->box_breite2 = $tmp_box[2]; - } - if($this->box_breite1=="") $this->box_breite1=34; - if($this->box_breite2=="") $this->box_breite2=38; - - - $fontinfobox = $this->getStyleElement("infobox"); - - if($italicBoldTitleStr != '') { - $this->SetFont($this->GetFont(),'BI',$fontinfobox); - $this->SetXY($startpos_links_rechts,80); - $this->MultiCell($this->box_breite1,4,$italicBoldTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft): $this->boxausrichtung); //TL - $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); - $this->MultiCell($this->box_breite2,4,$italicBoldValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR - } - elseif($italicTitleStr != '') { - $this->SetFont($this->GetFont(),'I',$fontinfobox); - $this->SetXY($startpos_links_rechts,80); - $this->MultiCell($this->box_breite1,4,$italicTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL - $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); - $this->MultiCell($this->box_breite2,4,$italicValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); - } - elseif($boldTitleStr!='') { - $this->SetFont($this->GetFont(),'B',$fontinfobox); - $this->SetXY($startpos_links_rechts,80); - $this->MultiCell($this->box_breite1,4,$boldTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL - $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); - $this->MultiCell($this->box_breite2,4,$boldValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR - } - else { - $this->SetXY($startpos_links_rechts,80+$this->abstand_boxrechtsoben); - $this->MultiCell($this->box_breite1,0,'','',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL - $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80+$this->abstand_boxrechtsoben); - $this->MultiCell($this->box_breite2,0,'','',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR - } - - $this->SetY(80); - $this->SetY($this->GetY()+$this->abstand_boxrechtsoben); - - $this->SetFont($this->GetFont(),'',$fontinfobox); - $tempY = $this->GetY(); - $this->SetX($startpos_links_rechts); - $this->MultiCell($this->box_breite1,4,$titleStr,"",$this->boxausrichtung); //BL - $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,$tempY); - $this->MultiCell($this->box_breitexi21,4,$valueStr,"",$this->boxausrichtung); //BR - - $this->SetY(80+$this->abstand_artikeltabelleoben); //Hoehe Box - //$this->SetY(60);//+$this->abstand_artikeltabelleoben); //Hoehe Box - } - - - public function renderDoctype() { - //$this->Ln(1); - - if($this->doctype=="brief") - $betreffszeile = $this->getStyleElement('betreffszeile'); - else - $betreffszeile = $this->getStyleElement('betreffszeile'); - - $this->SetY(80);//+$this->abstand_artikeltabelleoben); //Hoehe Box - //$this->SetY(80+$this->abstand_artikeltabelleoben); //Hoehe Box - - $this->SetFont($this->GetFont(),'B',$betreffszeile); - $this->SetY($this->GetY()+$this->abstand_betreffzeileoben); - //$this->Cell(85,6,$this->doctypeOrig); - $this->MultiCell(210-83+$this->abstand_boxrechtsoben_lr-$this->getStyleElement("abstand_seitenrandlinks")-5,6,html_entity_decode($this->doctypeOrig,ENT_QUOTES),0,'L'); - $this->SetY($this->GetY()-$this->abstand_betreffzeileoben); - - //$this->SetY($this->GetY()+$this->abstand_betreffzeileoben); - $this->SetY($this->GetY()+$this->abstand_artikeltabelleoben); //Hoehe Box - } - - public function renderText() { - - if(isset($this->textDetails['body'])) { - if($this->doctype=="brief") - $dokumententext = $this->getStyleElement('dokumententext'); - else - $dokumententext = $this->getStyleElement('dokumententext'); - $this->SetFont($this->GetFont(),'',$dokumententext); - //if($this->doctype!="brief") - $this->Ln(11); - - $this->textDetails['body'] = $this->app->erp->ParseUserVars($this->table,$this->id,$this->textDetails['body']); - - if($this->getStyleElement("briefhtml")=="1") - { - $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($this->textDetails['body'])); - $this->MultiCell(180,4,$this->WriteHTML($html)); - } else { - $this->MultiCell(180,4,$this->app->erp->ReadyForPDF($this->textDetails['body'])); - } - } - } - - public function renderFooter() { - - $this->app->erp->RunHook('briefpapier_render_footer_hook1', 1, $this); - - if(isset($this->textDetails['footer'])) { - $freitext = $this->getStyleElement('freitext'); - - if($this->getStyleElement("kleinunternehmer")) - { - if($this->textDetails['footer']=="") $this->textDetails['footer'] ="Als Kleinunternehmer im Sinne von §19 Abs.1 UStG wird Umsatzsteuer nicht berechnet!"; - else $this->textDetails['footer'] .="\r\nAls Kleinunternehmer im Sinne von § 19 Abs. 1 UStG wird Umsatzsteuer nicht berechnet!"; - } - - $this->textDetails['footer'] = $this->app->erp->ParseUserVars($this->table,$this->id,$this->textDetails['footer']); - - $this->SetFont($this->GetFont(),'',$freitext); - // $this->Ln(); - $y = $this->GetY(); - - // if($this->doctype!="lieferschein") - // $this->SetY($y-5); - //$parsed = $this->app->erp->ReadyForPDF($this->textDetails['footer']); - if($this->getStyleElement("briefhtml")=="1") - { - $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($this->textDetails['footer'])); - $this->MultiCell(180,4,$this->WriteHTML($html)); - } else { - $this->MultiCell(180,4,$this->app->erp->ReadyForPDF($this->textDetails['footer'])); - } - } - - $this->app->erp->RunHook('briefpapier_render_footer_hook2', 1, $this); - } - - public function CalcPosString($posstr, $oldpostr, $hauptnummer, $oldlvl, $newlvl) - { - if($oldpostr == 0) - { - if($hauptnummer) - { - return $hauptnummer.'.1'; - } - return '1'; - } - if($newlvl > $oldlvl) - { - return $oldpostr.str_repeat('.1', $newlvl - $oldlvl); - } - $oldpostra = explode('.', $oldpostr); - - $diff = $oldlvl - $newlvl; - $length = count($oldpostra); - if($hauptnummer && $hauptnummer != $oldpostra[0]){ - return (String)((int)$oldpostra[0]+1).'.1'; - } - - $ret = ''; - if($diff >= $length -1) - { - return (String)((int)$oldpostra[0]+1); - } - for($i = 0; $i < $length - 1 - $diff; $i++) - { - $ret .= $oldpostra[$i].'.'; - } - - return $ret.(String)((int)$oldpostra[$length - 1 - $diff]+1); - } - - /** - * @param string $type - * @param int $orderId - * @param int $orderPositionId - * @param string $doctype - * - * @return string - */ - public function getDeliveryNoteBestBeforeBatchSnFromOrder($type, $orderId, $orderPositionId, $doctype = 'auftrag') - { - if($doctype === 'rechnung') { - $orderPositionId = $this->app->DB->Select( - sprintf( - 'SELECT auftrag_position_id FROM rechnung_position WHERE id = %d', - $orderPositionId - ) - ); - if($orderPositionId <= 0) { - return ''; - } - } - - $position = $this->app->DB->SelectRow( - sprintf( - 'SELECT id, lieferschein - FROM lieferschein_position - WHERE auftrag_position_id = %d AND auftrag_position_id > 0 - LIMIT 1', - $orderPositionId - ) - ); - - if(empty($position)) { - return ''; - } - if($type === 'mhd') { - $this->mhd['lieferschein'][$position['lieferschein']][$position['id']] = - $this->GetChargeMHDSNString('mhd', 'lieferschein', $position['lieferschein'], $position['id']); - return $this->mhd['lieferschein'][$position['lieferschein']][$position['id']]; - } - if($type === 'charge') { - $this->charge['lieferschein'][$position['lieferschein']][$position['id']] = - $this->GetChargeMHDSNString('charge', 'lieferschein', $position['lieferschein'], $position['id']); - return $this->charge['lieferschein'][$position['lieferschein']][$position['id']]; - } - if($type === 'sn') { - $this->sn['lieferschein'][$position['lieferschein']][$position['id']] = - $this->GetChargeMHDSNString('sn', 'lieferschein', $position['lieferschein'], $position['id']); - return $this->sn['lieferschein'][$position['lieferschein']][$position['id']]; - } - - return ''; - } - - /** - * @param string $text - * @param string $doctype - * @param int $doctypeId - * @param int $positionId - * - * @return string - */ - public function parseBestBeforeBatchSn($text, $doctype, $doctypeId, $positionId){ - if(strpos($text, '{MHD}') !== false) { - $entry = !empty($this->mhd[$doctype]) && !empty($this->mhd[$doctype][$doctypeId]) - && !empty($this->mhd[$doctype][$doctypeId][$positionId])? - $this->mhd[$doctype][$doctypeId][$positionId]:''; - if($entry === '') { - $this->mhd[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( - 'mhd',$doctype,$doctypeId,$positionId, true - ); - $entry = $this->mhd[$doctype][$doctypeId][$positionId]; - if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { - $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('mhd', $doctypeId, $positionId, $doctype); - } - } - - $text = str_replace('{MHD}', $entry, $text); - } - if(strpos($text, '{CHARGE}') !== false) { - $entry = !empty($this->charge[$doctype]) && !empty($this->charge[$doctype][$doctypeId]) - && !empty($this->charge[$doctype][$doctypeId][$positionId])? - $this->charge[$doctype][$doctypeId][$positionId]:''; - if($entry === '') { - $this->charge[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( - 'charge',$doctype,$doctypeId,$positionId, true - ); - $entry = $this->charge[$doctype][$doctypeId][$positionId]; - if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { - $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('charge', $doctypeId, $positionId, $doctype); - } - } - $text = str_replace('{CHARGE}', $entry, $text); - } - if(strpos($text, '{SN}') !== false) { - $entry = !empty($this->sn[$doctype]) && !empty($this->sn[$doctype][$doctypeId]) - && !empty($this->sn[$doctype][$doctypeId][$positionId])? - $this->sn[$doctype][$doctypeId][$positionId]:''; - if($entry === '') { - $this->sn[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( - 'sn',$doctype,$doctypeId,$positionId, true - ); - $entry = $this->sn[$doctype][$doctypeId][$positionId]; - if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { - $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('sn', $doctypeId, $positionId, $doctype); - } - } - $text = str_replace('{SN}', $entry, $text); - } - - return $text; - } - - public function renderItems() { - - $this->app->erp->RunHook('briefpapier_renderitems',1, $this); - // if($this->bestellungohnepreis) $this->doctype="lieferschein"; - $posWidth = $this->getStyleElement("breite_position"); - $amWidth = $this->getStyleElement("breite_menge"); - $itemNoWidth = $this->getStyleElement("breite_nummer"); - $einheitWidth = $this->getStyleElement("breite_einheit"); - $descWidth = $this->getStyleElement("breite_artikel"); - $taxWidth = $this->getStyleElement("breite_steuer"); - $belege_subpositionen = $this->getStyleElement("belege_subpositionen"); - $belege_subpositionenstuecklisten = $this->getStyleElement('belege_subpositionenstuecklisten') && in_array(($this->table?$this->table:$this->doctype),array('rechnung', 'auftrag','lieferschein','gutschrift','angebot')); - $belege_stuecklisteneinrueckenmm = $this->getStyleElement('belege_stuecklisteneinrueckenmm'); - $doctype = $this->table?$this->table:$this->doctype; - $doctypeId = $this->id; - $docArr = $this->app->DB->SelectRow( - sprintf( - 'SELECT projekt,adresse,steuersatz_normal,steuersatz_ermaessigt FROM `%s` WHERE id = %d', - $doctype, $doctypeId - ) - ); - $query = sprintf("SELECT `sprache` FROM `%s` - WHERE `id` = %d - LIMIT 1", - $doctype, $doctypeId); - $documentLanguage = $this->app->DB->Select($query); - if(!empty($docArr)) { - $projekt = $docArr['projekt']; - $adresse = $docArr['adresse']; - } - else{ - $projekt = $this->app->DB->Select("SELECT projekt FROM " . ($this->table ? $this->table : $this->doctype) . " WHERE id = '" . $this->id . "' LIMIT 1"); - $adresse = $this->app->DB->Select("SELECT adresse FROM " . ($this->table ? $this->table : $this->doctype) . " WHERE id = '" . $this->id . "' LIMIT 1"); - } - $inventurohnepreis = null; - if(!in_array($this->table ? $this->table : $this->doctype, ['rechnung','auftrag','angebot','bestellung'])) { - $inventurohnepreis = $this->app->DB->Select( - sprintf( - 'SELECT noprice - FROM `%s` - WHERE id = %d - LIMIT 1', - $this->table ? $this->table : $this->doctype, $this->id - ) - ); - } - if($inventurohnepreis){ - $descWidth += 40; - } - - if($this->doctype=="arbeitsnachweis") - { - $itemNoWidth = 20; - $taxWidth = 40; - $descWidth = 95; - } - - if($this->rabatt=='1') { - $descWidth -= 15; - } - $priceWidth = 20; - $sumWidth = 20; - $rabattWidth = 15; - // $lineLength = $amWidth + $itemNoWidth + $descWidth + $taxWidth + $priceWidth + $sumWidth; - - // zwischenloesung um platz zu sparen - if($this->ust_spalteausblende) - { - $taxWidth--; - $descWidth += $taxWidth; - $taxWidth= 1; - } - - $cellhoehe = 5; - - // render table header - if(isset($this->textDetails['body'])) { - $this->Ln(); - } - else { - $this->Ln(8); - } - $tabellenbeschriftung = $this->getStyleElement('tabellenbeschriftung'); - - $this->SetX($this->getStyleElement('abstand_seitenrandlinks')+1); // eventuell einstellbar per GUI - - $this->SetFont($this->GetFont(),'B',$tabellenbeschriftung); - $this->Cell($posWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_position'),0,0,'C')); - if($this->doctype!='arbeitsnachweis') - { - if($this->doctype=='zahlungsavis') - { - $this->Cell($itemNoWidth,6,'Nummer'); - $this->Cell($descWidth-$einheitWidth+$taxWidth+$priceWidth+$rabattWidth,6,'Beleg'); - - $this->Cell($amWidth,6,'',0,0,'R'); - } - else { - $this->Cell($itemNoWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikelnummer'))); - if($this->getStyleElement('artikeleinheit')=='1'){ - $this->Cell($descWidth - $einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikel'))); - } - else{ - $this->Cell($descWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikel'))); - } - $this->Cell($amWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_menge')),0,0,'R'); - } - } else { - $this->Cell($taxWidth,6,'Mitarbeiter'); - $this->Cell($itemNoWidth,6,'Ort'); - $this->Cell($descWidth,6,'Tätigkeit'); - $this->Cell($amWidth,6,'Stunden',0,0,'R'); - } - - if($this->doctype!='lieferschein' && $this->doctype!='arbeitsnachweis' && $this->doctype!='produktion' && $this->doctype!='zahlungsavis' && $this->doctype!='preisanfrage'){ - if($this->getStyleElement('artikeleinheit')=='1'){ - $this->Cell($einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einheit')), 0, 0, 'R'); - } - - if($this->ust_spalteausblende){ - $this->Cell($taxWidth, 6, '', 0, 0, 'R'); - } - else{ - $this->Cell($taxWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_mwst')), 0, 0, 'R'); - } - - if($this->getStyleElement('artikeleinheit')=='1'){ - if(!$inventurohnepreis){ - $this->Cell($priceWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einzel')), 0, 0, 'R'); - } - } - else{ - if(!$inventurohnepreis){ - $this->Cell($priceWidth, 6, $this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_stueck'))), 0, 0, 'R'); - } - } - - if($this->rabatt=='1') { - if(!$inventurohnepreis){ - $this->Cell($rabattWidth,6,$this->app->erp->Beschriftung('dokument_rabatt'),0,0,'R'); - $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); - } - } else { - if(!$inventurohnepreis){ - $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); - } - } - } - else if ($this->doctype=='lieferschein' || $this->doctype=='preisanfrage') - { - if($this->getStyleElement("artikeleinheit")=='1'){ - $this->Cell($einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einheit')), 0, 0, 'R'); - } - } - else if ($this->doctype=='zahlungsavis') - { - $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); - } - - $this->Ln(); - $this->Line($this->getStyleElement('abstand_seitenrandlinks')+1, $this->GetY(), 210-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); - $this->Ln(2); - - // render table body - $tabelleninhalt = $this->getStyleElement('tabelleninhalt'); - - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - $topos = 0; - if(is_array($this->items))$topos = count($this->items); - $zwischenpositionen = $this->app->DB->Select("SELECT count(distinct pos) FROM beleg_zwischenpositionen WHERE doctype='".$this->doctype."' AND doctypeid='".$this->doctypeid."' AND pos >= 0 AND pos <'$topos' AND (postype = 'gruppe' OR postype = 'zwischensumme' OR postype = 'gruppensumme' OR postype = 'gruppensummemitoptionalenpreisen') ORDER by sort"); - if($zwischenpositionen < 1)$belege_subpositionen = false; - $hauptnummer = 0; - $posoffset = 0; - if($belege_subpositionen)$hauptnummer = 1; - $oldlvl = 0; - $oldpostr = 0; - $langeartikelnummern = ($this->getStyleElement('langeartikelnummern')?true:false); - if($this->doctype==='bestellung') { - $langeartikelnummern = $this->app->DB->Select("SELECT langeartikelnummern FROM bestellung WHERE id='".$this->doctypeid."' LIMIT 1")?true:false; - } - $pos=0; - $umsatzsteuerermaessigtProzent = !empty($docArr)?$docArr['steuersatz_ermaessigt']: $this->app->erp->GetSteuersatzErmaessigt(false,!empty($this->id)?$this->id:$this->doctypeid,$this->table); - $umsatzsteuernormalProzent = !empty($docArr)?$docArr['steuersatz_normal']:$this->app->erp->GetSteuersatzNormal(false,!empty($this->id)?$this->id:$this->doctypeid,$this->table); - - $umsatzsteuerermaessigt = (1+$umsatzsteuerermaessigtProzent/100); - $umsatzsteuernormal = (1+$umsatzsteuernormalProzent/100); - - $jitposfix = 0; //Die Anzahl der der Unterartikel des vorherigen Stücklistenartikels - $jitposfixbase = 0; //Die Gesamtzahl der bisher ausgeblendeten Stücklistenartikel - $anzeigeBelegNettoAdrese = $this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id); - $docRow = $this->app->DB->SelectRow( - sprintf( - 'SELECT * FROM `%s` WHERE id = %d', $this->doctype, $this->id - ) - ); - foreach($this->items as $item){ - $this->SetTextColor(0,0,0); - for ($l=$pos; $l <= $pos+$jitposfix ; $l++) { - //Arbeitet die Zwischenpositionen durch falls der vorherige Artikel ein Stücklistenartikel war bei dem Teile ausgeblendet wurden - $iszwichenpos = $this->DrawZwischenpositionen($l+$jitposfixbase); - } - $jitposfixbase += $jitposfix; - if($item['keineeinzelartikelanzeigen'] == 1){ - $jitposfix = $item['anzahlunterartikel']; - }else{ - $jitposfix = 0; - } - $item['name'] = ($langeartikelnummern?"\r\n\r\n":'').$this->app->erp->ReadyForPDF($item['name']); - $item['desc'] = $this->app->erp->ReadyForPDF($item['desc']); - $item['itemno'] = $this->app->erp->ReadyForPDF($item['itemno']); - $item['herstellernummer'] = $this->app->erp->ReadyForPDF($item['herstellernummer']); - $item['artikelnummerkunde'] = $this->app->erp->ReadyForPDF($item['artikelnummerkunde']); - $item['lieferdatum'] = $this->app->erp->ReadyForPDF($item['lieferdatum']); - $item['hersteller'] = $this->app->erp->ReadyForPDF($item['hersteller']); - - //TODO Soll einstellbar werden: Zeilenabstand in Tabelle normal mittel - $cellhoehe = 3; - //position - - if($iszwichenpos && $belege_subpositionen && $pos > $posoffset) - { - $hauptnummer++; - $posoffset = $pos; - } - if(isset($item['posausblenden']) && $item['posausblenden']){ - $posstr = ''; - }else{ - $pos++; - $posstr = $pos; - } - - if($belege_subpositionen && $hauptnummer) - { - $posstr = $hauptnummer.'.'.($pos-$posoffset); - } - $newlvl = isset($item['lvl'])?(int)$item['lvl']:0; - - - $itemNoWidthold = $itemNoWidth; - $posWidthold = $posWidth; - if($belege_stuecklisteneinrueckenmm && $newlvl > 0) - { - $this->Cell($belege_stuecklisteneinrueckenmm * $newlvl,$cellhoehe,''); - $posWidth -= $belege_stuecklisteneinrueckenmm * $newlvl; - if($posWidth < 2* strlen($posstr)) - { - $diff = 2* strlen($posstr) - $posWidth; - $posWidth += $diff; - $itemNoWidth -= $diff; - } - } - if($belege_subpositionenstuecklisten)$posstr = $this->CalcPosString($posstr,$oldpostr, $hauptnummer, $oldlvl, $newlvl); - $oldpostr = $posstr; - $oldlvl = isset($item['lvl'])?(int)$item['lvl']:0; - $this->Cell($posWidth,$cellhoehe,$posstr,0,0,$belege_stuecklisteneinrueckenmm?'':'C'); - //artikelnummer - if($this->doctype==='arbeitsnachweis') - { - $this->Cell($taxWidth,$cellhoehe,trim($item['person']),0); - - $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); - $this->SetFont($this->GetFont(),'',$zeilenuntertext); - - // ort - $tmpy = $this->GetY(); - $tmpx = $this->GetX(); - $this->MultiCell($itemNoWidth,($zeilenuntertext/2),trim($item['itemno']),0); // 4 = abstand - $tmpy2 = $this->GetY(); - $this->SetXY($tmpx+$itemNoWidth,$tmpy); - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - } - else { - //TODO BENE - if($this->doctype==='lieferschein' && $this->getStyleElement('modul_verband')=='1'){ - $this->SetFont($this->GetFont(), '', $tabelleninhalt + 3); - }else{ - $this->SetFont($this->GetFont(), '', $tabelleninhalt); - } - if(isset($item['itemno'])) { - $this->Cell($itemNoWidth,$cellhoehe,$item['itemno'],0); - } - else { - $this->Cell($itemNoWidth); - } - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - } - - $position_x = $this->GetX(); - $position_y = $this->GetY(); - -// start am Ende der Zeile Zeichnen - $this->SetAutoPageBreak(false,$this->getStyleElement("abstand_umbruchunten")); //2306BS - // Artikel Name - if($item['tax']!=='hidden' && $newlvl == 0){ - $this->SetFont($this->GetFont(), 'B', $tabelleninhalt); - } - if($item['tax'] === 'hidden' && $item['ohnepreis'] == 2 && $newlvl == 0){ - $this->SetFont($this->GetFont(), 'B', $tabelleninhalt); - } - if($this->getStyleElement("artikeleinheit")=='1'){ - $this->MultiCell($descWidth - $einheitWidth, $cellhoehe, $item['name'], 0, 'L', false); - } - else{ - $this->MultiCell($descWidth, $cellhoehe, $item['name'], 0, 'L', false); - } - - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - $this->SetAutoPageBreak(true,$this->getStyleElement('abstand_umbruchunten')); //2306BS - - $position_y_end_name = $this->GetY(); -// - - // wenn vorhanden Artikel Einheit - - - if($this->getStyleElement('artikeleinheit')=='1'){ - $this->SetXY(($position_x + $descWidth - $einheitWidth), $position_y); - } - else{ - $this->SetXY(($position_x + $descWidth), $position_y); - } - - - if($this->doctype==='arbeitsnachweis'){ - $this->SetXY(($position_x + $descWidth), $position_y); - } - - - // Menge - - if($this->doctype==='zahlungsavis'){ - $this->Cell($amWidth, $cellhoehe, '', 0, 0, 'R'); - } - else{ - $this->Cell($amWidth, $cellhoehe, $item['amount'], 0, 0, 'R'); - } - - if($this->doctype!=='lieferschein' && $this->doctype!=='arbeitsnachweis' && $this->doctype!=='produktion' && $this->doctype!=='preisanfrage') { - if($this->getStyleElement('artikeleinheit')=='1') - { - if($item['unit']!='') - $einheit = $item['unit']; - else { - if(!empty($item['artikel'])) - { - $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE - id='".$item['artikel']."' LIMIT 1"); - }else{ - $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE - nummer='".$item['itemno']."' LIMIT 1"); - } - if($einheit=='') { - $einheit = $this->getStyleElement('artikeleinheit_standard'); - } - } - if(!empty($einheit) && !empty($documentLanguage)){ - $query = sprintf("SELECT ae.id FROM `artikeleinheit` AS `ae` - WHERE ae.einheit_de = '%s'", - $this->app->DB->real_escape_string($einheit)); - $unitId = $this->app->DB->Select($query); - if(!empty($unitId)){ - $query = sprintf("SELECT u.beschriftung FROM `uebersetzung` AS `u` - WHERE u.sprache = '%s' AND u.label='%s'", - $documentLanguage,'artikeleinheit_'.$unitId); - $unitTranslation = $this->app->DB->Select($query); - if(!empty($unitTranslation)){ - $einheit = $unitTranslation; - } - } - } - - $this->Cell($einheitWidth,$cellhoehe,$this->app->erp->ReadyForPDF($einheit),0,0,'R'); - } - - // if($item['tax']=="hidden") $item['tax']=="hidden"; - if($item['tax']!=='hidden') - { - if($this->ust_befreit>0) { - $item['tax'] = 0; - } else { - if($item['tax'] === 'normal') { - $item['tax'] = $umsatzsteuernormal - 1; - } - else { - $item['tax'] = $umsatzsteuerermaessigt - 1; - } - } - if(isset($item['steuersatz'])){ - $item['tax'] = $item['steuersatz'] / 100; - } - } - - - // wenn steuerfrei komplett immer 0 steuer anzeigen - $item['tmptax'] = $item['tax'] + 1; - - // standard anzeige mit steuer - if(!$this->ust_spalteausblende){ - if($item['tax']==='hidden'){ - $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); - } else { - $tax = $item['tax']; //= $tax; //="USTV"?0.19:0.07; - $tax *= 100; $tax = $tax.'%'; - - if($this->doctype==='zahlungsavis'){ - $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); - } - else{ - $this->Cell($taxWidth, $cellhoehe, $item['ohnepreis'] ? '' : $tax, 0, 0, 'R'); - } - } - } else { - //kleinunternehmer - $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); - } - - if($this->doctype!=='lieferschein' && $this->doctype!=='produktion' && $this->doctype!=='preisanfrage') { - // preis pro Artikel - - if($this->doctype!=='zahlungsavis') - { - if($item['tax']!=='hidden'){ - - if($anzeigeBelegNettoAdrese){ - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - //&& $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - if(!$inventurohnepreis){ - $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price']), 0, 0, 'R'); - } - } - else{ - if(!$inventurohnepreis){ - $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price'] * $item['tmptax']), 0, 0, 'R'); - } - } - } else - { - if($item['ohnepreis']==2) { - if(!$inventurohnepreis){ - $this->Cell($priceWidth,$cellhoehe,$item['price'],0,0,'R'); - } - } // text alternativ zu preis - else { - if(!$inventurohnepreis){ - $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['price']),0,0,'R'); - } - } - } - } else { - $this->Cell($priceWidth,$cellhoehe,"",0,0,'R'); - } - - // zentale rabatt spalte - if($this->rabatt=='1') { - $rabatt_string=''; - - //rabatt - if($item['grundrabatt'] > 0 || $item['rabatt1'] > 0 || $item['rabatt2'] > 0) - { - if($item['grundrabatt']>0) { - $rabatt_string .= $item['grundrabatt']." %\r\n"; - } - if($item['rabatt1']>0) { - $rabatt_string .= $item['rabatt1']." %\r\n"; - } - if($item['rabatt2']>0) { - $rabatt_string .= $item['rabatt2']." %\r\n"; - } - if($item['rabatt3']>0) { - $rabatt_string .= $item['rabatt3']." %\r\n"; - } - if($item['rabatt4']>0) { - $rabatt_string .= $item['rabatt4']." %\r\n"; - } - if($item['rabatt5']>0) { - $rabatt_string .= $item['rabatt5']." %\r\n"; - } - - - $tmpy = $this->GetY(); - $tmpx = $this->GetX(); - - if($item['keinrabatterlaubt']=='1' || $item['rabatt']<=0 || $item['rabatt']==='') { - $rabatt_or_porto = $this->app->DB->Select("SELECT id FROM artikel WHERE - nummer='".$item['itemno']."' AND (porto='1' OR rabatt='1') LIMIT 1"); - if($rabatt_or_porto) - $rabatt_string=''; - else { - if($this->getStyleElement('modul_verband')=='1') { - $rabatt_string='SNP'; - } - else { - $rabatt_string=''; - } - } - if($item['keinrabatterlaubt']=='1' && $item['rabatt']<>0){ - $rabatt_string = $item['rabatt'] . " %\r\n"; - } - } - - // rabatt nur klein anzeigen wenn es mehr als einer ist - if(strstr(trim($rabatt_string), PHP_EOL)) { - $this->SetFont($this->GetFont(),'',6); - } - - if($item['tax']!=='hidden'){ - $this->MultiCell($rabattWidth, $cellhoehe - 1, $rabatt_string, 0, 0); - } - else{ - $this->MultiCell($rabattWidth, $cellhoehe - 1, "", 0, 0); - } - - $this->SetXY($tmpx+$rabattWidth,$tmpy); - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - } else { - if($item['rabatt']<>0){ - // && $item['keinrabatterlaubt']!="1") - $this->Cell($rabattWidth, $cellhoehe, $item['ohnepreis'] ? '' : $item['rabatt'] . " %", 0, 0, 'R'); - } - else - { - if($this->getStyleElement('modul_verband')=='1') - { - $rabatt_or_porto = $this->app->DB->Select("SELECT id FROM artikel WHERE - nummer='".$item['itemno']."' AND (porto='1' OR rabatt='1') LIMIT 1"); - if($rabatt_or_porto){ - $this->Cell($rabattWidth, $cellhoehe, '', 0, 0, 'R'); - } - else{ - $this->Cell($rabattWidth, $cellhoehe, 'SNP', 0, 0, 'R'); - } - } else { - $this->Cell($rabattWidth,$cellhoehe,"",0,0,'R'); - } - } - } - } - else { - // anzeige ohne zentrale rabatt spalte - if ($item['tax']==="hidden"){ - $this->Cell($priceWidth,$cellhoehe,"",0,0,'R'); - } - else { - if($anzeigeBelegNettoAdrese) - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - { - if(!$inventurohnepreis){ - $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['tprice']),0,0,'R'); - } - } - else{ - if(!$inventurohnepreis){ - $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); - } - } - - $this->Cell($rabattWidth,$cellhoehe,"",0,0,'R'); - } - } - } - else { - if($anzeigeBelegNettoAdrese) - // if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - if(!$inventurohnepreis){ - $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['price']),0,0,'R'); - } - else{ - if(!$inventurohnepreis){ - $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price'] * $item['tmptax']), 0, 0, 'R'); - } - } - } - //$this->Cell($sumWidth,$cellhoehe,$this->formatMoney($item['tprice']).' '.$item['currency'],0,0,'R'); - if($this->rabatt=='1') - { - //gesamt preis - if ($item['tax']==='hidden'){ - $this->Cell($priceWidth,$cellhoehe,'',0,0,'R'); - } - else { - if($this->rabatt=='1'){ - if($anzeigeBelegNettoAdrese){ - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - if(!$inventurohnepreis){ - $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice']), 0, 0, 'R'); - } - } - else{ - if(!$inventurohnepreis){ - $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); - } - } - } - else { - if($anzeigeBelegNettoAdrese){ - // if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - if(!$inventurohnepreis){ - $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice']), 0, 0, 'R'); - } - } - else{ - if(!$inventurohnepreis){ - $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); - } - } - } - } - } - - } - else if(($this->doctype==='lieferschein' || $this->doctype==='preisanfrage') && $this->getStyleElement('artikeleinheit')=='1') - { - if($item['unit']!='') - $einheit = $item['unit']; - else { - $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE - nummer='".$item['itemno']."' LIMIT 1"); - if($einheit=='') { - $einheit = $this->getStyleElement('artikeleinheit_standard'); - } - } - - if(!empty($einheit) && !empty($documentLanguage)){ - $query = sprintf("SELECT ae.id FROM `artikeleinheit` AS `ae` - WHERE ae.einheit_de = '%s'", - $this->app->DB->real_escape_string($einheit)); - $unitId = $this->app->DB->Select($query); - if(!empty($unitId)){ - $query = sprintf("SELECT u.beschriftung FROM `uebersetzung` AS `u` - WHERE u.sprache = '%s' AND u.label='%s'", - $documentLanguage,'artikeleinheit_'.$unitId); - $unitTranslation = $this->app->DB->Select($query); - if(!empty($unitTranslation)){ - $einheit = $unitTranslation; - } - } - } - - $this->Cell($einheitWidth,$cellhoehe,$this->app->erp->ReadyForPDF($einheit),0,0,'R'); - } - - $this->Ln(); - if($this->getStyleElement('herstellernummerimdokument')=='1' && $item['herstellernummer']!='') - { - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_herstellernummer') . ': ' . $item['herstellernummer']; - } - else{ - $item['desc'] = $this->app->erp->Beschriftung('dokument_herstellernummer') . ': ' . $item['herstellernummer']; - } - } - - $daten = $this->app->DB->SelectRow("SELECT laenge, breite, hoehe FROM artikel WHERE id = '".$item['artikel']."'"); - if($this->getStyleElement('abmessungimdokument')=='1' && (!empty($daten['laenge']) || $daten['breite']!='' || $daten['hoehe']!='')) { - $tmp = array(); - if($daten['laenge']<>0) { - $tmp[]=number_format($daten['laenge'],2,',','.'); - } - if($daten['breite']<>0) { - $tmp[]=number_format($daten['breite'],2,',','.'); - } - if($daten['hoehe']<>0) { - $tmp[]=number_format($daten['hoehe'],2,',','.'); - } - - if(count($tmp) > 0) - { - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_abmessung') . ': ' . implode('x', $tmp); - } - else{ - $item['desc'] = $this->app->erp->Beschriftung('dokument_abmessung') . ': ' . implode('x', $tmp); - } - } - } - - if($item['lieferdatum']!='' && $item['lieferdatum']!='0000-00-00' && $item['lieferdatum']!=='00.00.0000') - { - if(strpos($item['lieferdatum'],"-")!==false){ - $item['lieferdatum'] = $this->app->erp->ReadyForPDF($this->app->String->Convert($item['lieferdatum'], '%1-%2-%3', '%3.%2.%1')); - } - - if($item['lieferdatumkw']==1) - { - $ddate = $this->app->String->Convert($item['lieferdatum'],'%3.%2.%1','%1-%2-%3'); - $duedt = explode("-", $ddate); - $date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]); - $week = date('W/o', $date); - $item['lieferdatum'] = $this->app->erp->Beschriftung('dokument_lieferdatumkw').' '.$week; - } - - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_lieferdatum') . ': ' . $item['lieferdatum']; - } - else{ - $item['desc'] = $this->app->erp->Beschriftung('dokument_lieferdatum') . ': ' . $item['lieferdatum']; - } - } - - - if($this->getStyleElement('freifelderimdokument')=='1') - { - for($ifreifeld=1;$ifreifeld<=40;$ifreifeld++) - { - if($item['freifeld'.$ifreifeld]!='') - { - $freifeldbeschriftung = $this->app->erp->Beschriftung('artikel_freifeld' . $ifreifeld); - $freifeldtyp = $this->getStyleElement('freifeld' . $ifreifeld.'typ'); - if($freifeldtyp==='select') - { - $freifeldbeschriftung = strstr($freifeldbeschriftung, '|', true); - } - - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $freifeldbeschriftung . ': ' . $item['freifeld' . $ifreifeld]; - } - else{ - $item['desc'] = $freifeldbeschriftung . ': ' . $item['freifeld' . $ifreifeld]; - } - } - } - if(strpos($item['desc'],'{{') !== false && $this->app->erp->ModulVorhanden('formeln')) { - $item['desc'] = $this->app->erp->BerechneFormel($item['desc'], $this->table, $this->id, $pos, $item); - } - - if(strpos($item['desc'],'{') !== false) { - if(!empty($item['belegposition']) && !empty($this->doctype) && !empty($this->id)) { - $item['desc'] = $this->parseBestBeforeBatchSn($item['desc'], $this->doctype, $this->id, $item['belegposition']); - } - $item['desc'] = $this->app->erp->ParseIfVars($item['desc']); - } - } - - if(strpos($item['desc'],'{') !== false) { - if(!empty($item['belegposition']) && !empty($this->doctype) && !empty($this->id)){ - $item['desc'] = $this->parseBestBeforeBatchSn( - $item['desc'], $this->doctype, $this->id, $item['belegposition'] - ); - } - } - - if(!empty($this->doctype) && !empty($this->id) && strpos($item['desc'], '{') !== false) { - $item['desc'] = $this->app->erp->ParseUserVars($this->doctype, $this->id ,$item['desc']); - } - - if($item['artikelnummerkunde']!="" && $item['artikelnummerkunde']!='0') - { - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_artikelnummerkunde') . ': ' . $item['artikelnummerkunde']; - } - else{ - $item['desc'] = $this->app->erp->Beschriftung('dokument_artikelnummerkunde') . ': ' . $item['artikelnummerkunde']; - } - } - - if($item['zolltarifnummer']!='' && $item['zolltarifnummer']!='0' && $this->doctype!='proformarechnung') - { - if($item['desc']!='') { - $item['desc']=$item['desc']."\r\n".$this->app->erp->Beschriftung('dokument_zolltarifnummer').': '.$item['zolltarifnummer'].' '.($item['herkunftsland']!=''?$this->app->erp->Beschriftung('dokument_herkunftsland').': '.$item['herkunftsland']:''); - } - else { - $item['desc']=$this->app->erp->Beschriftung('dokument_zolltarifnummer').': '.$item['zolltarifnummer'].' '.($item['herkunftsland']!=""?$this->app->erp->Beschriftung('dokument_herkunftsland').': '.$item['herkunftsland']:''); - } - } - - if($item['ean']!='' && $item['ean']!='0') - { - if($item['desc']!=''){ - $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_ean') . ': ' . $item['ean']; - } - else{ - $item['desc'] = $this->app->erp->Beschriftung('dokument_ean') . ': ' . $item['ean']; - } - } - - if($item['zusammenfassen']){ - $item['desc'] = ''; - } - - $startpageBeforeDescription = $this->page; - - if($item['desc']!='' || !empty($item['steuertext'])) { - //Herstellernummer einblenden wenn vorhanden und aktiviert - $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); - $this->SetY($position_y_end_name+$this->getStyleElement('abstand_name_beschreibung')); - $yBeforeDescription = $this->GetY(); - $this->SetFont($this->GetFont(),'',$zeilenuntertext); - if($belege_stuecklisteneinrueckenmm && $newlvl > 0){ - $this->Cell($belege_stuecklisteneinrueckenmm * $newlvl, $cellhoehe, ''); - } - $this->Cell($posWidth); - $this->Cell($itemNoWidth); - if($this->doctype==='arbeitsnachweis') { - $this->Cell($taxWidth); - } - - if($this->doctype==='lieferschein' && $this->getStyleElement('modul_verband')=='1'){ - $this->SetFont($this->GetFont(), '', $tabelleninhalt + 1); - } - - if($this->getStyleElement('briefhtml')=='1') - { - $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($item['desc'])); - if($this->getStyleElement('artikeleinheit')=='1') - { - if($this->getStyleElement('breite_artikelbeschreibung')) - { - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$this->WriteHTML($html),0,'L'); // 4 = abstand - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - else - { - $this->MultiCell($descWidth-$einheitWidth,($zeilenuntertext/2),$this->WriteHTMLCell($descWidth-$einheitWidth,$html),0,'L'); // 4 = abstand //ALT - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - } - else - { - if($this->getStyleElement('breite_artikelbeschreibung')=='1') - { - $this->MultiCell($descWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$this->WriteHTML($html),0,'L'); // 4 = abstand - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - else - { - $this->MultiCell($descWidth,($zeilenuntertext/2),$this->WriteHTMLCell($descWidth,$html),0,'L'); // 4 = abstand //ALT - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - } - } else { - if($this->getStyleElement('artikeleinheit')=='1') - { - if($this->getStyleElement('breite_artikelbeschreibung')) - { - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - else - { - $this->MultiCell($descWidth-$einheitWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand //ALT - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - } - else - { - if($this->getStyleElement('breite_artikelbeschreibung')=='1') - { - $this->MultiCell($descWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - else - { - $this->MultiCell($descWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand //ALT - if(!empty($item['steuertext'])){ - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - } - } - - $this->Cell($taxWidth); - $this->Cell($amWidth); - $this->Ln(); - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - - $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); - $this->SetFont($this->GetFont(),'',$zeilenuntertext); - $this->Cell($posWidth); - $this->Cell($itemNoWidth); - if($this->doctype==='arbeitsnachweis') { - $this->Cell($taxWidth); - } - if($this->getStyleElement('artikeleinheit')=='1'){ - $this->MultiCell($descWidth - $einheitWidth, 4, '', 0); // 4 = abstand zwischen Artikeln - } - else{ - $this->MultiCell($descWidth, 4, '', 0); // 4 = abstand zwischen Artikeln - } - $this->Cell($taxWidth); - $this->Cell($amWidth); - $this->Ln(); - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - $yAfterDescription = $this->GetY(); - } else { - - $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); - $this->SetY($position_y_end_name); - $yBeforeDescription = $this->GetY(); - $this->SetFont($this->GetFont(),'',$zeilenuntertext); - $this->Cell($posWidth); - $this->Cell($itemNoWidth); - if($this->doctype==='arbeitsnachweis') - { - $this->Cell($taxWidth); - } - if($this->getStyleElement('artikeleinheit')=='1') - { - $this->MultiCell($descWidth-$einheitWidth,3,trim($item['desc']),0); // 4 = abstand - if(!empty($item['steuertext'])) - { - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - else - { - $this->MultiCell($descWidth,3,trim($item['desc']),0); // 4 = abstand - if(!empty($item['steuertext'])) - { - $this->SetX($this->GetX()+$posWidth+$itemNoWidth); - $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); - } - } - - if(!empty($staffelpreiseanzeigen)){ - $this->MultiCell($posWidth+$itemNoWidth+$descWidth+$amWidth+$taxWidth+$sumWidth+$priceWidth,($zeilenuntertext/2),trim($staffelpreistext),0,'R'); - } - - $this->Cell($taxWidth); - $this->Cell($amWidth); - $this->Ln(); - $this->SetFont($this->GetFont(),'',$tabelleninhalt); - $yAfterDescription = $this->GetY(); - } - - $itemNoWidth = $itemNoWidthold; - $posWidth = $posWidthold; - - - - if( - ($this->doctype == "auftrag" && $this->getStyleElement("beleg_artikelbild")) || - ($this->doctype == "lieferschein" && $this->getStyleElement("lieferschein_artikelbild")) || - ($this->doctype == "rechnung" && $this->getStyleElement("rechnung_artikelbild")) || - ($this->doctype == "bestellung" && $this->getStyleElement("bestellung_artikelbild")) || - ($this->doctype == "gutschrift" && $this->getStyleElement("gutschrift_artikelbild")) || - ($this->doctype == "angebot" && $this->getStyleElement("angebot_artikelbild")) - ){ - $datei = $this->app->DB->Select("SELECT datei FROM `datei_stichwoerter` WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='" . $item['artikel'] . "' ORDER by sort ASC LIMIT 1"); - if(!empty($datei)){ - $datei = $this->app->DB->Select("SELECT id FROM datei_version WHERE datei = '$datei' ORDER BY id DESC LIMIT 1"); - } - $startpage = $this->page; - if(!empty($datei)){ - $xBeforePic = $this->GetX(); - $folder = $this->app->erp->GetDMSPath($datei); - if(file_exists($folder . '/' . $datei)){ - if(!class_exists('image')) include_once(__DIR__ . '/../class.image.php'); - $img = new image($this->app); - $breite = 20 * 10; - $hoehe = $breite; - - [$width, $height] = getimagesize($folder . '/' . $datei); - if($width > 0 && $height > 0){ - $scalex = $breite / $width; - $scaley = $hoehe / $height; - if($scalex < $scaley){ - $hoehe /= $scaley / $scalex; - $hoehe = ceil($hoehe); - }else{ - $breite /= $scalex / $scaley; - $breite = ceil($breite); - } - - $cachefolder = $this->app->erp->CreateDMSPath($this->app->Conf->WFuserdata . '/dms/' . $this->app->Conf->WFdbname . '/cache', $datei, true) . "/"; - $dateiname = $cachefolder . $datei . '_' . $breite . '_' . $hoehe; - - if(!is_file($dateiname)) $img->scaledPicByFileId($datei, $breite, $hoehe, false, 'jpg'); - if(is_file($dateiname)){ - [$width, $height] = getimagesize($dateiname); - //$value['datei'] = array('file'=>$folder.'/cache/'.$datei.'_'.$breite.'_'.$breite,'width'=>$width/10,'height'=>$height/10); - - $this->SetX($posWidth + (int)$this->getStyleElement("abstand_seitenrandlinks") - 5); - $dateityp = mime_content_type($dateiname); - $dateityp = substr($dateityp,6); - if($dateityp == ''){ - $dateityp = 'jpg'; - } - - if($startpageBeforeDescription != $this->page){ - $this->SetY($this->abseite2y); - $this->SetX($posWidth + (int)$this->getStyleElement("abstand_seitenrandlinks") - 5); - $position_y_end_name = $this->abseite2y; - } - $this->Image($dateiname, $this->GetX(), $position_y_end_name + 2, $width / 10, $hoehe / 10,$dateityp); - $this->SetXY($this->GetX(), $position_y_end_name + 20); - $yAfterPic = $this->GetY(); - } - } - } - - if($yAfterPic < $yAfterDescription){ - $this->SetY($yAfterDescription); - } - - $this->SetX($xBeforePic); - - $y_nach_bild = $this->GetY(); - - if($yAfterDescription < $yAfterPic+5 && $startpage == $this->page){ - $this->SetY($y_nach_bild+5); - } - if($this->GetY() > 240){ - $this->AddPage(); - } - - } - - } - } - - for ($l=$pos; $l <= $pos+$jitposfix ; $l++) { - //Letzten Artikel durcharbeiten - $this->DrawZwischenpositionen($l+$jitposfixbase, $umsatzsteuerermaessigtProzent,$umsatzsteuernormalProzent); - } - - //$this->Line($this->GetX(), $this->GetY(), $this->getStyleElement("abstand_seitenrandlinks")+195-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); - - $this->Line($this->getStyleElement("abstand_seitenrandlinks")+1, $this->GetY(), 210-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); - } - - function DrawZwischenpositionen($pos,$umsatzsteuerermaessigt = null,$umsatzsteuernormal = null) { - $ret = false; - if(is_null($umsatzsteuerermaessigt)) - { - $umsatzsteuerermaessigt = $this->app->erp->GetSteuersatzErmaessigt(false,$this->doctypeid,$this->table); - } - if(is_null($umsatzsteuernormal)) - { - $umsatzsteuernormal = $this->app->erp->GetSteuersatzNormal(false,$this->doctypeid,$this->table); - } - if($this->table != 'lieferschein' && $this->table != 'preisanfrage') - { - $zwischenpositionen = $this->app->DB->SelectArr("SELECT * FROM beleg_zwischenpositionen WHERE doctype='".$this->table."' AND doctypeid='".$this->doctypeid."' AND pos='$pos' ORDER by sort"); - }else{ - $zwischenpositionen = $this->app->DB->SelectArr("SELECT * FROM beleg_zwischenpositionen WHERE doctype='".$this->table."' AND doctypeid='".$this->doctypeid."' AND pos='$pos' AND postype <> 'gruppensumme' AND postype <> 'gruppensummemitoptionalenpreisen' AND postype <> 'zwischensumme' ORDER by sort"); - } - - $projekt = $this->app->DB->Select("SELECT projekt FROM ".$this->table." WHERE id = '".$this->doctypeid."' LIMIT 1"); - $czwischenpositionen = !empty($zwischenpositionen)?count($zwischenpositionen):0; - for($i=0;$i<$czwischenpositionen;$i++) - { - $data = json_decode($zwischenpositionen[$i]['wert'], true); - switch($zwischenpositionen[$i]['postype']) - { - case "gruppe": - $ret = true; - $schriftgroesse = $this->FontSizePt; - $schriftgroesse_alt = $schriftgroesse; - if($schriftgroesse == 0)$schriftgroesse = 7; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - if($schriftgroesse == 0)$schriftgroesse = 7; - $this->SetFontSize($schriftgroesse); - } - $fett = true; - if(isset($data['Fett'])) - { - if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; - if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; - } - $unterstrichen = false; - if(isset($data['Unterstrichen'])) - { - $unterstrichen = $data['Unterstrichen']; - } - $this->underline = $unterstrichen; - $html = ($fett?"":"").$data['name'].($fett?"":""); - if(!empty($data['Abstand_Oben'])) - { - $this->Ln((int)$data['Abstand_Oben']); - }else{ - $this->Ln(0); - } - $schriftgroesse = 7; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - } - $this->SetFontSize($schriftgroesse_alt); - $x = $this->GetX(); - $abstand_links = 0; - if(isset($data['Abstand_Links'])) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - } - - $this->MultiCell(0,4,$this->WriteHTML($html)); - $this->SetX($x); - $this->Ln(); - $this->underline = false; - if($data['kurztext']!="") - { - - if(isset($data['Kurztext_Unterstrichen'])) - { - $this->underline = $data['Kurztext_Unterstrichen']; - } - $x = $this->GetX(); - $abstand_links = 0; - if(isset($data['Kurztext_Abstand_Links'])){ - $abstand_links = (int)$data['Kurztext_Abstand_Links']; - $this->SetX($x+$abstand_links); - } - elseif(isset($data['Abstand_Links'])) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - } - $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); - $this->SetX($x); - if(!empty($data['Abstand_Unten'])) - { - $this->Ln((int)$data['Abstand_Unten']); - }else{ - $this->Ln(10); - } - } - $this->SetFontSize($schriftgroesse_alt); - $this->underline = false; - break; - - case "bild": - if($data['bild']) - { - $nochtext = ''; - if($data['kurztext']!="") - { - $kurztexta = explode('{BILD}', $data['kurztext'], 2); - }else { - $kurztexta[] = ''; - } - if(count($kurztexta) > 1)$nochtext = $kurztexta[1]; - $data['kurztext'] = $kurztexta[0]; - - $__x = $this->GetX(); - //$ret = true; - $schriftgroesse = $this->FontSizePt; - $schriftgroesse_alt = $schriftgroesse; - if($schriftgroesse == 0)$schriftgroesse = 7; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - if($schriftgroesse == 0)$schriftgroesse = 7; - $this->SetFontSize($schriftgroesse); - } - $fett = true; - if(isset($data['Fett'])) - { - if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; - if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; - } - $unterstrichen = false; - if(isset($data['Unterstrichen'])) - { - $unterstrichen = $data['Unterstrichen']; - } - $this->underline = $unterstrichen; - $html = ($fett?"":"").$data['name'].($fett?"":""); - if(!empty($data['Abstand_Oben'])) - { - $this->Ln((int)$data['Abstand_Oben']); - }else{ - $this->Ln(0); - } - $schriftgroesse = 7; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - } - $this->SetFontSize($schriftgroesse_alt); - $x = $this->GetX(); - $abstand_links = 0; - if(isset($data['Abstand_Links'])) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - } - - $this->MultiCell(0,4,$this->WriteHTML($html)); - $this->SetX($x); - $this->Ln(); - $this->underline = false; - if($data['kurztext']!="") - { - - if(isset($data['Kurztext_Unterstrichen'])) - { - $this->underline = $data['Kurztext_Unterstrichen']; - } - $x = $this->GetX(); - $abstand_links = 0; - if(isset($data['Kurztext_Abstand_Links'])){ - $abstand_links = (int)$data['Kurztext_Abstand_Links']; - $this->SetX($x+$abstand_links); - } - elseif(isset($data['Abstand_Links'])) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - } - $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); - $this->SetX($x); - if($nochtext == '') - { - if(!empty($data['Abstand_Unten'])) - { - $this->Ln((int)$data['Abstand_Unten']); - }else{ - $this->Ln(10); - } - } - } - $this->SetFontSize($schriftgroesse_alt); - $this->underline = false; - - $posWidth = $this->getStyleElement("breite_position"); - $amWidth = $this->getStyleElement("breite_menge"); - $itemNoWidth = $this->getStyleElement("breite_nummer"); - $datei = $data['bild']; - if(!empty($datei)) - { - $datei = $this->app->DB->Select("SELECT id FROM datei_version WHERE datei = '$datei' ORDER BY id DESC LIMIT 1"); - } - if(!empty($datei)) - { - $folder = $this->app->erp->GetDMSPath($datei); - if(file_exists($folder.'/'.$datei)) - { - if(!class_exists('image'))include_once(__DIR__.'/../class.image.php'); - $img = new image($this->app); - if(isset($data['bildbreite']) && (int)$data['bildbreite'] > 0) - { - $breite = $data['bildbreite'] * 10; - }else{ - $breite = 30 * 10; - } - if(isset($data['bildhoehe']) && (int)$data['bildhoehe'] > 0) - { - $hoehe = $data['bildhoehe'] * 10; - }else{ - $hoehe = $breite; - } - [$width, $height] = getimagesize($folder.'/'.$datei); - if($width > 0 && $height > 0) - { - $scalex = $breite / $width; - $scaley = $hoehe / $height; - if($scalex < $scaley) - { - $hoehe /= $scaley / $scalex; - $hoehe = ceil($hoehe); - }else{ - $breite /= $scalex / $scaley; - $breite = ceil($breite); - } - - $cachefolder = $this->app->erp->CreateDMSPath($this->app->Conf->WFuserdata.'/dms/'.$this->app->Conf->WFdbname.'/cache', $datei, true)."/"; - $dateiname = $cachefolder.$datei.'_'.$breite.'_'.$hoehe; - - if(!is_file($dateiname))$img->scaledPicByFileId($datei, $breite, $hoehe, false, 'jpg'); - if(is_file($dateiname)) - { - [$width, $height] = getimagesize($dateiname); - //$value['datei'] = array('file'=>$folder.'/cache/'.$datei.'_'.$breite.'_'.$breite,'width'=>$width/10,'height'=>$height/10); - $x = $this->GetX(); - $y = $this->GetY(); - $this->SetX($posWidth+$itemNoWidth+(int)$this->getStyleElement("abstand_seitenrandlinks")); - $this->Image($dateiname, $this->GetX(), $this->GetY(),$width / 10, $hoehe / 10, 'jpg'); - if($nochtext == '') - { - $this->Cell($picwidth,6,'',0,0,'C'); - } - $this->SetXY($this->GetX(), $y + $height / 10 + ($nochtext == ''?5:0)); - } - } - } - } - $this->SetXY($__x, $this->GetY()); - - if($nochtext !== '') - { - $data['kurztext'] = $nochtext; - $__x = $this->GetX(); - $ret = true; - $schriftgroesse = $this->FontSizePt; - $schriftgroesse_alt = $schriftgroesse; - if($schriftgroesse == 0)$schriftgroesse = 7; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - if($schriftgroesse == 0)$schriftgroesse = 7; - $this->SetFontSize($schriftgroesse); - } - $fett = true; - if(isset($data['Fett'])) - { - if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; - if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; - } - - $this->SetFontSize($schriftgroesse_alt); - $x = $this->GetX(); - $this->underline = false; - if($data['kurztext']!="") - { - - if(isset($data['Kurztext_Unterstrichen'])) - { - $this->underline = $data['Kurztext_Unterstrichen']; - } - $x = $this->GetX(); - $abstand_links = 0; - if(isset($data['Kurztext_Abstand_Links'])){ - $abstand_links = (int)$data['Kurztext_Abstand_Links']; - $this->SetX($x+$abstand_links); - } - elseif(isset($data['Abstand_Links'])) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - } - $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); - $this->SetX($x); - if(!empty($data['Abstand_Unten'])) - { - $this->Ln((int)$data['Abstand_Unten']); - }else{ - $this->Ln(10); - } - } - $this->SetFontSize($schriftgroesse_alt); - $this->underline = false; - } - } - break; - case "seitenumbruch": - $this->AddPage(); - break; - - case "gruppensumme": - case "gruppensummemitoptionalenpreisen": - case "zwischensumme": - $ret = true; - $posWidth = $this->getStyleElement("breite_position"); - $amWidth = $this->getStyleElement("breite_menge"); - $itemNoWidth = $this->getStyleElement("breite_nummer"); - $einheitWidth = $this->getStyleElement("breite_einheit"); - $descWidth = $this->getStyleElement("breite_artikel"); - $taxWidth = $this->getStyleElement("breite_steuer"); - - if($this->doctype=="arbeitsnachweis") - { - $itemNoWidth = 20; - $taxWidth = 40; - $descWidth = 95; - } - else if($this->doctype!="lieferschein" && $this->doctype!="produktion" && $this->doctype!="preisanfrage") { - if($descWidth <=0) - $descWidth = 76; - - if($taxWidth <=0) - $taxWidth = 15; - } - else - { - $itemNoWidth = 30; - $descWidth = 91; - if($taxWidth <=0) - $taxWidth = 15; - } - $priceWidth = 20; - $sumWidth = 20; - $rabattWidth = 15; - - - $schriftgroesse = $this->FontSizePt; - $schriftgroesse_alt = $schriftgroesse; - if($schriftgroesse == 0)$schriftgroesse = 4; - if(!empty($data['Schriftgroesse'])) - { - $schriftgroesse = $data['Schriftgroesse']; - if($schriftgroesse == 0)$schriftgroesse = 4; - $this->SetFontSize($schriftgroesse); - } - $fett = true; - if(isset($data['Fett'])) - { - if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; - if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; - } - $unterstrichen = false; - if(isset($data['Unterstrichen'])) - { - $unterstrichen = $data['Unterstrichen']; - } - $this->underline = $unterstrichen; - - switch($zwischenpositionen[$i]['postype']) - { - case "gruppensumme": - case "gruppensummemitoptionalenpreisen": - $maxpos_untergruppedrueber = (int)$this->app->DB->Select("SELECT pos FROM beleg_zwischenpositionen WHERE doctype='".$this->doctype."' AND doctypeid='".$this->doctypeid."' AND pos < '$pos' AND postype='gruppe' ORDER by pos DESC LIMIT 1"); - - if($this->doctype=="angebot") - { - $subwhere = " AND (explodiert_parent = 0 OR 0 = ifnull((SELECT id FROM angebot_position WHERE id = ap.explodiert_parent AND berechnen_aus_teile = 1 LIMIT 1),0))"; - if($zwischenpositionen[$i]['postype'] !== 'gruppensummemitoptionalenpreisen'){ - $subwhere = ' AND optional!=1 '.$subwhere; - } - $zwischenpositionen[$i]['postype'] = 'gruppensumme'; - } - if($this->doctype=="bestellung") - { - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM(preis*menge) FROM ".$this->doctype."_position WHERE ".$this->doctype."='".$this->doctypeid."' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); - }else{ - $anzeigesteuerbelege = $this->app->DB->Select("SELECT anzeigesteuerbelege FROM projekt WHERE id = ".$projekt); - if( - ( - ( - $this->anrede=="firma" || - $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt,$this->table,$this->id) || - $this->doctype=="bestellung" || - $this->getStyleElement("immernettorechnungen",$projekt)=="1" || - $anzeigesteuerbelege =='1' - ) && - $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") || - $this->ust_befreit - ) { - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); - }else{ - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge)* - (1 + if(ifnull(steuersatz,-1) < 0,if(umsatzsteuer = 'befreit',0,if(umsatzsteuer = 'ermaessigt',$umsatzsteuerermaessigt,$umsatzsteuernormal)),steuersatz - )/100) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); - } - } - break; - default: - //zwischensumme - if($this->doctype=="angebot") - { - $subwhere = " AND optional!=1 AND (explodiert_parent = 0 OR 0 = ifnull((SELECT id FROM angebot_position WHERE id = ap.explodiert_parent AND berechnen_aus_teile = 1 LIMIT 1),0))"; - } - if($this->doctype=="bestellung") - { - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM(preis*menge) FROM ".$this->doctype."_position WHERE ".$this->doctype."='".$this->doctypeid."' AND sort <='$pos' $subwhere")); - }else{ - if((($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt,$this->table,$this->id) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") || $this->ust_befreit ) { - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' $subwhere")); - }else{ - $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge)* - (1 + if(ifnull(steuersatz,-1) < 0,if(umsatzsteuer = 'befreit',0,if(umsatzsteuer = 'ermaessigt',$umsatzsteuerermaessigt,$umsatzsteuernormal)),steuersatz - )/100) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' $subwhere")); - } - } - break; - } - - $beschriftung_zeile = ucfirst($zwischenpositionen[$i]['postype']); - - if($data['name']=="") - $html = ($fett?"":"").$beschriftung_zeile.($fett?"":""); - else - $html = ($fett?"":"").$data['name'].($fett?"":""); - if(!empty($data['Abstand_Oben'])) - { - $this->Ln((int)$data['Abstand_Oben']); - }else{ - $this->Ln(0); - } - $x = $this->GetX(); - - if(isset($data['Abstand_Links']) && $data['Abstand_Links'] > 0) - { - $abstand_links = (int)$data['Abstand_Links']; - $this->SetX($x+$abstand_links); - }else{ - $abstand_links = $posWidth +$itemNoWidth; - } - - $this->SetX($x+$abstand_links); - $this->Cell($descWidth,4,$this->WriteHTML($html)); - $this->SetX($x+$abstand_links+$descWidth); - //$this->SetX($x); - - $rahmen_links = false; - $rahmen_rechts = false; - $rahmen_oben = false; - $rahmen_unten = false; - if(isset($data['Rahmen_Links'])) - { - $rahmen_links = $data['Rahmen_Links']; - } - if(isset($data['Rahmen_Rechts'])) - { - $rahmen_rechts = $data['Rahmen_Rechts']; - } - if(isset($data['Rahmen_Oben'])) - { - $rahmen_oben = $data['Rahmen_Oben']; - } - if(isset($data['Rahmen_Unten'])) - { - $rahmen_unten = $data['Rahmen_Unten']; - } - $rahmen = ''; - if($rahmen_links)$rahmen .= 'L'; - if($rahmen_rechts)$rahmen .= 'R'; - if($rahmen_oben)$rahmen .= 'T'; - if($rahmen_unten)$rahmen .= 'B'; - $ausrichtung = 'R'; - if(isset($data['Text_Ausrichtung'])) - { - $ausrichtung = $data['Text_Ausrichtung']; - } - $this->Cell($priceWidth+$amWidth+$taxWidth+$priceWidth,4,$summe,$rahmen,0,$ausrichtung); - if(!empty($data['Abstand_Unten'])) - { - $this->Ln((int)$data['Abstand_Unten']); - }else{ - $this->Ln(10); - } - $this->SetFontSize($schriftgroesse_alt); - $this->underline = false; - break; - } - } - return $ret; - } - - - /* - totals ( - totalArticles - Summe aller Artikelpreise - modeOfDispatch - Versandart - priceOfDispatch - Versandkosten - modeOfPayment - Zahlungsweise - priceOfPayment - Kosten der Zahlungsweise - total = totalArticles + priceOfDispatch + priceOfPayment - totalTaxV - Summe voller Steuersatz - totalTaxR - Summe reduzierter Steuersatz - ) - */ - public function renderTotals() { - - if($this->doctype === 'angebot' && $this->app->DB->Select("SELECT gesamtsummeausblenden FROM angebot WHERE id = '".$this->doctypeid."'")){ - $this->Ln(8); - return ''; - } - - if($this->doctype === 'inventur' && $this->app->DB->Select("SELECT noprice FROM inventur WHERE id = '".$this->id."'")){ - $this->Ln(8); - return ''; - } - - $this->SetY($this->GetY()+1); - - $differenz_wegen_abstand = $this->getStyleElement('abstand_gesamtsumme_lr'); - - if($this->doctype!='lieferschein' && $this->doctype!='arbeitsnachweis' && $this->doctype!='preisanfrage') { - //$this->Line(110, $this->GetY(), 190, $this->GetY()); - $this->Ln(1); - $this->SetFont($this->GetFont(),'',$this->getStyleElement('schriftgroesse_gesamt')); - $this->Cell($differenz_wegen_abstand,2,'',0); - if($this->getStyleElement('kleinunternehmer')!='1' && $this->doctype!='zahlungsavis'){ - $nettoText = $this->app->erp->Beschriftung('dokument_gesamtnetto'); - $nettoAmount = $this->formatMoney(round((double)$this->totals['totalArticles'], 2), 2).' '.$this->waehrung; - $doctype = $this->doctype; - $doctypeid = !empty($this->doctypeid)?$this->doctypeid: $this->id; - $this->app->erp->RunHook('class_briefpapier_render_netto', 4, $doctype, $doctypeid, $nettoText, $nettoAmount); - $this->Cell(30,5,$nettoText,0,0,'L'); - $this->Cell(40,5,$nettoAmount,0,'L','R'); - } else { - //kleinunzernehmer - $this->Cell(30,5,'',0,0,'L'); - $this->Cell(40,5,'',0,'L','R'); - } - $this->Ln(); - - if(isset($this->totals['modeOfDispatch'])) { - $versand = 'Versand: '.$this->totals['modeOfDispatch']; - } - else { - $versand = 'Versandkosten: '; - } - if(isset($this->totals['priceOfDispatch'])) { - $this->Cell($differenz_wegen_abstand,2,'',0); - $this->Cell(30,5,$versand,0,'L','L'); - $this->Cell(40,5,$this->formatMoney((double)$this->totals['priceOfDispatch'], 2).' '.$this->waehrung,0,'L','R'); - } - //$this->Ln(); - - if(isset($this->totals['priceOfPayment']) && $this->totals['priceOfPayment']!='0.00'){ - $this->Cell($differenz_wegen_abstand,2,'',0); - $this->Cell(30,5,$this->totals['modeOfPayment'],0,'L','L'); - $this->Cell(40,5,$this->formatMoney((double)$this->totals['priceOfPayment'], 2).' '.$this->waehrung,0,'L','R'); - $this->Ln(); - } - - $this->SetY($this->GetY()); - $this->SetFont($this->GetFont(),'',$this->getStyleElement("schriftgroesse_gesamt_steuer")); - - - if(isset($this->totals['totalTaxV']) && $this->totals['totalTaxV']!="0.00"){ - $this->Cell($differenz_wegen_abstand,1,'',0); - - if($this->getStyleElement('kleinunternehmer')!='1'){ - if(!empty($this->doctype) && !empty($this->id) && is_numeric($this->id)){ - $projekt = $this->app->DB->Select('SELECT projekt FROM `' . $this->doctype . '` WHERE id = ' . $this->id); - $adresse = $this->app->DB->Select('SELECT adresse FROM `' . $this->doctype . '` WHERE id = ' . $this->id); - }else{ - $projekt = 0; - $adresse = 0; - } - - if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - { - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$this->app->erp->GetSteuersatzNormal(false,$this->id,$this->table).' %',0,'L','L'); //1 - } - else { - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$this->app->erp->GetSteuersatzNormal(false,$this->id,$this->table).' %',0,'L','L'); - } - $this->Cell(40,3,$this->formatMoney((double)$this->totals['totalTaxV'], 2).' '.$this->waehrung,0,'L','R'); - } else { - //kleinunternehmer - $this->Cell(30,3,'',0,'L','L'); - $this->Cell(40,3,'',0,'L','R'); - } - $this->Ln(); - } - $projekt = $this->projekt; - $adresse = $this->app->DB->Select("SELECT adresse FROM ".($this->table?$this->table:$this->doctype)." WHERE id = '".$this->id."' LIMIT 1"); - if(!empty($this->totals['totalTaxR']) && $this->totals['totalTaxR']!='0.00'){ - $this->Cell($differenz_wegen_abstand,1,'',0); - - if($this->getStyleElement('kleinunternehmer')!='1'){ - - if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - { - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$this->app->erp->GetSteuersatzErmaessigt(false,$this->id,$this->table).' %',0,'L','L'); //1 - } - else { - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$this->app->erp->GetSteuersatzErmaessigt(false,$this->id,$this->table).' %',0,'L','L'); - } - - $this->Cell(40,3,$this->formatMoney(round((double)$this->totals['totalTaxR'],2), 2).' '.$this->waehrung,0,'L','R'); - } else { - //kleinunternehmer - $this->Cell(30,3,'',0,'L','L'); - $this->Cell(40,3,"",0,'L','R'); - } - - $this->Ln(); - } - - if(!empty($this->totals['summen'])) - { - ksort($this->totals['summen'], SORT_NUMERIC); - foreach($this->totals['summen'] as $k => $value) - { - if($value == 0) - { - continue; - } - $this->Cell($differenz_wegen_abstand,1,'',0); - - if($this->getStyleElement('kleinunternehmer')!='1'){ - if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - { - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$k.' %',0,'L','L'); //1 - }else { - //$this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$k.' %',0,'L','L'); 09.12.2018 ab heute auskommentiert wegen 829087 - $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$k.' %',0,'L','L'); - } - - $this->Cell(40,3,$this->formatMoney(round($value,2), 2).' '.$this->waehrung,0,'L','R'); - } else { - //kleinunternehmer - $this->Cell(30,3,'',0,'L','L'); - $this->Cell(40,3,"",0,'L','R'); - } - - $this->Ln(); - - } - - } - - if(!isset($this->totals['totalTaxR']) && !isset($this->totals['totalTaxV']) && !isset($this->totals['summen']) && $this->doctype!="zahlungsavis") - { - $this->Cell($differenz_wegen_abstand,3,'',0); - - if($this->getStyleElement('kleinunternehmer')!='1') - { - if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) - //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") - // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") - { - if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland - { - $this->Cell(30, 3, $this->app->erp->Beschriftung('dokument_zzglmwst') . ' 0.00 %', 0, 'L', 'L'); //1 - } - } - else { - if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland - { - $this->Cell(30, 3, $this->app->erp->Beschriftung('dokument_inklmwst') . ' 0.00 %', 0, 'L', 'L'); - } - } - - if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland - { - $this->Cell(40, 3, '0,00 ' . $this->waehrung, 0, 'L', 'R'); - } - } else { - //kleinunternehmer - $this->Cell(30,3,'',0,'L','L'); - $this->Cell(40,3,'',0,'L','R'); - } - $this->Ln(); - } - $this->SetY($this->GetY()+2); - //$this->Line(110, $this->GetY(), 190,$this->GetY()); - } - - $this->SetFont($this->GetFont(),'B',$this->getStyleElement('schriftgroesse_gesamt')); - $this->Cell($differenz_wegen_abstand,5,'',0); - if($this->doctype=='offer'){ - $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); - } - elseif($this->doctype=='creditnote'){ - $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); - } - else if($this->doctype=='arbeitsnachweis'){ - $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); - } - else if($this->doctype=='zahlungsavis'){ - $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); - } - else{ - $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); - } - - if($this->doctype=='arbeitsnachweis'){ - $this->Cell(40, 5, $this->totals['total'] . ' ', 0, 'L', 'R'); - } - else { - if($this->getStyleElement('kleinunternehmer')!='1'){ - $this->Cell(40, 5, $this->formatMoney(round((double)$this->totals['total'], 2), 2) . ' ' . $this->waehrung, 0, 'L', 'R'); - } - else{ - $this->Cell(40, 5, $this->formatMoney(round((double)$this->totals['totalArticles'], 2), 2) . ' ' . $this->waehrung, 0, 'L', 'R'); - } - } - - $this->Ln(); - if($this->getStyleElement('briefpapier_ohnedoppelstrich')!='1') - { - $this->Line($differenz_wegen_abstand+5, $this->GetY(), 210-$this->getStyleElement('abstand_seitenrandrechts'),$this->GetY()); - $this->Line($differenz_wegen_abstand+5, $this->GetY()+1, 210-$this->getStyleElement('abstand_seitenrandrechts'),$this->GetY()+1); - } - - $this->SetY($this->GetY()+10); - } - - function displayAnhaenge($output='D') - { - SuperFPDF::__construct('P','mm','A4'); - $this->seite_von_sichtbar = 1; - - - - // if($this->getStyleElement("schriftart")!="") - // $this->SetFont($this->getStyleElement("schriftart")); - - if($this->getStyleElement('schriftart')!='' && $this->getStyleElement('schriftart')!='Arial' && - $this->getStyleElement('schriftart')!='Courier' && $this->getStyleElement('schriftart')!='Helvetica' - && $this->getStyleElement('schriftart')!='Times' && $this->getStyleElement('schriftart')!='Arial'){ - $this->AddFont($this->getStyleElement('schriftart'),'',strtolower($this->getStyleElement('schriftart')).'.php'); - $this->AddFont($this->getStyleElement('schriftart'),'I',strtolower($this->getStyleElement('schriftart')).'.php'); - $this->AddFont($this->getStyleElement('schriftart'),'B',strtolower($this->getStyleElement('schriftart')).'.php'); - } - if(!empty($this->addpdf) && is_array($this->addpdf)) - { - - foreach($this->addpdf as $addpdf) - { - - $filename = $addpdf; - - $pn = $this->setSourceFile($filename); - //$this->AddPage(); - //$this->SetXY(0,0); - for($i = 1; $i <= $pn ; $i++) - { - $fn =& $this->current_filename; - $mediabox = $this->parsers[$fn]->getPageMediaBox($i); - //$this->app->erp->LogFile(addslashes(json_encode($mediabox))); - if($i >= 1) - { - if(isset($mediabox['w']) && (float)$mediabox['w'] > 210.1 ) - { - $this->AddPage('L'); - } else { - $this->AddPage(); - } - $this->SetXY(0,0); - } - $tplidx = $this->ImportPage($i); - $this->useTemplate($tplidx); - } - } - } - $this->filename = $this->app->erp->Dateinamen($this->filename); - $this->Output($this->filename,$output); - exit; - } - - /** - * @param float $value - * @param int|null $decimals - * - * @return string - */ - protected function formatMoney($value, $decimals = null) - { - $decimals = $decimals !== null ? (int)$decimals : $this->anzahlkomma; - $currency = $this->waehrung; - return $this->app->erp->formatMoney($value, $currency,$decimals); - } -} +setStyleData($styleData); + //$orientation='P';$unit='mm';$format='A4'; + //parent::PDF_EPS($orientation,$unit,$format); + $this->projekt = $projekt; + + $this->app=$app; + $this->absender = ''; + $this->firmendatenid = $this->app->DB->Select("SELECT MAX(id) FROM firmendaten LIMIT 1"); + $this->parameter = ''; + + $viernachkommastellen_belege = $this->getStyleElement('viernachkommastellen_belege'); + if($viernachkommastellen_belege=='1') + { + $this->anzahlkomma=4; + } else { + $this->anzahlkomma=2; + } + + $this->ust_spalteausblende=false; + + if($this->getStyleElement('kleinunternehmer')=='1') + { + $this->ust_befreit=1; + $this->ust_spalteausblende=true; + } + + + $hintergrund = $this->getStyleElement('hintergrund'); + + if(!empty(erpAPI::Ioncube_Property('isdevelopmentversion'))) { + $this->setDevelopmentVersionBackground(); + } + elseif($this->app->erp->BriefpapierHintergrunddisable) + { + } + else if($hintergrund=='logo') + { + $logo = $this->app->erp->getSettingsFile('logo'); + $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_logo.jpg'; + if ($handle = fopen($filename, 'w')) { + fwrite($handle, $logo); + fclose($handle); + } + $this->logofile = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_logo.jpg'; + $this->briefpapier=''; + } + else if($hintergrund=='briefpapier') + { + $briefpapier = $this->app->erp->getSettingsFile('briefpapier'); + $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier.pdf'; + if ($handle = fopen($filename, 'w')) { + fwrite($handle, $briefpapier); + fclose($handle); + } + + $this->briefpapier=$this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier.pdf'; + $this->logofile = ''; + + $briefpapier2vorhanden = $this->getStyleElement('briefpapier2vorhanden'); + $this->briefpapier2vorhanden = $briefpapier2vorhanden; + if($briefpapier2vorhanden > 0) + { + $briefpapier2 = $this->app->erp->getSettingsFile('briefpapier2'); + $filename = $this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier2.pdf'; + if ($handle = fopen($filename, 'w')) { + fwrite($handle, $briefpapier2); + fclose($handle); + } + + $this->briefpapier2=$this->app->erp->GetTMP().$this->app->Conf->WFdbname.'_briefpapier2.pdf'; + } + } + else { + $this->logofile = ''; + $this->briefpapier=''; + } + + if(isset($this->app->Conf->WFtestmode) && $this->app->Conf->WFtestmode==true) + { + $this->briefpapier='./lib/dokumente/briefpapier_testmodus.pdf'; + $this->briefpapier2='./lib/dokumente/briefpapier_testmodus.pdf'; + } + + $this->knickfalz = $this->getStyleElement('knickfalz'); + $this->abseite2y = $this->getStyleElement('abseite2y'); + + $footersichtbar = $this->getStyleElement('footersichtbar'); + if($footersichtbar==1) { + $this->nichtsichtbar_footer = false; + } else { + $this->nichtsichtbar_footer = true; + } + + $seite_von_sichtbar = $this->getStyleElement('seite_von_sichtbar'); + if($seite_von_sichtbar==1) { + $this->seite_von_sichtbar = false; + } else { + $this->seite_von_sichtbar = true; + } + + $this->seite_von_ausrichtung = $this->getStyleElement('seite_von_ausrichtung'); + + + $this->abstand_adresszeileoben = $this->getStyleElement('abstand_adresszeileoben'); + $this->abstand_boxrechtsoben = $this->getStyleElement('abstand_boxrechtsoben'); + $this->abstand_boxrechtsoben_lr = $this->getStyleElement('abstand_boxrechtsoben_lr'); + $this->abstand_betreffzeileoben = $this->getStyleElement('abstand_betreffzeileoben'); + $this->abstand_artikeltabelleoben = $this->getStyleElement('abstand_artikeltabelleoben'); + + $this->boxausrichtung = $this->getStyleElement('boxausrichtung'); + + $sichtbar = $this->getStyleElement('sichtbar'); + if($sichtbar==1) { + $this->nichtsichtbar_zeileabsender = false; + } else { + $this->nichtsichtbar_zeileabsender =true; + } + + + $this->barcode_sichtbar = $this->getStyleElement('barcode'); + $this->barcode_x = $this->getStyleElement('barcode_x'); + $this->barcode_y = $this->getStyleElement('barcode_y'); + $this->barcode_x_header = $this->getStyleElement('barcode_x_header'); + $this->barcode_y_header = $this->getStyleElement('barcode_y_header'); + + $projekt = $this->projekt; + + + $this->waehrung=$this->getStyleElement('waehrung'); + + + + // kann man herausfinden was fuer ein projekt angegeben ist??? + $speziallieferschein = $this->app->DB->Select("SELECT speziallieferschein FROM projekt WHERE id='$projekt' LIMIT 1"); + $speziallieferscheinbeschriftung = $this->app->DB->Select("SELECT speziallieferscheinbeschriftung FROM projekt WHERE id='$projekt' LIMIT 1"); + $eigenesteuer = $this->app->DB->Select("SELECT eigenesteuer FROM projekt WHERE id='$projekt' LIMIT 1"); + if($eigenesteuer=='1'){ + $this->waehrung = $this->app->DB->Select("SELECT waehrung FROM projekt WHERE id='$projekt' LIMIT 1"); + } + if($speziallieferschein>0) + { + if(!$this->app->erp->BriefpapierHintergrunddisable) + { + $seite1 = $this->app->DB->Select("SELECT ds.datei FROM datei_stichwoerter ds INNER JOIN datei d ON d.id=ds.datei AND IFNULL(d.geloescht,0)=0 WHERE ds.subjekt LIKE 'Briefpapier1' AND ds.objekt LIKE 'Projekt' AND ds.parameter='$projekt' LIMIT 1"); + $seite2 = $this->app->DB->Select("SELECT ds.datei FROM datei_stichwoerter ds INNER JOIN datei d ON d.id=ds.datei AND IFNULL(d.geloescht,0)=0 WHERE ds.subjekt LIKE 'Briefpapier2' AND ds.objekt LIKE 'Projekt' AND ds.parameter='$projekt' LIMIT 1"); + } + + if(!empty($seite1) && is_file($this->app->erp->GetDateiPfad($seite1))){ + $this->briefpapier = $this->app->erp->GetDateiPfad($seite1); + } + if(!empty($seite2) && is_file($this->app->erp->GetDateiPfad($seite2))){ + $this->briefpapier2 = $this->app->erp->GetDateiPfad($seite2); + } + + if($seite2>0 && is_file($this->app->erp->GetDateiPfad($seite2))){ + $this->briefpapier2vorhanden = 1; + } + + $this->logofile = ''; + + if($speziallieferscheinbeschriftung!=1){ + $this->nichtsichtbar_zeileabsender = true; + $this->nichtsichtbar_footer = true; + $this->nichtsichtbar_rechtsoben = true; + } + } + + $this->nichtsichtbar_rechtsoben = true; + $this->nichtsichtbar_summe = false; + $this->nichtsichtbar_box=false; + $this->nichtsichtbar_empfaenger=false; + } + + /** + * set Development-watermark as pdf-background + * + * @return void + */ + protected function setDevelopmentVersionBackground(): void + { + $this->briefpapier = $this->app->erp->GetTMP().'development_version.pdf'; + $this->briefpapier2 = ''; + $this->logofile = ''; + if(is_file($this->briefpapier)) { + return; + } + $waterMarkPdf = new SuperFPDF('P', 'mm', 'A4'); + $waterMarkPdf->filename = $this->briefpapier; + $waterMarkPdf->AddPage(); + $waterMarkPdf->SetTextColor(200); + $waterMarkPdf->SetFont( + ($this->app->erp->Firmendaten('schriftart') ? $this->app->erp->Firmendaten('schriftart') : 'Arial'), + 'B', + 45 + ); + $waterMarkPdf->Rotate(45, 45, 180); + $waterMarkPdf->Text(45, 180, 'DEVELOPMENT VERSION'); + $waterMarkPdf->Rotate(0); + $waterMarkPdf->SetTextColor(0); + file_put_contents($waterMarkPdf->filename, $waterMarkPdf->displayAnhaenge('S')); + } + + /** + * @param string $language + * + * @return string + */ + public function getLanguageCodeFrom($language) { + if(empty($language)) { + return ''; + } + $languages = $this->app->DB->SelectArr("SELECT * FROM sprachen WHERE aktiv = 1 AND iso <> ''"); + if(empty($languages)) { + return ''; + } + foreach($languages as $languagesRow) { + if(in_array( + $language, + [ + $languagesRow['iso'], + $languagesRow['alias'], + $languagesRow['bezeichnung_de'], + $languagesRow['bezeichnung_en' + ] + ] + )) { + return $languagesRow['iso']; + } + } + + return ''; + } + + public function GetChargeMHDSNString($type,$doctype,$doctypeid,$posid, $returnSimpleString = false) + { + $lieferschein_posid = 0; + $auftrag_position_id = 0; + $lieferschein = 0; + if($doctype === 'rechnung'){ + $lieferschein = $this->app->DB->Select("SELECT lieferschein FROM rechnung WHERE id = '$doctypeid' LIMIT 1"); + } + if($doctype === 'rechnung' && !$lieferschein){ + $lieferschein = $this->app->DB->Select("SELECT id FROM lieferschein WHERE rechnungid = '$doctypeid' LIMIT 1"); + } + if($doctype === 'rechnung' && !$lieferschein) + { + $auftrag = $this->app->DB->Select("SELECT auftragid FROM rechnung WHERE id = '$doctypeid' LIMIT 1"); + if($auftrag){ + $lieferschein = $this->app->DB->Select("SELECT id FROM lieferschein WHERE auftragid = '$auftrag' LIMIT 1"); + } + } + if($doctype === 'lieferschein'){ + $lieferschein_posid = $posid; + } + if($doctype === 'rechnung'){ + $auftrag_position_id = $this->app->DB->Select("SELECT auftrag_position_id FROM rechnung_position WHERE id='$posid'"); + } + if($doctype === 'gutschrift'){ + $auftrag_position_id = $this->app->DB->Select("SELECT gutschrift_position_id FROM rechnung_position WHERE id='$posid'"); + } + if($doctype === 'rechnung') + { + if(!empty($auftrag_position_id) && $auftrag_position_id > 0){ + $lieferschein_posid = $this->app->DB->Select("SELECT id FROM lieferschein_position WHERE auftrag_position_id='$auftrag_position_id' AND auftrag_position_id <> 0 ORDER BY lieferschein = '$lieferschein' DESC LIMIT 1"); + } + if(!$lieferschein_posid) + { + $lieferschein_posarr = $this->app->DB->SelectArr("SELECT lieferschein_position_id FROM `sammelrechnung_position` WHERE rechnung_position_id = '$posid' AND lieferschein_position_id <> 0 AND menge <> 0"); + if(!empty($lieferschein_posarr)) + { + $lieferschein_posid = null; + foreach($lieferschein_posarr as $v) + { + $lieferschein_posid[] = $v['lieferschein_position_id']; + } + if(!empty($lieferschein_posid) && count($lieferschein_posid) === 1) + { + $lieferschein_posid = reset($lieferschein_posid); + if($lieferschein_posid){ + $lieferschein = $this->app->DB->Select("SELECT lieferschein FROM lieferschein_position WHERE id = '$lieferschein_posid' LIMIT 1"); + } + } + } + } + }else{ + if(!empty($auftrag_position_id) && $auftrag_position_id > 0){ + $lieferschein_posid = $this->app->DB->Select("SELECT id FROM lieferschein_position WHERE auftrag_position_id='$auftrag_position_id' AND auftrag_position_id <> 0 LIMIT 1"); + } + } + if($type === 'sn' && ($doctype === 'lieferschein' || $doctype === 'rechnung' || $doctype === 'gutschrift')) + { + if(!empty($tmp)) + { + $ctmp = count($tmp); + for($i=0;$i<$ctmp;$i++) + { + $tmp_string[]=$tmp[$i]['seriennummer']; + } + } + } + + $belegPosCharge = $this->getStyleElement('beleg_pos_charge'); + $belegPosMhd = $this->getStyleElement('beleg_pos_mhd'); + if($returnSimpleString) { + $belegPosCharge = 1; + $belegPosMhd = 1; + } + if($belegPosCharge=='1' + && $belegPosMhd =='1') { + if($type === 'mhd') + { + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' + GROUP by wert,wert2"); + if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) + { + if(is_array($lieferschein_posid)) + { + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND pos in (".implode(', ',$lieferschein_posid ).") + GROUP by wert,wert2"); + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 ,type2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' + GROUP by wert,wert2"); + } + } + + }elseif($type === 'charge') + { + if($returnSimpleString) { + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + WHERE bc1.type='$type' AND bc1.doctype='$doctype' AND bc1.doctypeid='$doctypeid' AND bc1.pos='$posid' + GROUP by bc1.wert"); + } + else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + LEFT JOIN beleg_chargesnmhd bc2 + ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz + AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert + WHERE bc1.type='$type' AND bc1.doctype='$doctype' AND bc1.doctypeid='$doctypeid' AND bc1.pos='$posid' AND isnull(bc2.id) + GROUP by bc1.wert"); + } + if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) + { + if($returnSimpleString) { + if(is_array($lieferschein_posid)){ + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND + bc1.pos in ('" . implode(', ', $lieferschein_posid) . "') + GROUP by bc1.wert"); + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.doctypeid='$lieferschein' + AND bc1.pos='$lieferschein_posid' + GROUP by bc1.wert"); + } + } + else{ + if(is_array($lieferschein_posid)){ + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + LEFT JOIN beleg_chargesnmhd bc2 + ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz + AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert + WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.pos in ('" . implode(', ', $lieferschein_posid) . "') AND isnull(bc2.id) + GROUP by bc1.wert"); + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(bc1.menge) as menge,bc1.wert + FROM beleg_chargesnmhd bc1 + LEFT JOIN beleg_chargesnmhd bc2 + ON bc1.doctype = bc2.doctype AND bc1.doctypeid = bc2.doctypeid AND bc1.pos = bc2.pos AND bc1.lagerplatz = bc2.lagerplatz + AND bc2.type = 'mhd' AND bc2.type2 = 'charge' AND bc2.wert2 = bc1.wert + WHERE bc1.type='$type' AND bc1.doctype='lieferschein' AND bc1.doctypeid='$lieferschein' AND bc1.pos='$lieferschein_posid' AND isnull(bc2.id) + GROUP by bc1.wert"); + } + } + } + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' + GROUP by wert"); + if(empty($tmp) && $lieferschein && $lieferschein_posid) + { + if(is_array($lieferschein_posid)) + { + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND pos in ('".implode(', ',$lieferschein_posid )."') + GROUP by wert"); + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' + GROUP by wert"); + } + } + } + if(!empty($tmp)){ + $ctmp = count($tmp); + for ($i = 0; $i < $ctmp; $i++) { + if($type === 'mhd' && $tmp[$i]['wert'] != ""){ + $tmp[$i]['wert'] = ($i > 0 ? $this->app->erp->Beschriftung('dokument_mhd') . ': ' : '') . date('d.m.Y', strtotime($tmp[$i]['wert'])); + if($tmp[$i]['wert2'] != '' && $tmp[$i]['type2'] === 'charge') { + $tmp[$i]['wert'] .= ' ' . $this->app->erp->Beschriftung('dokument_charge') . ': ' . $tmp[$i]['wert2']; + } + }elseif($type === 'charge'){ + if($i > 0) { + $tmp[$i]['wert'] = $this->app->erp->Beschriftung('dokument_charge') . ': ' . $tmp[$i]['wert']; + } + }elseif($type === 'sn'){ + if($i > 0) { + $tmp[$i]['wert'] = $this->app->erp->Beschriftung('dokument_seriennummer') . ': ' . $tmp[$i]['wert']; + } + } + if($tmp[$i]['menge'] > 1) { + $tmp[$i]['menge'] = ' (' . (float)$tmp[$i]['menge'] . ')'; + }else { + $tmp[$i]['menge'] = ''; + } + $tmp_string[] = $tmp[$i]['wert'] . $tmp[$i]['menge']; + } + } + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='$doctype' AND doctypeid='$doctypeid' AND pos='$posid' + GROUP by wert"); + if(empty($tmp) && $doctype === 'rechnung' && $lieferschein && $lieferschein_posid) + { + if(is_array($lieferschein_posid)) + { + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND pos in ('".implode(', ',$lieferschein_posid )."') + GROUP by wert"); + }else{ + $tmp = $this->app->DB->SelectArr("SELECT SUM(menge) as menge,wert, wert2 + FROM beleg_chargesnmhd + WHERE type='$type' AND doctype='lieferschein' AND doctypeid='$lieferschein' AND pos='$lieferschein_posid' + GROUP by wert"); + } + } + + if(!empty($tmp)){ + $ctmp = count($tmp); + for ($i = 0; $i < $ctmp; $i++) { + if($type === 'mhd' && $tmp[$i]['wert'] != ''){ + $tmp[$i]['wert'] = + ($i > 0 && !$returnSimpleString ? $this->app->erp->Beschriftung('dokument_mhd') . ': ' : '') . + date('d.m.Y', strtotime($tmp[$i]['wert'])); + } + elseif($type === 'charge'){ + if($i > 0) { + $tmp[$i]['wert'] = (!$returnSimpleString?$this->app->erp->Beschriftung('dokument_charge') . ': ':'') . $tmp[$i]['wert']; + } + } + elseif($type === 'sn'){ + if($i > 0) { + $tmp[$i]['wert'] = (!$returnSimpleString?$this->app->erp->Beschriftung('dokument_seriennummer') . ': ':'') . $tmp[$i]['wert']; + } + } + if($tmp[$i]['menge'] > 1) { + $tmp[$i]['menge'] = ' (' . (float)$tmp[$i]['menge'] . ')'; + } + else { + $tmp[$i]['menge'] = ''; + } + $tmp_string[] = $tmp[$i]['wert'] . $tmp[$i]['menge']; + } + } + } + + if(!empty($tmp_string)){ + if($returnSimpleString) { + return implode(', ', $tmp_string); + } + return implode("\r\n",$tmp_string); + } + return ''; + } + + function CheckPosition($value,$doctype,$doctypeid,$posid) + { + // ean + if($this->getStyleElement('beleg_pos_ean')=='1') + { + $ean = $this->app->DB->Select("SELECT ean FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); + if($ean!='') { + $tmpvalue['ean'] = $this->app->erp->Beschriftung('dokument_ean').': '.$ean; + } + } + + // zolltarif // check ust id + $ust_befreit = $this->app->DB->Select("SELECT ust_befreit FROM $doctype WHERE id='$doctypeid' LIMIT 1"); + if(($ust_befreit==2 && ($doctype=='rechnung' || $doctype=='gutschrift')) || + ($doctype!='proformarechnung' && $this->getStyleElement('beleg_pos_zolltarifnummer')=='1')) + { + if($value['zolltarifnummer']=='' || $value['zolltarifnummer']==0) { + $value['zolltarifnummer'] = $this->app->DB->Select("SELECT zolltarifnummer FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); + } + if($value['herkunftsland']=='' || $value['herkunftsland']==0) { + $value['herkunftsland'] = $this->app->DB->Select("SELECT herkunftsland FROM artikel WHERE id='".$value['artikel']."' LIMIT 1"); + } + } else { + $value['zolltarifnummer']=''; + $value['herkunftsland']=''; + } + + if($this->getStyleElement('beleg_pos_herkunftsland')=='1') + { + $value['herkunftsland']=''; + } + + $this->mhd[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('mhd',$doctype,$doctypeid,$posid); + // mhd + if($this->getStyleElement('beleg_pos_mhd')=='1') + { + $mhd=$this->mhd[$doctype][$doctypeid][$posid];//$this->GetChargeMHDSNString('mhd',$doctype,$doctypeid,$posid); + if(strpos($value['beschreibung'], '{MHD}') !== false) { + $value['beschreibung'] = str_replace( + '{MHD}', + $mhd, + $value['beschreibung'] + ); + } + if($mhd!='') { + $tmpvalue['mhd'] = $this->app->erp->Beschriftung('dokument_mhd').': '.$mhd; + } + } + + $this->charge[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('charge',$doctype,$doctypeid,$posid); + // charge + if($this->getStyleElement('beleg_pos_charge')=='1') + { + $charge=$this->charge[$doctype][$doctypeid][$posid]; + if(strpos($value['beschreibung'], '{CHARGE}') !== false) { + $value['beschreibung'] = str_replace( + '{CHARGE}', + $charge, + $value['beschreibung'] + ); + } + if($charge!='') { + $tmpvalue['charge'] = $this->app->erp->Beschriftung('dokument_charge').': '.$charge; + } + } + + $this->sn[$doctype][$doctypeid][$posid] = $this->GetChargeMHDSNString('sn',$doctype,$doctypeid,$posid); + // sn + if($this->getStyleElement('beleg_pos_sn')=='1') + { + $seriennr=$this->sn[$doctype][$doctypeid][$posid]; + if(strpos($value['beschreibung'], '{SN}') !== false) { + $value['beschreibung'] = str_replace( + '{SN}', + $seriennr, + $value['beschreibung'] + ); + } + if($seriennr!='') { + $tmpvalue['sn'] = $this->app->erp->Beschriftung('dokument_seriennummer').': '.$seriennr; + $value['seriennummer']=''; + } + } + + if(!empty($tmpvalue)) { + if($value['beschreibung']!=''){ + $value['beschreibung'] = $value['beschreibung'] . "\r\n" . implode("\r\n", $tmpvalue); + } + else{ + $value['beschreibung'] = implode("\r\n", $tmpvalue); + } + } + return $value; + } + + + + + public function addItem($rdata){ + // add rabatt + if($rdata['price']!='-'){ + if($rdata['rabatt'] == 100){ + $rdata['tprice'] = round($rdata['amount'] * ((double)$rdata['price'] - (double)($rdata['price'] / 100.00 * (double)$rdata['rabatt'])), 13); + }else{ + $rdata['tprice'] = $rdata['amount'] * ((double)$rdata['price'] - (double)($rdata['price'] / 100.00 * (double)$rdata['rabatt'])); + } + } + else { + $rdata['tprice']='-'; + } + $this->items[]=$rdata; + } + + public function setSender($rdata){ + $this->sender['enterprise'] = $this->app->erp->ReadyForPDF($rdata[0]); + $this->sender['firstname'] = $this->app->erp->ReadyForPDF($rdata[1]); + $this->sender['familyname'] = $this->app->erp->ReadyForPDF($rdata[2]); + $this->sender['address1'] = $this->app->erp->ReadyForPDF($rdata[3]); + $this->sender['areacode'] = $this->app->erp->ReadyForPDF($rdata[4]); + $this->sender['city'] = $this->app->erp->ReadyForPDF($rdata[5]); + if(isset($rdata[6])){ + $this->sender['country'] = $this->app->erp->ReadyForPDF($rdata[6]); + } + } + + function setRecipientRechnung($id) + { + + + } + + + function setRecipientLieferadresse($id,$table) + { + $this->id = $id; + $this->table = $table; + + if($table == 'serviceauftrag'){ + $adressid = $this->app->DB->Select("SELECT adresse FROM serviceauftrag WHERE id = '$id' LIMIT 1"); + if($adressid != "" && $adressid > 0){ + $tmp = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$adressid' LIMIT 1"); + } + }else{ + $tmp = $this->app->DB->SelectArr("SELECT * FROM $table WHERE id='$id' LIMIT 1"); + } + + $titelansprechpartner=""; + $titelname=""; + + if($tmp[0]['ansprechpartner']!='' && $tmp[0]['titel']!='') + { + $titelansprechpartner = $tmp[0]['titel'].' '; + } + else if ($tmp[0]['titel']!='') { + $titelname = $tmp[0]['titel'].' '; + } + + if($table != 'serviceauftrag'){ + if($tmp[0]['typ']==''){ + $tmp[0]['typ'] = $this->app->DB->Select("SELECT typ FROM adresse WHERE id='" . $tmp[0]['adresse'] . "' LIMIT 1"); + } + } + + $check = $this->app->DB->Select("SELECT bezeichnung FROM adresse_typ WHERE type='".$tmp[0]['typ']."' LIMIT 1"); + + if($check!="") + $this->recipient['anrede'] = $this->app->erp->ReadyForPDF($check); + else + $this->recipient['anrede'] = $this->app->erp->ReadyForPDF(ucfirst($tmp[0]['typ'])); + + + if($tmp[0]['typ']!="person") + { + $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($titelname.$tmp[0]['name']); + + + if($tmp[0]['abteilung']!='' && strlen($tmp[0]['abteilung']) >1){ + $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['abteilung']); + } + + if($tmp[0]['ansprechpartner']!='' && strlen($tmp[0]['ansprechpartner'])>1){ + $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($titelansprechpartner . $tmp[0]['ansprechpartner']); + } + + if(($table=='rechnung' || $table=='gutschrift') && $this->getStyleElement('rechnung_gutschrift_ansprechpartner')!='1'){ + $this->recipient['firstname'] = ''; + } + else if(($table=='angebot' || $table=='auftrag' || $table=='bestellung') && $this->getStyleElement('angebot_auftrag_bestellung_ansprechpartner')!='1'){ + $this->recipient['firstname'] = ''; + } + + + if($tmp[0]['unterabteilung']!=''){ + $this->recipient['address3'] = $this->app->erp->ReadyForPDF($tmp[0]['unterabteilung']); + } + + if($tmp[0]['adresszusatz']!=''){ + $this->recipient['address4'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); + } + + } + + else { + $vorname = ''; + if(isset($tmp[0]['vorname']) && $tmp[0]['vorname']!='' && strlen(trim($tmp[0]['vorname']))>0){ + $vorname = $tmp[0]['vorname'] . ' '; + } + + $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($vorname.$tmp[0]['name']); + $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); + } + + + $this->recipient['address1'] = $this->app->erp->ReadyForPDF($tmp[0]['strasse']); + $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($tmp[0]['plz']); + $this->recipient['city'] = $this->app->erp->ReadyForPDF($tmp[0]['ort']); + //if($this->recipient['city']!="") + $this->recipient['country'] = $this->app->erp->ReadyForPDF($tmp[0]['land']); + } + + + function setRecipientDB($adresse) + { + $tmp = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$adresse' LIMIT 1"); + if($tmp[0]['typ']!="person") + { + $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($tmp[0]['name']); + + if($tmp[0]['abteilung']!='' && strlen($tmp[0]['abteilung'])>1){ + $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['abteilung']); + } + + + $tmp[0]['anrede'] = $this->app->DB->Select("SELECT anrede FROM adresse WHERE id='".$tmp[0]['id']."' LIMIT 1"); + $check = $this->app->DB->Select("SELECT bezeichnung FROM adresse_typ WHERE type='".$tmp[0]['anrede']."' LIMIT 1"); + + if($check!=''){ + $this->recipient['anrede'] = $this->app->erp->ReadyForPDF($check); + } + else{ + $this->recipient['anrede'] = $this->app->erp->ReadyForPDF(ucfirst($tmp[0]['anrede'])); + } + + + if(($this->table=='rechnung' || $this->table=='gutschrift') && $this->getStyleElement('rechnung_gutschrift_ansprechpartner')=='1') + { + if($tmp[0]['ansprechpartner']!=''){ + $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($tmp[0]['ansprechpartner']); + } + } + else if(($this->table=='angebot' || $this->table=='auftrag' || $this->table=='bestellung') && $this->getStyleElement("angebot_auftrag_bestellung_ansprechpartner")=='1') + { + if($tmp[0]['ansprechpartner']!=''){ + $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($tmp[0]['ansprechpartner']); + } + } + + + if($tmp[0]['unterabteilung']!=''){ + $this->recipient['address3'] = $this->app->erp->ReadyForPDF($tmp[0]['unterabteilung']); + } + + if($tmp[0]['adresszusatz']!=''){ + $this->recipient['address4'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); + } + + } + + else { + $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($tmp[0]['name']); + $this->recipient['address2'] = $this->app->erp->ReadyForPDF($tmp[0]['adresszusatz']); + } + + + $this->recipient['address1'] = $this->app->erp->ReadyForPDF($tmp[0]['strasse']); + $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($tmp[0]['plz']); + $this->recipient['city'] = $this->app->erp->ReadyForPDF($tmp[0]['ort']); + //if($this->recipient['city']!="") + $this->recipient['country'] = $this->app->erp->ReadyForPDF($tmp[0]['land']); + } + + + public function setRecipient($rdata){ + $this->recipient['enterprise'] = $this->app->erp->ReadyForPDF($rdata[0]); + $this->recipient['firstname'] = $this->app->erp->ReadyForPDF($rdata[1]); + $this->recipient['familyname'] = $this->app->erp->ReadyForPDF($rdata[2]); + $this->recipient['address1'] = $this->app->erp->ReadyForPDF($rdata[3]); + $this->recipient['areacode'] = $this->app->erp->ReadyForPDF($rdata[4]); + $this->recipient['city'] = $this->app->erp->ReadyForPDF($rdata[5]); + if(isset($rdata[3]))$this->recipient['country'] = $this->app->erp->ReadyForPDF($rdata[6]); + } + + public function setCorrDetails($rdata, $onlyData = false){ + if($onlyData) { + $this->corrDetails = $rdata; + return; + } + + if($this->getStyleElement("projektnummerimdokument")=='1'){ + $rdata[$this->app->erp->Beschriftung("dokument_projekt")] = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='" . $this->projekt . "' LIMIT 1"); + } + + if($this->getStyleElement("internetnummerimbeleg")=='1') + { + switch($this->doctype) + { + case "rechnung": + case "lieferschein": + $internetnummer = $this->app->DB->Select("SELECT a.internet FROM auftrag a LEFT JOIN ".$this->doctype." b ON b.auftragid=a.id WHERE b.id='".$this->doctypeid."' LIMIT 1"); + break; + case "gutschrift": + $internetnummer = $this->app->DB->Select("SELECT a.internet FROM gutschrift g LEFT JOIN rechnung r ON r.id=g.rechnungid LEFT JOIN auftrag a ON a.id=r.auftragid WHERE g.id='".$this->doctypeid."' LIMIT 1"); + break; + case "auftrag": + $internetnummer = $this->app->DB->Select("SELECT internet FROM auftrag WHERE id='".$this->doctypeid."' LIMIT 1"); + break; + default: + $internetnummer = ''; + + } + //$rdata[$this->getStyleElement("beschriftunginternetnummer")]=$internetnummer; + $rdata[$this->app->erp->Beschriftung("beschriftunginternetnummer")]=$internetnummer; + } + if($this->doctype=="rechnung"||$this->doctype=="lieferschein"||$this->doctype=="gutschrift"||$this->doctype=="auftrag"||$this->doctype=="angebot"||$this->doctype=="lieferschein") + { + if($this->doctype=='lieferschein'){ + $tabelle='lieferschein'; + }else { + $tabelle=$this->doctype; + } +// $bearbeiteremail = $this->app->DB->Select("SELECT b.email FROM ".$this->doctype." a LEFT JOIN adresse adr ON a.adresse=adr.id LEFT JOIN adresse b ON b.id=adr.innendienst WHERE a.id='".$this->doctypeid."' LIMIT 1"); + // $bearbeitertelefon = $this->app->DB->Select("SELECT b.telefon FROM ".$this->doctype." a LEFT JOIN adresse adr ON a.adresse=adr.id LEFT JOIN adresse b ON b.id=adr.innendienst WHERE a.id='".$this->doctypeid."' LIMIT 1"); + + $bearbeiteremail = $this->app->DB->Select("SELECT b.email FROM ".$tabelle." a LEFT JOIN adresse b ON b.id=a.bearbeiterid WHERE a.id='".$this->doctypeid."' LIMIT 1"); + $bearbeitertelefon = $this->app->DB->Select("SELECT b.telefon FROM ".$tabelle." a LEFT JOIN adresse b ON b.id=a.bearbeiterid WHERE a.id='".$this->doctypeid."' LIMIT 1"); + } + + if($this->getStyleElement('bearbeiteremailimdokument')=='1'){ + $rdata[$this->app->erp->Beschriftung('dokument_email')] = $bearbeiteremail; + } + if($this->getStyleElement('bearbeitertelefonimdokument')=='1'){ + $rdata[$this->app->erp->Beschriftung('dokument_telefon')] = $bearbeitertelefon; + } + + + //$rdata[$this->getStyleElement("beschriftungbearbeiteremail")]=$internetnummer; + //$rdata[$this->getStyleElement("beschriftungbearbeitertelefonnummer")]=$internetnummer; + + $this->corrDetails = $rdata; + } + public function setBoldCorrDetails($rdata){ + $this->boldCorrDetails = $rdata; + } + + public function setItalicBoldCorrDetails($rdata){ + $this->italicBoldCorrDetails = $rdata; + } + + public function setItalicCorrDetails($rdata){ + $this->italicCorrDetails = $rdata; + } + + public function setTextDetails($rdata){ + $this->textDetails = $rdata; + } + + + public function setTotals($rdata){ + $this->totals = $rdata; + } + + // Briefpapier festlegen + public function setStationery($stationeryfile) { + $this->setSourceFile($stationeryfile); + $tplidx = $this->ImportPage(1); + $this->useTemplate($tplidx); + } + /* + public function setLogo($logofile) { + $this->logofile = "./lib/pdf/images/".$logofile; + } + */ + + // label settings + public function setBarcode($barcode) { + $barcode = preg_replace('/[^0-9a-zA-Z\-]/', '', $barcode); + if($this->barcode_sichtbar) + $this->barcode = $barcode; + else $this->barcode=""; + + } + + + public function Header() { + if($this->knickfalz!='1'){ + $this->Line(0,105,5,105); + $this->Line(0,148,7,148); + $this->Line(0,210,5,210); + } + if($this->logofile!='') + $this->Image($this->logofile,15,10,110); + + if($this->barcode!='' && $this->briefpapier==''){ + //$this->Rotate(90); + $this->Code39($this->barcode_x, $this->barcode_y, $this->barcode, 1, 3); + //$this->Rotate(0); + } + + if($this->briefpapier!='' && $this->PageNo()<=1) + $this->setStationery($this->briefpapier); + + // wenn + if($this->PageNo() > 1 && $this->briefpapier2!='' && $this->briefpapier2vorhanden=='1'){ + if($this->doctype != 'produktion'){ + $this->setStationery($this->briefpapier2); + } + } + else if ( $this->PageNo() > 1 && $this->briefpapier!=''){ + $this->setStationery($this->briefpapier); + } + + + if($this->PageNo() > 1) + { + $this->SetY($this->abseite2y); + } + } + + public function Footer() { + $differenz=12; + $this->SetXY(12,$this->getStyleElement("abstand_seiten_unten")*-1); + $this->SetFont($this->GetFont(),'',8); + + + if($this->seite_von_sichtbar!="1") + { + if($this->getStyleElement("seite_von_ausrichtung_relativ")=="1")// && $this->seite_von_ausrichtung=="C") + { + $this->SetX($this->getStyleElement("abstand_seitenrandlinks")); + $differenz = $this->getStyleElement("abstand_seitenrandlinks"); + } + + $tmp = $this->rMargin; + if($this->getStyleElement("abstand_seitenrandrechts")>0) + $this->rMargin=$this->getStyleElement("abstand_seitenrandrechts"); + else + $this->rMargin=$this->getStyleElement("abstand_seitenrandlinks"); + + $tmpc = $this->cMargin; + if($this->seite_von_ausrichtung=="R") + $this->cMargin=-3; + + if($this->getStyleElement("seite_belegnr")) + $this->Cell(0,8,$this->app->erp->Beschriftung("dokument_seite").' '.$this->PageNo().' '.$this->app->erp->Beschriftung("dokument_seitevon").' {nb} '.$this->zusatzfooter,0,0,$this->seite_von_ausrichtung); + else + $this->Cell(0,8,$this->app->erp->Beschriftung("dokument_seite").' '.$this->PageNo().' '.$this->app->erp->Beschriftung("dokument_seitevon").' {nb}',0,0,$this->seite_von_ausrichtung); + + $this->cMargin = $tmpc; + + $this->rMargin=$tmp; + } + + if($this->nichtsichtbar_footer!=true) + { + + $footerarr = $this->app->DB->SelectArr("SELECT * FROM firmendaten WHERE id='".$this->firmendatenid."' LIMIT 1"); + $firmendaten_extra = $this->app->DB->SelectArr("SELECT * FROM firmendaten_werte"); + if($firmendaten_extra) + { + foreach($firmendaten_extra as $v) + { + if(!isset($footerarr[0][$v['name']]))$footerarr[0][$v['name']] = $v['wert']; + } + } + $footerarr = $footerarr[0]; + + foreach($footerarr as $key=>$value) + $footerarr[$key] = utf8_decode($value); + + $this->SetXY(10,-26); + $this->SetDrawColor($this->getStyleElement("footer_farbe")); + $this->SetTextColor($this->getStyleElement("footer_farbe")); + + $this->SetFont($this->GetFont(),'',7); + + + if($this->getStyleElement("footer_zentriert")!=1) + { + $this->MultiCell($footerarr['footer_breite1'],3,utf8_encode(" ".$footerarr['footer_0_0']."\n ".$footerarr['footer_0_1']."\n ".$footerarr['footer_0_2']."\n ".$footerarr['footer_0_3']."\n ".$footerarr['footer_0_4']."\n ".$footerarr['footer_0_5'].""),'','L'); + $this->SetXY($footerarr['footer_breite1'] + 10,-26); // Breite 1 + 10 + $this->MultiCell($footerarr['footer_breite2'],3,utf8_encode(" ".$footerarr['footer_1_0']."\n ".$footerarr['footer_1_1']."\n ".$footerarr['footer_1_2']."\n ".$footerarr['footer_1_3']."\n ".$footerarr['footer_1_4']."\n ".$footerarr['footer_1_5'].""),'','L'); + $this->SetXY($footerarr['footer_breite1'] + $footerarr['footer_breite2'] + 10,-26); //breite 1 + breite 2 + 10 + $this->MultiCell($footerarr['footer_breite3'],3,utf8_encode(" ".$footerarr['footer_2_0']."\n ".$footerarr['footer_2_1']."\n ".$footerarr['footer_2_2']."\n ".$footerarr['footer_2_3']."\n ".$footerarr['footer_2_4']."\n ".$footerarr['footer_2_5'].""),'','L'); + $this->SetXY($footerarr['footer_breite1'] + $footerarr['footer_breite2'] + $footerarr['footer_breite3'] + 10,-26); //breite 1 + breite 2 + breite 3 + 10 + $this->MultiCell($footerarr['footer_breite4'],3,utf8_encode(" ".$footerarr['footer_3_0']."\n ".$footerarr['footer_3_1']."\n ".$footerarr['footer_3_2']."\n ".$footerarr['footer_3_3']."\n ".$footerarr['footer_3_4']."\n ".$footerarr['footer_3_5'].""),'','L'); + } else { + $this->MultiCell(0,3,utf8_encode(" ".$footerarr['footer_0_0']."\n ".$footerarr['footer_0_1']."\n ".$footerarr['footer_0_2']."\n ".$footerarr['footer_0_3']."\n ".$footerarr['footer_0_4']."\n ".$footerarr['footer_0_5'].""),'','C'); + + + } + } + } + + /** + * @param string $parameter + * + * @return array|null + */ + protected function getOldDocument(string $parameter): ?array + { + return $this->app->DB->SelectRow( + "SELECT * + FROM `pdfarchiv` + WHERE `table_id` = '".$this->id."' + AND `table_name` = '".$this->table."' + AND `doctype` = '".$this->app->DB->real_escape_string($this->doctype)."' + AND `doctypeorig` = '".$this->app->DB->real_escape_string($this->doctypeOrig)."' + AND CHAR_LENGTH(`belegnummer`) > 2 + AND `belegnummer` <> 'SAB' + AND `parameter` = '$parameter' + AND `keinhintergrund` = '".($this->app->erp->BriefpapierHintergrunddisable?'1':'0')."' + ORDER BY `zeitstempel` DESC + LIMIT 1" + ); + } + + /** + * @param string $path + * + * @return bool + */ + protected function checkAndUpdateDocumentName(string $path): bool + { + if(!file_exists($path)){ + return false; + } + $pathInfos = explode('_', basename($path),3); + $md5 = md5_file($path); + if($md5 === $pathInfos[0]){ + return false; + } + + return $this->updateDocumentEntry($pathInfos, $md5,$path); + } + + /** + * @param array $fileInfos + * @param string $md5 + * @param string $filePath + */ + protected function updateDocumentEntry(array $fileInfos, string $md5, string $filePath): bool + { + $fileName = basename($filePath); + $dir = dirname($filePath); + $newFileName = $md5 . '_' . explode('_', basename($filePath),2)[1]; + $newFilePath = $dir . '/' . $newFileName; + $tableId = $fileInfos[1]; + if(file_exists($newFilePath)){ + $this->checkAndUpdateDocumentName($newFilePath); + } + if(file_exists($newFilePath)){ + return false; + } + + $this->updatePdfArchiveEntry((int)$tableId, $md5, $newFileName, $fileName); + rename($dir . '/' . $fileName, $newFilePath); + + return true; + } + + /** + * @param int $tableId + * @param string $md5 + * @param string $newFileName + * @param string $oldFilename + */ + protected function updatePdfArchiveEntry(int $tableId, string $md5, string $newFileName, string $oldFilename): void + { + $this->app->DB->Update( + "UPDATE `pdfarchiv` + SET `checksum` = '{$md5}', `dateiname` = '{$newFileName}' + WHERE `dateiname` = '{$oldFilename}' AND `table_id` = {$tableId} AND `table_name` = '{$this->table}'" + ); + } + + /** + * @param string $checkSum + * @param string $fileName + * @param string $documentNumber + * @param string $parameter + * + * @return int + */ + protected function createPdfArchiveEntry( + string $checkSum, string $fileName, string $documentNumber, string $parameter = '' + ): int + { + $userName = $this->app->DB->real_escape_string($this->app->User->GetName()); + $documentType = $this->app->DB->real_escape_string($this->doctype); + $originalDocumentType = $this->app->DB->real_escape_string($this->doctypeOrig); + $documentNumber = $this->app->DB->real_escape_string($documentNumber); + $parameter = $this->app->DB->real_escape_string($parameter); + $noBackGround = $this->app->erp->BriefpapierHintergrunddisable ? 1 : 0; + $this->app->DB->Insert( + "INSERT INTO `pdfarchiv` + ( + `schreibschutz`, `zeitstempel`, `checksum`, `table_id`, `table_name`, `bearbeiter`, + `erstesoriginal`, `doctype`, `doctypeorig`, `dateiname`, + `belegnummer`, `keinhintergrund`, `parameter` + ) + VALUES + ( + 1, NOW(), '{$checkSum}', '{$this->id}', '{$this->table}', '{$userName}', + 0, '{$documentType}', '{$originalDocumentType}', '{$fileName}', + '{$documentNumber}', '{$noBackGround}', '{$parameter}' + )" + ); + + return (int)$this->app->DB->GetInsertID(); + } + + /** + * @param false $schreibschutz + * @param false $force + * @param string $parameter + */ + public function ArchiviereDocument($schreibschutz = false, $force = false, $parameter = ''): void + { + if(!$schreibschutz){ + $schreibschutz = (bool)$this->app->DB->Select( + "SELECT `schreibschutz` FROM `{$this->table}` WHERE `id` = '{$this->id}' LIMIT 1" + ); + } + + if($parameter == ''){ + $parameter = $this->parameter; + } + + if($this->ausarchiv){ + return; + } + + $isDraft = $this->app->DB->Select( + "SELECT `id` FROM `{$this->table}` WHERE `id` = '{$this->id}' AND `belegnr` <> '' AND `belegnr` <> '0' LIMIT 1" + ) === null; + + if($isDraft){ + return; + } + + if($force) { + $this->app->DB->Update("UPDATE `{$this->table}` SET `schreibschutz` = 1 WHERE `id` = '{$this->id}' LIMIT 1"); + $schreibschutz = true; + } + + if(!$schreibschutz){ + return; + } + + $this->filename = $this->app->erp->Dateinamen($this->filename); + $dir = rtrim($this->app->Conf->WFuserdata, '/') . '/pdfarchiv/' . $this->app->Conf->WFdbname . '/' . $this->table; + if(!is_dir($dir) && !mkdir($dir, 0700,true) && !is_dir($dir)){ + $this->app->erp->LogFile('Fehler beim erstellen von '.$dir); + return; + } + + $dir = dirname(Briefpapier::getPDFfolder($dir, $this->id, $this->id . '_' . $this->filename, false, true)); + $absoluteFilePath = $dir . '/' .$this->id . '_' . $this->filename; + + $oldDocument = $this->getOldDocument((string)$parameter); + $isOldDocumentFileExists = !empty($oldDocument['dateiname']) && is_file($dir . '/' . $oldDocument['dateiname']); + $hasOldDocumentFileMd5Sum = $isOldDocumentFileExists + && !empty($oldDocument['checksum']) + && strpos($oldDocument['dateiname'], $oldDocument['checksum']) ===0; + if($hasOldDocumentFileMd5Sum) { + $oldFile = $dir . '/' . $oldDocument['dateiname']; + if($this->checkAndUpdateDocumentName($oldFile)) { + $oldDocument = $this->getOldDocument((string)$parameter); + $isOldDocumentFileExists = !empty($oldDocument['dateiname']) && is_file($dir . '/' . $oldDocument['dateiname']); + } + } + $oldFile = $isOldDocumentFileExists ? $dir . '/' . $oldDocument['dateiname'] : null; + if($oldFile !== null && !$force) { + return; + } + $documentNumber = str_ireplace('.pdf', '', substr($this->filename, strrpos($this->filename, '_') + 1)); + // If the current document file does not exist + if(!file_exists($absoluteFilePath)){ + // save this document to file + $this->Output($absoluteFilePath, 'F'); + if(empty($oldDocument) || $oldDocument['dateiname'] !== basename($absoluteFilePath)) { + $this->createPdfArchiveEntry( + md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter + ); + } + $this->resetToArchiveFlag(); + return; + } + // create a new temp file + $tempFilePath = $dir . '/' .$this->id . '_temp' . $this->filename; + $this->Output($tempFilePath, 'F'); + if($oldFile !== null && $this->areFilesEqualExceptCreationDate($oldFile, $tempFilePath)) { + unlink($tempFilePath); + $this->resetToArchiveFlag(); + return; + } + $md5CurrentFile = md5_file($absoluteFilePath); + // and compare with existing file + if($this->areFilesEqualExceptCreationDate($absoluteFilePath, $tempFilePath)){ + //if($md5CurrentFile === md5_file($tempFilePath)){ + // If same, delete temp file and + unlink($tempFilePath); + $this->resetToArchiveFlag(); + return; + } + // build the file name with md5_hash + $md5FileName = $dir . '/' . $md5CurrentFile . '_' . $this->id . '_' . $this->filename; + // check if the file exists + $this->checkAndUpdateDocumentName($md5FileName); + if(!file_exists($md5FileName)){ + rename($absoluteFilePath, $md5FileName); + $this->updatePdfArchiveEntry($this->id, $md5CurrentFile, basename($md5FileName), basename($absoluteFilePath)); + + rename($tempFilePath, $absoluteFilePath); + $this->createPdfArchiveEntry( + md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter + ); + $this->resetToArchiveFlag(); + return; + } + if($this->areFilesEqualExceptCreationDate($absoluteFilePath, $md5FileName)){ + rename($tempFilePath, $absoluteFilePath); + $this->createPdfArchiveEntry( + md5_file($absoluteFilePath), basename($absoluteFilePath), $documentNumber, (string)$parameter + ); + $this->resetToArchiveFlag(); + return; + } + + unlink($tempFilePath); + $this->resetToArchiveFlag(); + } + + /** + * resolve to-archive request for document, after creating new pdf-file + */ + public function resetToArchiveFlag(): void + { + if(empty($this->id) || empty($this->table)) { + return; + } + $this->app->DB->Update("UPDATE `{$this->table}` SET `zuarchivieren` = 0 WHERE `id` = {$this->id} LIMIT 1"); + } + + /** + * @param string $firstFilePath + * @param string $secondFilePath + * @return bool + */ + public function areFilesEqualExceptCreationDate(string $firstFilePath, string $secondFilePath) + { + if(!file_exists($firstFilePath) || !file_exists($secondFilePath)){ + return false; + } + + $pattern = '#CreationDate \(D:[0-9]+\)#'; + + $contentFirstFile = preg_replace($pattern, '', @file_get_contents($firstFilePath)); + $contentSecondFile = preg_replace($pattern, '', @file_get_contents($secondFilePath)); + + return md5($contentFirstFile) === md5($contentSecondFile); + } + + public function DocumentArchiviert() + { + $this->filename = $this->app->erp->Dateinamen($this->filename); + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname; + if(!is_dir($dir)){ + return false; + } + if(!is_dir($dir.'/'.$this->table)){ + return false; + } + + $md5alt = false; + $altesdokument = $this->app->DB->SelectRow("SELECT * from pdfarchiv where table_id = '".$this->id."' and table_name = '".$this->table."' AND doctype = '".$this->app->DB->real_escape_string($this->doctype)."' AND doctypeorig = '".$this->app->DB->real_escape_string($this->doctypeOrig)."' AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND parameter = '".$this->parameter."' ORDER BY zeitstempel DESC LIMIT 1"); + if(empty($altesdokument)){ + return false; + } + + $md5alt = $altesdokument['checksum']; + if(!file_exists($dir.'/'.$this->table.'/'.$md5alt.'_'.$this->id.'_'.$this->filename)) { + $file = Briefpapier::getPDFfolder($dir.'/'.$this->table, $this->id,$md5alt.'_'.$this->id.'_'.$this->filename); + if(!file_exists($file)){ + return false; + } + } + + $this->Output($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename,'F'); + $md5sum_tmp = md5_file($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename); + unlink($dir.'/'.$this->table.'/TEMP_'.$this->id.'_'.$this->filename); + return $md5sum_tmp == $md5alt; + } + + + public function archiveDocument($parameter = '') + { + if($this->table && $this->id) + { + $this->ArchiviereDocument($this->app->DB->Select('SELECT schreibschutz FROM `'.trim($this->app->DB->real_escape_string($this->table))."` WHERE id = '".(int)$this->id."' LIMIT 1")?true:false,false, $parameter); + }else{ + $this->ArchiviereDocument(); + } + } + + public static function getPDFfolder($folder, $tableid, $file = '', $forcenew = false, $createfolder = false) + { + if($file === '') { + $file = $folder; + $folder = dirname($folder); + $file = substr($file, strlen($folder)+1); + } + if(!$forcenew && file_exists($folder.'/'.$file)) { + return $folder.'/'.$file; + } + $tableida = str_split($tableid, 1); + $newfolder = $folder. '/'.implode('/',$tableida); + if(!$createfolder) { + return $newfolder.'/'.$file; + } + + if(!is_dir($newfolder) && !mkdir($newfolder,0700,true) && !is_dir($newfolder)){ + return $folder.'/'.$file; + } + + return $newfolder.'/'.$file; + } + + public function inlineDocument($from_archiv = false) { + //$from_archiv=false; + //$filenameprefix = substr($this->filename,9,2); + $content = null; + if($from_archiv && !empty($this->table) && !empty($this->id)) { + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; + if(is_dir($dir)) { + if($this->table === 'rechnung') { + $filenameprefix = substr($this->filename,9,2); + $mirror = $this->app->DB->Select( + "SELECT dateiname + FROM pdfarchiv + WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' + ORDER BY zeitstempel DESC + LIMIT 1" + ); + } + else{ + $mirror = $this->app->DB->Select( + "SELECT dateiname + FROM pdfarchiv + WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' + ORDER BY zeitstempel DESC + LIMIT 1" + ); + } + if(!empty($mirror)) { + $file = Briefpapier::getPDFfolder($dir,$this->id, $mirror); + //if(is_file($dir.'/'.$mirror)) + if(is_file($file)) { + //$content = file_get_contents($dir.'/'.$mirror); + $content = file_get_contents($file); + if(!empty($content)) { + header('Content-type: application/pdf'); + echo $content; + $this->app->ExitXentral(); + } + } + } + } + } + + $this->renderDocument(); + $this->archiveDocument(); + header('Content-type: application/pdf'); + $this->Output(); + + $this->app->ExitXentral(); + } + + /** + * @param int $tableid + * @param string $tablename + * + * @return bool + */ + public function zuArchivieren($tableid, $tablename) + { + if($tablename) { + $check = $this->app->DB->Select("SELECT zuArchivieren FROM `$tablename` WHERE id = '$tableid'"); + } + if($check){ + return true; + } + $mirrors = $this->app->DB->SelectArr( + "SELECT * + FROM pdfarchiv + WHERE table_id = '".$tableid."' AND `table_name` = '".$tablename."' AND erstesoriginal = 0 + AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND parameter = '".$this->parameter."' + AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' + ORDER BY zeitstempel DESC" + ); + if(empty($mirrors)) { + return true; + } + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$tablename; + if(!is_dir($dir)) { + return true; + } + foreach($mirrors as $k => $mirror) { + $dateipfad = Briefpapier::getPDFfolder($dir,$tableid,$mirror['dateiname']); + if(!empty($mirror['dateiname']) && file_exists($dateipfad)) { + return false; + } + } + + return true; + } + + /** + * @param int $id + */ + public function movePDFArchiv($id) + { + + $mirrors = $id <=0?null:$this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM pdfarchiv WHERE id = %d', + $id + ) + ); + + if(empty($mirrors) || empty($mirrors['dateiname'])) { + return; + } + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$mirrors['table_name']; + if(!is_file($dir.'/'.$mirrors['dateiname'])) { + return; + } + $newfile = self::getPDFfolder($dir,$mirrors['table_id'],$mirrors['dateiname'],true,true); + if($newfile != $dir.'/'.$mirrors['dateiname'] && !is_file($newfile)) { + @rename($dir.'/'.$mirrors['dateiname'], $newfile); + } + } + + /** + * @param int $tableid + * @param string $tablename + * + * @return array|bool + */ + public function getArchivedFiles($tableid, $tablename) + { + $mirrors = $this->app->DB->SelectArr("SELECT * from pdfarchiv where table_id = '".$tableid."' and table_name = '".$tablename."' AND CHAR_LENGTH(belegnummer) > 2 AND belegnummer <> 'SAB' AND keinhintergrund = 0 ORDER BY zeitstempel DESC"); + if(!$mirrors){ + return false; + } + + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$tablename; + if(!is_dir($dir)) { + return false; + } + + foreach($mirrors as $k => $mirror) { + $dateipfad = Briefpapier::getPDFfolder($dir,$tableid,$mirror['dateiname']); + if(!$mirror['dateiname'] || !file_exists($dateipfad)) { + unset($mirrors[$k]); + } + else{ + $mirrors[$k]['file'] = $mirror['dateiname']; + } + } + + if(empty($mirrors)) { + return false; + } + + return $mirrors; + } + + public function getArchivedFiles_alt($tableid, $tablename) + { + + $mirrors = $this->app->DB->SelectArr("SELECT * from pdfmirror_md5pool where table_id = '".$tableid."' and table_name = '".$tablename."' ORDER BY zeitstempel DESC"); + + if(!$mirrors)return false; + + $dir = $this->app->Conf->WFuserdata."/pdfmirror/".$this->app->Conf->WFdbname.'/'.$tablename; + if(is_dir($dir)) + { + + + $files = glob($dir.'/*.pdf'); + if(!$files)return false; + + foreach($files as $file) + { + $path_parts = pathinfo($file); + foreach($mirrors as $k => $mirror) + { + if($mirror['checksum']) + { + + if(strpos($path_parts['basename'],$mirror['checksum'])=== 0) + { + $mirrors[$k]['file'] = $path_parts['basename']; + } + + } else { + if(strpos($path_parts['filename'], $tableid.'_') === 0){ + $mirrors[$k]['file'] = $path_parts['basename']; + } + + } + + } + } + foreach($mirrors as $k => $mirror) + { + if(!isset($mirror['file']))unset($mirrors[$k]); + } + + if(!isset($mirrors) || count($mirrors) < 1)return false; + + return $mirrors; + } + return false; + } + + /** + * @param int $id + * + * @return bool|array + */ + public function getArchivByID($id) + { + $id = (int)$id; + if($id <= 0) { + return false; + } + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname; + if(!is_dir($dir)) { + return false; + } + $mirror = $this->app->DB->SelectRow(sprintf('SELECT * FROM pdfarchiv WHERE id = %d LIMIT 1', $id)); + if(empty($mirror)){ + return false; + } + + if(empty($mirror['dateiname'])) { + return false; + } + $file = Briefpapier::getPDFfolder($dir.'/'.$mirror['table_name'], $mirror['table_id'], $mirror['dateiname']); + + if(!file_exists($file)) { + return false; + } + + $tmpr['belegnr'] = $mirror['belegnummer']; + $tmpr['file'] = file_get_contents($file); + + return $tmpr; + } + + public function getArchivByID_alt($id) + { + $id = (int)$id; + if(!$id)return false; + $dir = $this->app->Conf->WFuserdata."/pdfmirror/".$this->app->Conf->WFdbname; + if(!is_dir($dir))return false; + $mirror = $this->app->DB->SelectArr("SELECT * from pdfmirror_md5pool where id = '$id' LIMIT 1"); + if(!$mirror)return false; + $mirror = reset($mirror); + $mirrors = $this->getArchivedFiles_alt($mirror['table_id'], $mirror['table_name']); + if(!$mirrors)return false; + foreach($mirrors as $mirror) + { + //echo "."; + if($mirror['id'] == $id) + { + //echo ":"; + if(file_exists($dir."/".$mirror['table_name']."/".$mirror['file'])) + { + //echo ";"; + $tmpr['belegnr'] = str_replace('.pdf','',$mirror['file']); + $tmpr['belegnr'] = substr($tmpr['belegnr'],strrpos($tmpr['belegnr'],'_')+1); + $tmpr['file'] = file_get_contents($dir."/".$mirror['table_name']."/".$mirror['file']); + return $tmpr; + } + return false; + } + } + return false; + } + + /** + * @param bool $from_archiv + */ + public function displayDocument($from_archiv = false) { + //$from_archiv=false; + if($from_archiv) { + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; + if($this->table && $this->id && is_dir($dir)) { + if($this->table === 'rechnung') { + $filenameprefix = substr($this->filename,9,2); + $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); + } + else{ + $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); + } + if($mirror) { + $file = Briefpapier::getPDFfolder($dir, $this->id, $mirror); + //if(is_file($dir.'/'.$mirror)) + if(is_file($file)) { + //$content = file_get_contents($dir.'/'.$mirror); + $content = file_get_contents($file); + if(!empty($content)) { + $this->filename = $this->app->erp->Dateinamen($this->filename); + header('Content-type: application/pdf'); + header('Content-Disposition: attachment; filename="'.$this->filename.'"'); + echo $content; + $this->app->ExitXentral(); + } + } + } + } + } + $this->filename = $this->app->erp->Dateinamen($this->filename); + + $this->renderDocument(); + $this->archiveDocument(); + $this->Output($this->filename,'D'); + $this->app->ExitXentral(); + } + + public function displayTMP($from_archiv = false) { + //if(!$from_archiv && $this->table && $this->id)$from_archiv = $this->app->DB->Select("SELECT schreibschutz FROM `".$this->table."` WHERE id = '".$this->id."' LIMIT 1"); + if($from_archiv) { + $dir = $this->app->Conf->WFuserdata.'/pdfarchiv/'.$this->app->Conf->WFdbname.'/'.$this->table; + if($this->table && $this->id && is_dir($dir)) { + if($this->table === 'rechnung') { + $filenameprefix = substr($this->filename,9,2); + $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND substring(belegnummer,1,2) = '$filenameprefix' AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); + } + else{ + $mirror = $this->app->DB->Select("SELECT dateiname FROM pdfarchiv WHERE table_name = '".$this->table."' AND table_id = '".$this->id."' AND schreibschutz = 1 AND parameter = '".$this->parameter."' AND keinhintergrund = '".(int)$this->app->erp->BriefpapierHintergrunddisable."' ORDER by zeitstempel DESC LIMIT 1"); + } + if($mirror){ + $mirror2 = Briefpapier::getPDFfolder($dir,$this->id, $mirror); + if(is_file($mirror2)) { + $mirror = substr($mirror2, strlen($dir)+1); + } + if(is_file($dir.'/'.$mirror)){ + $this->filename = $this->app->erp->Dateinamen($this->filename); + $content = file_get_contents($dir.'/'.$mirror); + if($content != '' && file_put_contents($this->app->erp->GetTMP().$this->filename,$content)){ + if($this->addpdf){ + $files[] = $this->app->erp->GetTMP().$this->filename; + foreach($this->addpdf as $file){ + $files[] = $file; + } + $content = $this->app->erp->MergePDF($files); + file_put_contents($this->app->erp->GetTMP().$this->filename,$content); + } + $this->ausarchiv = true; + return $this->app->erp->GetTMP().$this->filename; + } + } + } + } + } + + $this->renderDocument(); + $this->archiveDocument(); + $this->filename = $this->app->erp->Dateinamen($this->filename); + $this->Output($this->app->erp->GetTMP().$this->filename,'F'); + + return $this->app->erp->GetTMP().$this->filename; + } + + public function sendDocument($from_archiv = false) { + $this->renderDocument(); + $this->archiveDocument(); + $this->filename = $this->app->erp->Dateinamen($this->filename); + $this->Output($this->filename,'S'); + $this->app->ExitXentral(); + } + + /*********************************** + * public functions + ***********************************/ + // setup relevant data for a invoice + public function setupTax() { + // full taxrate + // define("USTV",0.19); + // reduced taxrate + // define("USTR",0.07); + } + + + public function calcTotals() { + $total=$totalFullTax=$totalReducedTax=0; + $citems = !empty($this->items)?count($this->items):0; + for($i=0;$i<$citems;$i++) { + $total += $this->items[$i]['tprice']; + if($this->items[$i]['tax']=="USTV") { + $totalFullTax+= $this->items[$i]['tprice']*USTV; + } + else { + $totalReducedTax+= $this->items[$i]['tprice']*USTR; + } + } + return array($total,$totalFullTax,$totalReducedTax); + } + + function GetFont() + { + if($this->getStyleElement('schriftart')!=''){ + return $this->getStyleElement('schriftart'); + } + + return 'Arial'; + } + + public function setStyleData($styleData){ + $this->styleData = $styleData; + } + + private function getStyleElement($key){ + if(isset($this->styleData[$key]) && !empty($this->styleData[$key])) return $this->styleData[$key]; + + return $this->app->erp->Firmendaten($key); + } + + public function renderDocument() { + // prepare page details + parent::__construct('P','mm','A4'); + $this->app->erp->RunHook('briefpapier_render_document_hook1', 1, $this); + + + // if($this->getStyleElement("schriftart")!="") + // $this->SetFont($this->getStyleElement("schriftart")); + + $font = $this->getStyleElement('schriftart'); + + if(!in_array($font, ['', 'Arial', 'Courier', 'Helvetica', 'Times'])){ + $this->AddFont($font,'',strtolower($font).'.php'); + + if(is_file("lib/pdf/font/".strtolower($font).'i.php')) + $this->AddFont($font,'I',strtolower($font).'i.php'); + else + $this->AddFont($font,'I',strtolower($font).'.php'); + + if(is_file("lib/pdf/font/".strtolower($font).'b.php')) + $this->AddFont($font,'B',strtolower($font).'b.php'); + else + $this->AddFont($font,'B',strtolower($font).'.php'); + + if(is_file("lib/pdf/font/".strtolower($font).'bi.php')) + $this->AddFont($font,'BI',strtolower($font).'bi.php'); + else + $this->AddFont($font,'BI',strtolower($font).'.php'); + + } + + // invoke Header() and Footer() by adding a new page + $this->AddPage(); + //$this->setStationery("/home/eproo/eproo-master/app/main/www/lib/dokumente/demo.pdf"); + $this->SetDisplayMode("real","single"); + + if($this->getStyleElement("abstand_seitenrandrechts")=="") + $this->getStyleElementSet("abstand_seitenrandrechts",$this->getStyleElement("abstand_seitenrandlinks")); + + $this->SetMargins($this->getStyleElement("abstand_seitenrandlinks"),50,$this->getStyleElement("abstand_seitenrandrechts")); + $this->SetAutoPageBreak(true,$this->getStyleElement("abstand_umbruchunten")); + $this->AliasNbPages('{nb}'); + + // render document top to bottom + if(!$this->nichtsichtbar_empfaenger) + { + if(!empty($this->recipient)) + $this->renderRecipient(); + } + + if($this->doctype=="lieferschein" && !empty($this->barcode)) + { + if($this->barcode_y_header!=0) + $y = $this->barcode_y_header; + else + $y = $this->GetY(); + $this->Code39($this->barcode_x_header, $y+1, $this->barcode, 1, 5); + } + + if($this->barcode!="" && $this->briefpapier!=""){ + $this->Code39($this->barcode_x, $this->barcode_y, $this->barcode, 1, 3); + } + + //if(!empty($this->sender)) + $this->renderSender(); + + if(!$this->nichtsichtbar_box) + { + if(!empty($this->corrDetails) || !empty($this->boldCorrDetails) || !empty($this->italicCorrDetails) + || !empty($this->italicBoldCorrDetails)) + $this->renderCorrDetails(); + } + + $this->renderDoctype(); + if($this->doctype=="brief") + { + $this->SetY(95); + $this->textDetails['body']=$this->letterDetails['body']; + } + + $this->renderText(); + if(!empty($this->items)) { + $this->renderItems(); + $this->SetTextColor(0,0,0); + if($this->doctype!="lieferschein" && $this->doctype!="preisanfrage" && !$this->nichtsichtbar_summe) { + $this->renderTotals(); + } else $this->Cell(1,5,'',0); + } + $this->renderFooter(); + $this->logofile = ""; + $this->briefpapier=""; + $this->briefpapier2=""; + if($this->addpdf) + { + foreach($this->addpdf as $addpdf) + { + $filename = $addpdf; + $this->AddPage(); + $this->SetXY(0,0); + $anz = $this->setSourceFile($filename); + for($i = 1; $i <= $anz; $i++) + { + if($i > 1) + { + $this->AddPage(); + $this->SetXY(0,0); + } + $tplidx = $this->ImportPage($i); + $this->useTemplate($tplidx); + } + } + } + $this->app->erp->RunHook('briefpapier_render_document_hook2', 1, $this); + } + + + public function renderRecipient(){ + // $this->SetY(50); + $this->SetY(50+$this->abstand_adresszeileoben); + $this->SetFont($this->GetFont(),'',10); + + $schriftgroesse = $this->getStyleElement('schriftgroesse'); + if($schriftgroesse>0) + $this->SetFont($this->GetFont(),'',$schriftgroesse); + + if($this->recipient['anrede']!="" && $this->getStyleElement('typimdokument')) + { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['anrede'],0,1); + } + + $this->SetMargins($this->getStyleElement("abstand_adresszeilelinks"),50); + if($this->recipient['enterprise']) { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $charlimit=40; + if(strlen($this->recipient['enterprise'])>$charlimit + 15) + { + $array = explode( "\n", wordwrap($this->recipient['enterprise'], $charlimit)); + foreach($array as $row) + { + $this->Cell(80,5,$this->app->erp->ReadyForPDF($row),0,1); + } + } else { + $this->Cell(80,5,$this->app->erp->ReadyForPDF($this->recipient['enterprise']),0,1); + } + + } + + + if($this->recipient['firstname']!="") + { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['firstname'],0,1); + } + + if($this->recipient['address2']!="") { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['address2'],0,1); + } + + if($this->recipient['address3']!="") + { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['address3'],0,1); + } + + if($this->recipient['address4']!="") + { + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['address4'],0,1); + } + + + //$this->Cell(80,5,$this->recipient['firstname']." ".$this->recipient['familyname'],0,1); + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,$this->recipient['address1'],0,1); + + + $this->SetFont($this->GetFont(),'',10); + if($schriftgroesse>0) + $this->SetFont($this->GetFont(),'',$schriftgroesse); + + + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $inland = $this->getStyleElement("land"); + if($this->recipient['country']!=$inland) + { + //$this->Cell(80,5,$this->recipient['country']."-".$this->recipient['areacode']." ".$this->recipient['city'],0,1); + + if(function_exists('mb_strtoupper')) + $this->Cell(80,5,mb_strtoupper($this->recipient['areacode']." ".$this->recipient['city'],"UTF-8"),0,1); + else + $this->Cell(80,5,strtoupper($this->recipient['areacode']." ".$this->recipient['city']),0,1); + + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + $this->Cell(80,5,strtoupper($this->app->erp->UmlauteEntfernen($this->app->GetLandLang($this->recipient['country'],$this->sprache))),0,1); + + } + else { + $this->Cell(80,5,$this->recipient['areacode']." ".$this->recipient['city'],0,1); + } + //$this->SetFont($this->GetFont(),'',9); + //if(isset($this->recipient['country'])) $this->Cell(80,5,$this->recipient['country'],0,1); + + + //FREITEXT1 + $freitext1aktiv = $this->getStyleElement('freitext1aktiv'); + if($freitext1aktiv){ + $freitext1inhalt = $this->app->erp->Beschriftung("freitext1inhalt"); + if($freitext1inhalt=="") $freitext1inhalt = $this->getStyleElement('freitext1inhalt'); + + $freitext1inhalt = $this->app->erp->ParseUserVars($this->table,$this->id,$freitext1inhalt); + $freitext1inhalt = $this->app->erp->ReadyForPDF($freitext1inhalt); + $freitext1schriftgroesse = $this->getStyleElement('freitext1schriftgroesse'); + $freitext1y = $this->getStyleElement('freitext1y'); + $freitext1x = $this->getStyleElement('freitext1x'); + $freitext1breite = $this->getStyleElement('freitext1breite'); + $this->SetFont($this->GetFont(),'',$freitext1schriftgroesse); + $this->SetY($freitext1y); + $this->SetX($freitext1x); + $this->MultiCell($freitext1breite, 5, $this->WriteHTML($freitext1inhalt), 0, 'L'); + } + + + //FREITEXT2 + $freitext2aktiv = $this->getStyleElement('freitext2aktiv'); + if($freitext2aktiv){ + $freitext2inhalt = $this->app->erp->Beschriftung("freitext2inhalt"); + if($freitext2inhalt=="") $freitext1inhalt = $this->getStyleElement('freitext2inhalt'); + + $freitext2inhalt = $this->app->erp->ParseUserVars($this->table,$this->id,$freitext2inhalt); + $freitext2inhalt = $this->app->erp->ReadyForPDF($freitext2inhalt); + $freitext2schriftgroesse = $this->getStyleElement('freitext2schriftgroesse'); + $freitext2y = $this->getStyleElement('freitext2y'); + $freitext2x = $this->getStyleElement('freitext2x'); + $freitext2breite = $this->getStyleElement('freitext2breite'); + $this->SetFont($this->GetFont(),'',$freitext2schriftgroesse); + $this->SetY($freitext2y); + $this->SetX($freitext2x); + $this->MultiCell($freitext2breite, 5, $this->WriteHTML($freitext2inhalt), 0, 'L'); + } + + + $this->SetMargins($this->getStyleElement("abstand_seitenrandlinks"),50,$this->getStyleElement("abstand_seitenrandrechts")); + } + + public function setAbsender($sender) + { + $this->absender = $sender; + + } + + public function renderSender() { + $monthlu = array("", "Januar", "Februar", "M�rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"); + $monthnom = date("n"); + $month = $monthlu[$monthnom]; + $date = date("j").". ".$month." ".date("Y"); + + + if($this->nichtsichtbar_zeileabsender!=true) + { + + //abstand_adresszeileoben + // line above address field + $absender = (($this->absender!='') ? $this->absender : $this->getStyleElement('absender')); + $schriftgroesse = $this->getStyleElement('schriftgroesseabsender'); + $this->SetY(43+$this->abstand_adresszeileoben); + $this->SetFont($this->GetFont(),'',$schriftgroesse); + //$cellStr = $this->sender['enterprise']." � ".$this->sender['address1']." � ".$this->sender['areacode']." ".$this->sender['city']; + $cellStr = $this->app->erp->ReadyForPDF($absender); + + $this->SetX($this->getStyleElement("abstand_adresszeilelinks")); + + if($this->getStyleElement("absenderunterstrichen")=="1") + $this->Cell($this->GetStringWidth($cellStr)+2,5,$cellStr,'B'); + else + $this->Cell($this->GetStringWidth($cellStr)+2,5,$cellStr,''); + } + + if($this->nichtsichtbar_rechtsoben!=true) + { + // detailed sender data + $lineHeight = 4; + $xOffset = 131; + $absatz = 3; + + $this->SetXY($xOffset,10); + $this->SetFont($this->GetFont(),'',9); + $this->Cell(30,$lineHeight,"Name der Gesellschaft: ",0,0,'R'); + $this->SetFont($this->GetFont(),'B',9); + $this->Cell(60,$lineHeight,$this->sender['enterprise'],0,2); + if(isset($this->sender['enterprise2'])) + $this->Cell(60,$lineHeight,$this->sender['enterprise2'],0,2); + + $this->SetXY($xOffset,$this->GetY()); + $this->SetFont($this->GetFont(),'',9); + $this->Cell(30,$lineHeight,"Sitz der Gesellschaft: ",0,0,'R'); + $this->SetFont($this->GetFont(),'B',9); + $this->Cell(60,$lineHeight,$this->sender['address1'],0,2); + if(isset($this->sender['address2'])) + $this->Cell(60,$lineHeight,$this->sender['address2'],0,2); + $this->Cell(60,$lineHeight,$this->sender['areacode']." ".$this->sender['city'],0,2); + + $this->SetXY($xOffset,$this->GetY()+$absatz); //abstand + $this->SetFont($this->GetFont(),'',9); + if(isset($this->sender['phone1'])) { + $this->Cell(30,$lineHeight,"Fon: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['phone1'],0,2); + } + + if(isset($this->sender['fax'])) { + $this->SetXY($xOffset,$this->GetY()); + $this->Cell(30,$lineHeight,"Fax: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['fax'],0,2); + } + + + $this->SetXY($xOffset, $this->GetY()+$absatz); //abstand + if(isset($this->sender['email'])) { + $this->Cell(30,$lineHeight,"Mail: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['email'],0,2); + } + + if(isset($this->sender['web'])) { + $this->SetXY($xOffset,$this->GetY()); + $this->Cell(30,$lineHeight,"Web: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['web'],0,2); + } + + $this->SetXY($xOffset, $this->GetY()+$absatz); //abstand + if(isset($this->sender['ustid'])) { + $this->Cell(30,$lineHeight,"UST-ID: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['ustid'],0,2); + } + if(isset($this->sender['taxnr'])) { + $this->SetXY($xOffset,$this->GetY()); + $this->Cell(30,$lineHeight,"Steuer-Nr.: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['taxnr'],0,2); + } + if(isset($this->sender['hreg'])) { + $this->SetXY($xOffset,$this->GetY()); + $this->Cell(30,$lineHeight,"Handelsregister: ",0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['hreg'],0,2); + } + + $this->SetXY($xOffset,$this->GetY()); + $this->Cell(30,$lineHeight,utf8_encode("Gesch�ftsf�hrung: "),0,0,'R'); + $this->Cell(60,$lineHeight,$this->sender['firstname'].' '.$this->sender['familyname'],0,2); + + //$this->SetXY($xOffset, $this->GetY()+$absatz+2); //abstand + //$this->Cell(30,$lineHeight,"Datum: ",0,0,'R'); + //$this->Cell(60,$lineHeight,utf8_encode($date),0,2); + } + } + + + // kundennummer rechnungsnummer und datum + public function renderCorrDetails() { + + $breite_spalte_rechts = 30; + + $recht_links_verschieben = $this->abstand_boxrechtsoben_lr; + + $startpos_links_rechts = -83 + $recht_links_verschieben; + + $boldTitleStr = $boldValueStr = $titleStr = $valueStr = ""; + $italicTitleStr = $italicValueStr = ''; + $italicBoldTitleStr = $italicBoldValueStr = ''; + if(isset($this->boldCorrDetails)){ + foreach($this->boldCorrDetails as $title => $value) { + $boldTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; + $boldValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; + } + } + if(!empty($this->italicCorrDetails)) { + foreach($this->italicCorrDetails as $title => $value) { + $italicTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; + $italicValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; + } + } + + if(!empty($this->italicBoldCorrDetails)) { + foreach($this->italicBoldCorrDetails as $title => $value) { + $italicBoldTitleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; + $italicBoldValueStr .= $this->app->erp->ReadyForPDF($value)."\n"; + } + } + + if(isset($this->corrDetails)){ + foreach($this->corrDetails as $title => $value) { + if($value!="") + { + $titleStr .= $title !== ''?$this->app->erp->ReadyForPDF($title).": \n":" \n"; + $valueStr .= $this->app->erp->ReadyForPDF($value)."\n"; + } + } + } + + if($this->boxausrichtung=="") $this->boxausrichtung="R"; + + $pos = strpos($this->boxausrichtung, ';'); + if($pos > 0) + { + $tmp_box = explode(";",$this->boxausrichtung); + $this->boxausrichtung = $tmp_box[0]; + $this->box_breite1 = $tmp_box[1]; + $this->box_breite2 = $tmp_box[2]; + } + if($this->box_breite1=="") $this->box_breite1=34; + if($this->box_breite2=="") $this->box_breite2=38; + + + $fontinfobox = $this->getStyleElement("infobox"); + + if($italicBoldTitleStr != '') { + $this->SetFont($this->GetFont(),'BI',$fontinfobox); + $this->SetXY($startpos_links_rechts,80); + $this->MultiCell($this->box_breite1,4,$italicBoldTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft): $this->boxausrichtung); //TL + $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); + $this->MultiCell($this->box_breite2,4,$italicBoldValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR + } + elseif($italicTitleStr != '') { + $this->SetFont($this->GetFont(),'I',$fontinfobox); + $this->SetXY($startpos_links_rechts,80); + $this->MultiCell($this->box_breite1,4,$italicTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL + $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); + $this->MultiCell($this->box_breite2,4,$italicValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); + } + elseif($boldTitleStr!='') { + $this->SetFont($this->GetFont(),'B',$fontinfobox); + $this->SetXY($startpos_links_rechts,80); + $this->MultiCell($this->box_breite1,4,$boldTitleStr,'',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL + $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80); + $this->MultiCell($this->box_breite2,4,$boldValueStr,'',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR + } + else { + $this->SetXY($startpos_links_rechts,80+$this->abstand_boxrechtsoben); + $this->MultiCell($this->box_breite1,0,'','',!empty($this->boxalignmentleft)?strtoupper($this->boxalignmentleft):$this->boxausrichtung); //TL + $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,80+$this->abstand_boxrechtsoben); + $this->MultiCell($this->box_breite2,0,'','',!empty($this->boxalignmentright)?strtoupper($this->boxalignmentright):$this->boxausrichtung); //TR + } + + $this->SetY(80); + $this->SetY($this->GetY()+$this->abstand_boxrechtsoben); + + $this->SetFont($this->GetFont(),'',$fontinfobox); + $tempY = $this->GetY(); + $this->SetX($startpos_links_rechts); + $this->MultiCell($this->box_breite1,4,$titleStr,"",$this->boxausrichtung); //BL + $this->SetXY($startpos_links_rechts+$breite_spalte_rechts,$tempY); + $this->MultiCell($this->box_breitexi21,4,$valueStr,"",$this->boxausrichtung); //BR + + $this->SetY(80+$this->abstand_artikeltabelleoben); //Hoehe Box + //$this->SetY(60);//+$this->abstand_artikeltabelleoben); //Hoehe Box + } + + + public function renderDoctype() { + //$this->Ln(1); + + if($this->doctype=="brief") + $betreffszeile = $this->getStyleElement('betreffszeile'); + else + $betreffszeile = $this->getStyleElement('betreffszeile'); + + $this->SetY(80);//+$this->abstand_artikeltabelleoben); //Hoehe Box + //$this->SetY(80+$this->abstand_artikeltabelleoben); //Hoehe Box + + $this->SetFont($this->GetFont(),'B',$betreffszeile); + $this->SetY($this->GetY()+$this->abstand_betreffzeileoben); + //$this->Cell(85,6,$this->doctypeOrig); + $this->MultiCell(210-83+$this->abstand_boxrechtsoben_lr-$this->getStyleElement("abstand_seitenrandlinks")-5,6,html_entity_decode($this->doctypeOrig,ENT_QUOTES),0,'L'); + $this->SetY($this->GetY()-$this->abstand_betreffzeileoben); + + //$this->SetY($this->GetY()+$this->abstand_betreffzeileoben); + $this->SetY($this->GetY()+$this->abstand_artikeltabelleoben); //Hoehe Box + } + + public function renderText() { + + if(isset($this->textDetails['body'])) { + if($this->doctype=="brief") + $dokumententext = $this->getStyleElement('dokumententext'); + else + $dokumententext = $this->getStyleElement('dokumententext'); + $this->SetFont($this->GetFont(),'',$dokumententext); + //if($this->doctype!="brief") + $this->Ln(11); + + $this->textDetails['body'] = $this->app->erp->ParseUserVars($this->table,$this->id,$this->textDetails['body']); + + if($this->getStyleElement("briefhtml")=="1") + { + $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($this->textDetails['body'])); + $this->MultiCell(180,4,$this->WriteHTML($html)); + } else { + $this->MultiCell(180,4,$this->app->erp->ReadyForPDF($this->textDetails['body'])); + } + } + } + + public function renderFooter() { + + $this->app->erp->RunHook('briefpapier_render_footer_hook1', 1, $this); + + if(isset($this->textDetails['footer'])) { + $freitext = $this->getStyleElement('freitext'); + + if($this->getStyleElement("kleinunternehmer")) + { + if($this->textDetails['footer']=="") $this->textDetails['footer'] ="Als Kleinunternehmer im Sinne von §19 Abs.1 UStG wird Umsatzsteuer nicht berechnet!"; + else $this->textDetails['footer'] .="\r\nAls Kleinunternehmer im Sinne von § 19 Abs. 1 UStG wird Umsatzsteuer nicht berechnet!"; + } + + $this->textDetails['footer'] = $this->app->erp->ParseUserVars($this->table,$this->id,$this->textDetails['footer']); + + $this->SetFont($this->GetFont(),'',$freitext); + // $this->Ln(); + $y = $this->GetY(); + + // if($this->doctype!="lieferschein") + // $this->SetY($y-5); + //$parsed = $this->app->erp->ReadyForPDF($this->textDetails['footer']); + if($this->getStyleElement("briefhtml")=="1") + { + $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($this->textDetails['footer'])); + $this->MultiCell(180,4,$this->WriteHTML($html)); + } else { + $this->MultiCell(180,4,$this->app->erp->ReadyForPDF($this->textDetails['footer'])); + } + } + + $this->app->erp->RunHook('briefpapier_render_footer_hook2', 1, $this); + } + + public function CalcPosString($posstr, $oldpostr, $hauptnummer, $oldlvl, $newlvl) + { + if($oldpostr == 0) + { + if($hauptnummer) + { + return $hauptnummer.'.1'; + } + return '1'; + } + if($newlvl > $oldlvl) + { + return $oldpostr.str_repeat('.1', $newlvl - $oldlvl); + } + $oldpostra = explode('.', $oldpostr); + + $diff = $oldlvl - $newlvl; + $length = count($oldpostra); + if($hauptnummer && $hauptnummer != $oldpostra[0]){ + return (String)((int)$oldpostra[0]+1).'.1'; + } + + $ret = ''; + if($diff >= $length -1) + { + return (String)((int)$oldpostra[0]+1); + } + for($i = 0; $i < $length - 1 - $diff; $i++) + { + $ret .= $oldpostra[$i].'.'; + } + + return $ret.(String)((int)$oldpostra[$length - 1 - $diff]+1); + } + + /** + * @param string $type + * @param int $orderId + * @param int $orderPositionId + * @param string $doctype + * + * @return string + */ + public function getDeliveryNoteBestBeforeBatchSnFromOrder($type, $orderId, $orderPositionId, $doctype = 'auftrag') + { + if($doctype === 'rechnung') { + $orderPositionId = $this->app->DB->Select( + sprintf( + 'SELECT auftrag_position_id FROM rechnung_position WHERE id = %d', + $orderPositionId + ) + ); + if($orderPositionId <= 0) { + return ''; + } + } + + $position = $this->app->DB->SelectRow( + sprintf( + 'SELECT id, lieferschein + FROM lieferschein_position + WHERE auftrag_position_id = %d AND auftrag_position_id > 0 + LIMIT 1', + $orderPositionId + ) + ); + + if(empty($position)) { + return ''; + } + if($type === 'mhd') { + $this->mhd['lieferschein'][$position['lieferschein']][$position['id']] = + $this->GetChargeMHDSNString('mhd', 'lieferschein', $position['lieferschein'], $position['id']); + return $this->mhd['lieferschein'][$position['lieferschein']][$position['id']]; + } + if($type === 'charge') { + $this->charge['lieferschein'][$position['lieferschein']][$position['id']] = + $this->GetChargeMHDSNString('charge', 'lieferschein', $position['lieferschein'], $position['id']); + return $this->charge['lieferschein'][$position['lieferschein']][$position['id']]; + } + if($type === 'sn') { + $this->sn['lieferschein'][$position['lieferschein']][$position['id']] = + $this->GetChargeMHDSNString('sn', 'lieferschein', $position['lieferschein'], $position['id']); + return $this->sn['lieferschein'][$position['lieferschein']][$position['id']]; + } + + return ''; + } + + /** + * @param string $text + * @param string $doctype + * @param int $doctypeId + * @param int $positionId + * + * @return string + */ + public function parseBestBeforeBatchSn($text, $doctype, $doctypeId, $positionId){ + if(strpos($text, '{MHD}') !== false) { + $entry = !empty($this->mhd[$doctype]) && !empty($this->mhd[$doctype][$doctypeId]) + && !empty($this->mhd[$doctype][$doctypeId][$positionId])? + $this->mhd[$doctype][$doctypeId][$positionId]:''; + if($entry === '') { + $this->mhd[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( + 'mhd',$doctype,$doctypeId,$positionId, true + ); + $entry = $this->mhd[$doctype][$doctypeId][$positionId]; + if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { + $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('mhd', $doctypeId, $positionId, $doctype); + } + } + + $text = str_replace('{MHD}', $entry, $text); + } + if(strpos($text, '{CHARGE}') !== false) { + $entry = !empty($this->charge[$doctype]) && !empty($this->charge[$doctype][$doctypeId]) + && !empty($this->charge[$doctype][$doctypeId][$positionId])? + $this->charge[$doctype][$doctypeId][$positionId]:''; + if($entry === '') { + $this->charge[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( + 'charge',$doctype,$doctypeId,$positionId, true + ); + $entry = $this->charge[$doctype][$doctypeId][$positionId]; + if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { + $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('charge', $doctypeId, $positionId, $doctype); + } + } + $text = str_replace('{CHARGE}', $entry, $text); + } + if(strpos($text, '{SN}') !== false) { + $entry = !empty($this->sn[$doctype]) && !empty($this->sn[$doctype][$doctypeId]) + && !empty($this->sn[$doctype][$doctypeId][$positionId])? + $this->sn[$doctype][$doctypeId][$positionId]:''; + if($entry === '') { + $this->sn[$doctype][$doctypeId][$positionId] = $this->GetChargeMHDSNString( + 'sn',$doctype,$doctypeId,$positionId, true + ); + $entry = $this->sn[$doctype][$doctypeId][$positionId]; + if($entry === '' && ($doctype === 'auftrag' || $doctype === 'rechnung')) { + $entry = $this->getDeliveryNoteBestBeforeBatchSnFromOrder('sn', $doctypeId, $positionId, $doctype); + } + } + $text = str_replace('{SN}', $entry, $text); + } + + return $text; + } + + public function renderItems() { + + $this->app->erp->RunHook('briefpapier_renderitems',1, $this); + // if($this->bestellungohnepreis) $this->doctype="lieferschein"; + $posWidth = $this->getStyleElement("breite_position"); + $amWidth = $this->getStyleElement("breite_menge"); + $itemNoWidth = $this->getStyleElement("breite_nummer"); + $einheitWidth = $this->getStyleElement("breite_einheit"); + $descWidth = $this->getStyleElement("breite_artikel"); + $taxWidth = $this->getStyleElement("breite_steuer"); + $belege_subpositionen = $this->getStyleElement("belege_subpositionen"); + $belege_subpositionenstuecklisten = $this->getStyleElement('belege_subpositionenstuecklisten') && in_array(($this->table?$this->table:$this->doctype),array('rechnung', 'auftrag','lieferschein','gutschrift','angebot')); + $belege_stuecklisteneinrueckenmm = $this->getStyleElement('belege_stuecklisteneinrueckenmm'); + $doctype = $this->table?$this->table:$this->doctype; + $doctypeId = $this->id; + + $has_steuer = $this->app->DB->Select("SHOW COLUMNS FROM `$doctype` LIKE 'steuersatz_normal'"); + + if ($has_steuer) { + $docArr = $this->app->DB->SelectRow( + sprintf( + 'SELECT projekt,adresse,steuersatz_normal,steuersatz_ermaessigt FROM `%s` WHERE id = %d', + $doctype, $doctypeId + ) + ); + } else { + $docArr = $this->app->DB->SelectRow( + sprintf( + 'SELECT projekt,adresse, 0 AS steuersatz_normal, 0 AS steuersatz_ermaessigt FROM `%s` WHERE id = %d', + $doctype, $doctypeId + ) + ); + } + + $query = sprintf("SELECT `sprache` FROM `%s` + WHERE `id` = %d + LIMIT 1", + $doctype, $doctypeId); + $documentLanguage = $this->app->DB->Select($query); + if(!empty($docArr)) { + $projekt = $docArr['projekt']; + $adresse = $docArr['adresse']; + } + else{ + $projekt = $this->app->DB->Select("SELECT projekt FROM " . ($this->table ? $this->table : $this->doctype) . " WHERE id = '" . $this->id . "' LIMIT 1"); + $adresse = $this->app->DB->Select("SELECT adresse FROM " . ($this->table ? $this->table : $this->doctype) . " WHERE id = '" . $this->id . "' LIMIT 1"); + } + $inventurohnepreis = null; + if(!in_array($this->table ? $this->table : $this->doctype, ['rechnung','auftrag','angebot','bestellung'])) { + + $from = $this->table ? $this->table : $this->doctype; + + if ($this->app->DB->Select("SHOW COLUMNS FROM `$from` LIKE 'noprice'")) { + + $inventurohnepreis = $this->app->DB->Select( + sprintf( + 'SELECT noprice + FROM `%s` + WHERE id = %d + LIMIT 1', + $from, + $this->id + ) + ); + } + else { + $inventurohnepreis = false; + } + } + if($inventurohnepreis){ + $descWidth += 40; + } + + if($this->doctype=="arbeitsnachweis") + { + $itemNoWidth = 20; + $taxWidth = 40; + $descWidth = 95; + } + + if($this->rabatt=='1') { + $descWidth -= 15; + } + $priceWidth = 20; + $sumWidth = 20; + $rabattWidth = 15; + // $lineLength = $amWidth + $itemNoWidth + $descWidth + $taxWidth + $priceWidth + $sumWidth; + + // zwischenloesung um platz zu sparen + if($this->ust_spalteausblende) + { + $taxWidth--; + $descWidth += $taxWidth; + $taxWidth= 1; + } + + $cellhoehe = 5; + + // render table header + if(isset($this->textDetails['body'])) { + $this->Ln(); + } + else { + $this->Ln(8); + } + $tabellenbeschriftung = $this->getStyleElement('tabellenbeschriftung'); + + $this->SetX($this->getStyleElement('abstand_seitenrandlinks')+1); // eventuell einstellbar per GUI + + $this->SetFont($this->GetFont(),'B',$tabellenbeschriftung); + $this->Cell($posWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_position'),0,0,'C')); + if($this->doctype!='arbeitsnachweis') + { + if($this->doctype=='zahlungsavis') + { + $this->Cell($itemNoWidth,6,'Nummer'); + $this->Cell($descWidth-$einheitWidth+$taxWidth+$priceWidth+$rabattWidth,6,'Beleg'); + + $this->Cell($amWidth,6,'',0,0,'R'); + } + else { + $this->Cell($itemNoWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikelnummer'))); + if($this->getStyleElement('artikeleinheit')=='1'){ + $this->Cell($descWidth - $einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikel'))); + } + else{ + $this->Cell($descWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_artikel'))); + } + $this->Cell($amWidth,6,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_menge')),0,0,'R'); + } + } else { + $this->Cell($taxWidth,6,'Mitarbeiter'); + $this->Cell($itemNoWidth,6,'Ort'); + $this->Cell($descWidth,6,'Tätigkeit'); + $this->Cell($amWidth,6,'Stunden',0,0,'R'); + } + + if($this->doctype!='lieferschein' && $this->doctype!='arbeitsnachweis' && $this->doctype!='produktion' && $this->doctype!='zahlungsavis' && $this->doctype!='preisanfrage'){ + if($this->getStyleElement('artikeleinheit')=='1'){ + $this->Cell($einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einheit')), 0, 0, 'R'); + } + + if($this->ust_spalteausblende){ + $this->Cell($taxWidth, 6, '', 0, 0, 'R'); + } + else{ + $this->Cell($taxWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_mwst')), 0, 0, 'R'); + } + + if($this->getStyleElement('artikeleinheit')=='1'){ + if(!$inventurohnepreis){ + $this->Cell($priceWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einzel')), 0, 0, 'R'); + } + } + else{ + if(!$inventurohnepreis){ + $this->Cell($priceWidth, 6, $this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_stueck'))), 0, 0, 'R'); + } + } + + if($this->rabatt=='1') { + if(!$inventurohnepreis){ + $this->Cell($rabattWidth,6,$this->app->erp->Beschriftung('dokument_rabatt'),0,0,'R'); + $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); + } + } else { + if(!$inventurohnepreis){ + $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); + } + } + } + else if ($this->doctype=='lieferschein' || $this->doctype=='preisanfrage') + { + if($this->getStyleElement("artikeleinheit")=='1'){ + $this->Cell($einheitWidth, 6, $this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_einheit')), 0, 0, 'R'); + } + } + else if ($this->doctype=='zahlungsavis') + { + $this->Cell($sumWidth,6,$this->app->erp->ParseUserVars($this->doctype, $this->id,$this->app->erp->ReadyForPDF($this->app->erp->Beschriftung('dokument_gesamt'))),0,0,'R'); + } + + $this->Ln(); + $this->Line($this->getStyleElement('abstand_seitenrandlinks')+1, $this->GetY(), 210-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); + $this->Ln(2); + + // render table body + $tabelleninhalt = $this->getStyleElement('tabelleninhalt'); + + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + $topos = 0; + if(is_array($this->items))$topos = count($this->items); + $zwischenpositionen = $this->app->DB->Select("SELECT count(distinct pos) FROM beleg_zwischenpositionen WHERE doctype='".$this->doctype."' AND doctypeid='".$this->doctypeid."' AND pos >= 0 AND pos <'$topos' AND (postype = 'gruppe' OR postype = 'zwischensumme' OR postype = 'gruppensumme' OR postype = 'gruppensummemitoptionalenpreisen') ORDER by sort"); + if($zwischenpositionen < 1)$belege_subpositionen = false; + $hauptnummer = 0; + $posoffset = 0; + if($belege_subpositionen)$hauptnummer = 1; + $oldlvl = 0; + $oldpostr = 0; + $langeartikelnummern = ($this->getStyleElement('langeartikelnummern')?true:false); + if($this->doctype==='bestellung') { + $langeartikelnummern = $this->app->DB->Select("SELECT langeartikelnummern FROM bestellung WHERE id='".$this->doctypeid."' LIMIT 1")?true:false; + } + $pos=0; + $umsatzsteuerermaessigtProzent = !empty($docArr)?$docArr['steuersatz_ermaessigt']: $this->app->erp->GetSteuersatzErmaessigt(false,!empty($this->id)?$this->id:$this->doctypeid,$this->table); + $umsatzsteuernormalProzent = !empty($docArr)?$docArr['steuersatz_normal']:$this->app->erp->GetSteuersatzNormal(false,!empty($this->id)?$this->id:$this->doctypeid,$this->table); + + $umsatzsteuerermaessigt = (1+$umsatzsteuerermaessigtProzent/100); + $umsatzsteuernormal = (1+$umsatzsteuernormalProzent/100); + + $jitposfix = 0; //Die Anzahl der der Unterartikel des vorherigen Stücklistenartikels + $jitposfixbase = 0; //Die Gesamtzahl der bisher ausgeblendeten Stücklistenartikel + $anzeigeBelegNettoAdrese = $this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id); + $docRow = $this->app->DB->SelectRow( + sprintf( + 'SELECT * FROM `%s` WHERE id = %d', $this->doctype, $this->id + ) + ); + foreach($this->items as $item){ + $this->SetTextColor(0,0,0); + for ($l=$pos; $l <= $pos+$jitposfix ; $l++) { + //Arbeitet die Zwischenpositionen durch falls der vorherige Artikel ein Stücklistenartikel war bei dem Teile ausgeblendet wurden + $iszwichenpos = $this->DrawZwischenpositionen($l+$jitposfixbase); + } + $jitposfixbase += $jitposfix; + if($item['keineeinzelartikelanzeigen'] == 1){ + $jitposfix = $item['anzahlunterartikel']; + }else{ + $jitposfix = 0; + } + $item['name'] = ($langeartikelnummern?"\r\n\r\n":'').$this->app->erp->ReadyForPDF($item['name']); + $item['desc'] = $this->app->erp->ReadyForPDF($item['desc']); + $item['itemno'] = $this->app->erp->ReadyForPDF($item['itemno']); + $item['herstellernummer'] = $this->app->erp->ReadyForPDF($item['herstellernummer']); + $item['artikelnummerkunde'] = $this->app->erp->ReadyForPDF($item['artikelnummerkunde']); + $item['lieferdatum'] = $this->app->erp->ReadyForPDF($item['lieferdatum']); + $item['hersteller'] = $this->app->erp->ReadyForPDF($item['hersteller']); + + //TODO Soll einstellbar werden: Zeilenabstand in Tabelle normal mittel + $cellhoehe = 3; + //position + + if($iszwichenpos && $belege_subpositionen && $pos > $posoffset) + { + $hauptnummer++; + $posoffset = $pos; + } + if(isset($item['posausblenden']) && $item['posausblenden']){ + $posstr = ''; + }else{ + $pos++; + $posstr = $pos; + } + + if($belege_subpositionen && $hauptnummer) + { + $posstr = $hauptnummer.'.'.($pos-$posoffset); + } + $newlvl = isset($item['lvl'])?(int)$item['lvl']:0; + + + $itemNoWidthold = $itemNoWidth; + $posWidthold = $posWidth; + if($belege_stuecklisteneinrueckenmm && $newlvl > 0) + { + $this->Cell($belege_stuecklisteneinrueckenmm * $newlvl,$cellhoehe,''); + $posWidth -= $belege_stuecklisteneinrueckenmm * $newlvl; + if($posWidth < 2* strlen($posstr)) + { + $diff = 2* strlen($posstr) - $posWidth; + $posWidth += $diff; + $itemNoWidth -= $diff; + } + } + if($belege_subpositionenstuecklisten)$posstr = $this->CalcPosString($posstr,$oldpostr, $hauptnummer, $oldlvl, $newlvl); + $oldpostr = $posstr; + $oldlvl = isset($item['lvl'])?(int)$item['lvl']:0; + $this->Cell($posWidth,$cellhoehe,$posstr,0,0,$belege_stuecklisteneinrueckenmm?'':'C'); + //artikelnummer + if($this->doctype==='arbeitsnachweis') + { + $this->Cell($taxWidth,$cellhoehe,trim($item['person']),0); + + $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); + $this->SetFont($this->GetFont(),'',$zeilenuntertext); + + // ort + $tmpy = $this->GetY(); + $tmpx = $this->GetX(); + $this->MultiCell($itemNoWidth,($zeilenuntertext/2),trim($item['itemno']),0); // 4 = abstand + $tmpy2 = $this->GetY(); + $this->SetXY($tmpx+$itemNoWidth,$tmpy); + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + } + else { + //TODO BENE + if($this->doctype==='lieferschein' && $this->getStyleElement('modul_verband')=='1'){ + $this->SetFont($this->GetFont(), '', $tabelleninhalt + 3); + }else{ + $this->SetFont($this->GetFont(), '', $tabelleninhalt); + } + if(isset($item['itemno'])) { + $this->Cell($itemNoWidth,$cellhoehe,$item['itemno'],0); + } + else { + $this->Cell($itemNoWidth); + } + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + } + + $position_x = $this->GetX(); + $position_y = $this->GetY(); + +// start am Ende der Zeile Zeichnen + $this->SetAutoPageBreak(false,$this->getStyleElement("abstand_umbruchunten")); //2306BS + // Artikel Name + if($item['tax']!=='hidden' && $newlvl == 0){ + $this->SetFont($this->GetFont(), 'B', $tabelleninhalt); + } + if($item['tax'] === 'hidden' && $item['ohnepreis'] == 2 && $newlvl == 0){ + $this->SetFont($this->GetFont(), 'B', $tabelleninhalt); + } + if($this->getStyleElement("artikeleinheit")=='1'){ + $this->MultiCell($descWidth - $einheitWidth, $cellhoehe, $item['name'], 0, 'L', false); + } + else{ + $this->MultiCell($descWidth, $cellhoehe, $item['name'], 0, 'L', false); + } + + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + $this->SetAutoPageBreak(true,$this->getStyleElement('abstand_umbruchunten')); //2306BS + + $position_y_end_name = $this->GetY(); +// + + // wenn vorhanden Artikel Einheit + + + if($this->getStyleElement('artikeleinheit')=='1'){ + $this->SetXY(($position_x + $descWidth - $einheitWidth), $position_y); + } + else{ + $this->SetXY(($position_x + $descWidth), $position_y); + } + + + if($this->doctype==='arbeitsnachweis'){ + $this->SetXY(($position_x + $descWidth), $position_y); + } + + + // Menge + + if($this->doctype==='zahlungsavis'){ + $this->Cell($amWidth, $cellhoehe, '', 0, 0, 'R'); + } + else{ + $this->Cell($amWidth, $cellhoehe, $item['amount'], 0, 0, 'R'); + } + + if($this->doctype!=='lieferschein' && $this->doctype!=='arbeitsnachweis' && $this->doctype!=='produktion' && $this->doctype!=='preisanfrage') { + if($this->getStyleElement('artikeleinheit')=='1') + { + if($item['unit']!='') + $einheit = $item['unit']; + else { + if(!empty($item['artikel'])) + { + $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE + id='".$item['artikel']."' LIMIT 1"); + }else{ + $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE + nummer='".$item['itemno']."' LIMIT 1"); + } + if($einheit=='') { + $einheit = $this->getStyleElement('artikeleinheit_standard'); + } + } + if(!empty($einheit) && !empty($documentLanguage)){ + $query = sprintf("SELECT ae.id FROM `artikeleinheit` AS `ae` + WHERE ae.einheit_de = '%s'", + $this->app->DB->real_escape_string($einheit)); + $unitId = $this->app->DB->Select($query); + if(!empty($unitId)){ + $query = sprintf("SELECT u.beschriftung FROM `uebersetzung` AS `u` + WHERE u.sprache = '%s' AND u.label='%s'", + $documentLanguage,'artikeleinheit_'.$unitId); + $unitTranslation = $this->app->DB->Select($query); + if(!empty($unitTranslation)){ + $einheit = $unitTranslation; + } + } + } + + $this->Cell($einheitWidth,$cellhoehe,$this->app->erp->ReadyForPDF($einheit),0,0,'R'); + } + + // if($item['tax']=="hidden") $item['tax']=="hidden"; + if($item['tax']!=='hidden') + { + if($this->ust_befreit>0) { + $item['tax'] = 0; + } else { + if($item['tax'] === 'normal') { + $item['tax'] = $umsatzsteuernormal - 1; + } + else { + $item['tax'] = $umsatzsteuerermaessigt - 1; + } + } + if(isset($item['steuersatz'])){ + $item['tax'] = $item['steuersatz'] / 100; + } + } + + + // wenn steuerfrei komplett immer 0 steuer anzeigen + $item['tmptax'] = $item['tax'] + 1; + + // standard anzeige mit steuer + if(!$this->ust_spalteausblende){ + if($item['tax']==='hidden'){ + $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); + } else { + $tax = $item['tax']; //= $tax; //="USTV"?0.19:0.07; + $tax *= 100; $tax = $tax.'%'; + + if($this->doctype==='zahlungsavis'){ + $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); + } + else{ + $this->Cell($taxWidth, $cellhoehe, $item['ohnepreis'] ? '' : $tax, 0, 0, 'R'); + } + } + } else { + //kleinunternehmer + $this->Cell($taxWidth,$cellhoehe,"",0,0,'R'); + } + + if($this->doctype!=='lieferschein' && $this->doctype!=='produktion' && $this->doctype!=='preisanfrage') { + // preis pro Artikel + + if($this->doctype!=='zahlungsavis') + { + if($item['tax']!=='hidden'){ + + if($anzeigeBelegNettoAdrese){ + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + //&& $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + if(!$inventurohnepreis){ + $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price']), 0, 0, 'R'); + } + } + else{ + if(!$inventurohnepreis){ + $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price'] * $item['tmptax']), 0, 0, 'R'); + } + } + } else + { + if($item['ohnepreis']==2) { + if(!$inventurohnepreis){ + $this->Cell($priceWidth,$cellhoehe,$item['price'],0,0,'R'); + } + } // text alternativ zu preis + else { + if(!$inventurohnepreis){ + $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['price']),0,0,'R'); + } + } + } + } else { + $this->Cell($priceWidth,$cellhoehe,"",0,0,'R'); + } + + // zentale rabatt spalte + if($this->rabatt=='1') { + $rabatt_string=''; + + //rabatt + if($item['grundrabatt'] > 0 || $item['rabatt1'] > 0 || $item['rabatt2'] > 0) + { + if($item['grundrabatt']>0) { + $rabatt_string .= $item['grundrabatt']." %\r\n"; + } + if($item['rabatt1']>0) { + $rabatt_string .= $item['rabatt1']." %\r\n"; + } + if($item['rabatt2']>0) { + $rabatt_string .= $item['rabatt2']." %\r\n"; + } + if($item['rabatt3']>0) { + $rabatt_string .= $item['rabatt3']." %\r\n"; + } + if($item['rabatt4']>0) { + $rabatt_string .= $item['rabatt4']." %\r\n"; + } + if($item['rabatt5']>0) { + $rabatt_string .= $item['rabatt5']." %\r\n"; + } + + + $tmpy = $this->GetY(); + $tmpx = $this->GetX(); + + if($item['keinrabatterlaubt']=='1' || $item['rabatt']<=0 || $item['rabatt']==='') { + $rabatt_or_porto = $this->app->DB->Select("SELECT id FROM artikel WHERE + nummer='".$item['itemno']."' AND (porto='1' OR rabatt='1') LIMIT 1"); + if($rabatt_or_porto) + $rabatt_string=''; + else { + if($this->getStyleElement('modul_verband')=='1') { + $rabatt_string='SNP'; + } + else { + $rabatt_string=''; + } + } + if($item['keinrabatterlaubt']=='1' && $item['rabatt']<>0){ + $rabatt_string = $item['rabatt'] . " %\r\n"; + } + } + + // rabatt nur klein anzeigen wenn es mehr als einer ist + if(strstr(trim($rabatt_string), PHP_EOL)) { + $this->SetFont($this->GetFont(),'',6); + } + + if($item['tax']!=='hidden'){ + $this->MultiCell($rabattWidth, $cellhoehe - 1, $rabatt_string, 0, 0); + } + else{ + $this->MultiCell($rabattWidth, $cellhoehe - 1, "", 0, 0); + } + + $this->SetXY($tmpx+$rabattWidth,$tmpy); + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + } else { + if($item['rabatt']<>0){ + // && $item['keinrabatterlaubt']!="1") + $this->Cell($rabattWidth, $cellhoehe, $item['ohnepreis'] ? '' : $item['rabatt'] . " %", 0, 0, 'R'); + } + else + { + if($this->getStyleElement('modul_verband')=='1') + { + $rabatt_or_porto = $this->app->DB->Select("SELECT id FROM artikel WHERE + nummer='".$item['itemno']."' AND (porto='1' OR rabatt='1') LIMIT 1"); + if($rabatt_or_porto){ + $this->Cell($rabattWidth, $cellhoehe, '', 0, 0, 'R'); + } + else{ + $this->Cell($rabattWidth, $cellhoehe, 'SNP', 0, 0, 'R'); + } + } else { + $this->Cell($rabattWidth,$cellhoehe,"",0,0,'R'); + } + } + } + } + else { + // anzeige ohne zentrale rabatt spalte + if ($item['tax']==="hidden"){ + $this->Cell($priceWidth,$cellhoehe,"",0,0,'R'); + } + else { + if($anzeigeBelegNettoAdrese) + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + { + if(!$inventurohnepreis){ + $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['tprice']),0,0,'R'); + } + } + else{ + if(!$inventurohnepreis){ + $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); + } + } + + $this->Cell($rabattWidth,$cellhoehe,"",0,0,'R'); + } + } + } + else { + if($anzeigeBelegNettoAdrese) + // if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + if(!$inventurohnepreis){ + $this->Cell($priceWidth,$cellhoehe,$item['ohnepreis']?'':$this->formatMoney((double)$item['price']),0,0,'R'); + } + else{ + if(!$inventurohnepreis){ + $this->Cell($priceWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['price'] * $item['tmptax']), 0, 0, 'R'); + } + } + } + //$this->Cell($sumWidth,$cellhoehe,$this->formatMoney($item['tprice']).' '.$item['currency'],0,0,'R'); + if($this->rabatt=='1') + { + //gesamt preis + if ($item['tax']==='hidden'){ + $this->Cell($priceWidth,$cellhoehe,'',0,0,'R'); + } + else { + if($this->rabatt=='1'){ + if($anzeigeBelegNettoAdrese){ + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + if(!$inventurohnepreis){ + $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice']), 0, 0, 'R'); + } + } + else{ + if(!$inventurohnepreis){ + $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); + } + } + } + else { + if($anzeigeBelegNettoAdrese){ + // if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + if(!$inventurohnepreis){ + $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice']), 0, 0, 'R'); + } + } + else{ + if(!$inventurohnepreis){ + $this->Cell($sumWidth, $cellhoehe, $item['ohnepreis'] ? '' : $this->formatMoney((double)$item['tprice'] * $item['tmptax']), 0, 0, 'R'); + } + } + } + } + } + + } + else if(($this->doctype==='lieferschein' || $this->doctype==='preisanfrage') && $this->getStyleElement('artikeleinheit')=='1') + { + if($item['unit']!='') + $einheit = $item['unit']; + else { + $einheit = $this->app->DB->Select("SELECT einheit FROM artikel WHERE + nummer='".$item['itemno']."' LIMIT 1"); + if($einheit=='') { + $einheit = $this->getStyleElement('artikeleinheit_standard'); + } + } + + if(!empty($einheit) && !empty($documentLanguage)){ + $query = sprintf("SELECT ae.id FROM `artikeleinheit` AS `ae` + WHERE ae.einheit_de = '%s'", + $this->app->DB->real_escape_string($einheit)); + $unitId = $this->app->DB->Select($query); + if(!empty($unitId)){ + $query = sprintf("SELECT u.beschriftung FROM `uebersetzung` AS `u` + WHERE u.sprache = '%s' AND u.label='%s'", + $documentLanguage,'artikeleinheit_'.$unitId); + $unitTranslation = $this->app->DB->Select($query); + if(!empty($unitTranslation)){ + $einheit = $unitTranslation; + } + } + } + + $this->Cell($einheitWidth,$cellhoehe,$this->app->erp->ReadyForPDF($einheit),0,0,'R'); + } + + $this->Ln(); + if($this->getStyleElement('herstellernummerimdokument')=='1' && $item['herstellernummer']!='') + { + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_herstellernummer') . ': ' . $item['herstellernummer']; + } + else{ + $item['desc'] = $this->app->erp->Beschriftung('dokument_herstellernummer') . ': ' . $item['herstellernummer']; + } + } + + $daten = $this->app->DB->SelectRow("SELECT laenge, breite, hoehe FROM artikel WHERE id = '".$item['artikel']."'"); + if($this->getStyleElement('abmessungimdokument')=='1' && (!empty($daten['laenge']) || $daten['breite']!='' || $daten['hoehe']!='')) { + $tmp = array(); + if($daten['laenge']<>0) { + $tmp[]=number_format($daten['laenge'],2,',','.'); + } + if($daten['breite']<>0) { + $tmp[]=number_format($daten['breite'],2,',','.'); + } + if($daten['hoehe']<>0) { + $tmp[]=number_format($daten['hoehe'],2,',','.'); + } + + if(count($tmp) > 0) + { + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_abmessung') . ': ' . implode('x', $tmp); + } + else{ + $item['desc'] = $this->app->erp->Beschriftung('dokument_abmessung') . ': ' . implode('x', $tmp); + } + } + } + + if($item['lieferdatum']!='' && $item['lieferdatum']!='0000-00-00' && $item['lieferdatum']!=='00.00.0000') + { + if(strpos($item['lieferdatum'],"-")!==false){ + $item['lieferdatum'] = $this->app->erp->ReadyForPDF($this->app->String->Convert($item['lieferdatum'], '%1-%2-%3', '%3.%2.%1')); + } + + if($item['lieferdatumkw']==1) + { + $ddate = $this->app->String->Convert($item['lieferdatum'],'%3.%2.%1','%1-%2-%3'); + $duedt = explode("-", $ddate); + $date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]); + $week = date('W/o', $date); + $item['lieferdatum'] = $this->app->erp->Beschriftung('dokument_lieferdatumkw').' '.$week; + } + + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_lieferdatum') . ': ' . $item['lieferdatum']; + } + else{ + $item['desc'] = $this->app->erp->Beschriftung('dokument_lieferdatum') . ': ' . $item['lieferdatum']; + } + } + + + if($this->getStyleElement('freifelderimdokument')=='1') + { + for($ifreifeld=1;$ifreifeld<=40;$ifreifeld++) + { + if($item['freifeld'.$ifreifeld]!='') + { + $freifeldbeschriftung = $this->app->erp->Beschriftung('artikel_freifeld' . $ifreifeld); + $freifeldtyp = $this->getStyleElement('freifeld' . $ifreifeld.'typ'); + if($freifeldtyp==='select') + { + $freifeldbeschriftung = strstr($freifeldbeschriftung, '|', true); + } + + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $freifeldbeschriftung . ': ' . $item['freifeld' . $ifreifeld]; + } + else{ + $item['desc'] = $freifeldbeschriftung . ': ' . $item['freifeld' . $ifreifeld]; + } + } + } + if(strpos($item['desc'],'{{') !== false && $this->app->erp->ModulVorhanden('formeln')) { + $item['desc'] = $this->app->erp->BerechneFormel($item['desc'], $this->table, $this->id, $pos, $item); + } + + if(strpos($item['desc'],'{') !== false) { + if(!empty($item['belegposition']) && !empty($this->doctype) && !empty($this->id)) { + $item['desc'] = $this->parseBestBeforeBatchSn($item['desc'], $this->doctype, $this->id, $item['belegposition']); + } + $item['desc'] = $this->app->erp->ParseIfVars($item['desc']); + } + } + + if(strpos($item['desc'],'{') !== false) { + if(!empty($item['belegposition']) && !empty($this->doctype) && !empty($this->id)){ + $item['desc'] = $this->parseBestBeforeBatchSn( + $item['desc'], $this->doctype, $this->id, $item['belegposition'] + ); + } + } + + if(!empty($this->doctype) && !empty($this->id) && strpos($item['desc'], '{') !== false) { + $item['desc'] = $this->app->erp->ParseUserVars($this->doctype, $this->id ,$item['desc']); + } + + if($item['artikelnummerkunde']!="" && $item['artikelnummerkunde']!='0') + { + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_artikelnummerkunde') . ': ' . $item['artikelnummerkunde']; + } + else{ + $item['desc'] = $this->app->erp->Beschriftung('dokument_artikelnummerkunde') . ': ' . $item['artikelnummerkunde']; + } + } + + if($item['zolltarifnummer']!='' && $item['zolltarifnummer']!='0' && $this->doctype!='proformarechnung') + { + if($item['desc']!='') { + $item['desc']=$item['desc']."\r\n".$this->app->erp->Beschriftung('dokument_zolltarifnummer').': '.$item['zolltarifnummer'].' '.($item['herkunftsland']!=''?$this->app->erp->Beschriftung('dokument_herkunftsland').': '.$item['herkunftsland']:''); + } + else { + $item['desc']=$this->app->erp->Beschriftung('dokument_zolltarifnummer').': '.$item['zolltarifnummer'].' '.($item['herkunftsland']!=""?$this->app->erp->Beschriftung('dokument_herkunftsland').': '.$item['herkunftsland']:''); + } + } + + if($item['ean']!='' && $item['ean']!='0') + { + if($item['desc']!=''){ + $item['desc'] = $item['desc'] . "\r\n" . $this->app->erp->Beschriftung('dokument_ean') . ': ' . $item['ean']; + } + else{ + $item['desc'] = $this->app->erp->Beschriftung('dokument_ean') . ': ' . $item['ean']; + } + } + + if($item['zusammenfassen']){ + $item['desc'] = ''; + } + + $startpageBeforeDescription = $this->page; + + if($item['desc']!='' || !empty($item['steuertext'])) { + //Herstellernummer einblenden wenn vorhanden und aktiviert + $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); + $this->SetY($position_y_end_name+$this->getStyleElement('abstand_name_beschreibung')); + $yBeforeDescription = $this->GetY(); + $this->SetFont($this->GetFont(),'',$zeilenuntertext); + if($belege_stuecklisteneinrueckenmm && $newlvl > 0){ + $this->Cell($belege_stuecklisteneinrueckenmm * $newlvl, $cellhoehe, ''); + } + $this->Cell($posWidth); + $this->Cell($itemNoWidth); + if($this->doctype==='arbeitsnachweis') { + $this->Cell($taxWidth); + } + + if($this->doctype==='lieferschein' && $this->getStyleElement('modul_verband')=='1'){ + $this->SetFont($this->GetFont(), '', $tabelleninhalt + 1); + } + + if($this->getStyleElement('briefhtml')=='1') + { + $html = $this->app->erp->ReadyForPDF($this->app->erp->RemoveNewlineAfterBreaks($item['desc'])); + if($this->getStyleElement('artikeleinheit')=='1') + { + if($this->getStyleElement('breite_artikelbeschreibung')) + { + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$this->WriteHTML($html),0,'L'); // 4 = abstand + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + else + { + $this->MultiCell($descWidth-$einheitWidth,($zeilenuntertext/2),$this->WriteHTMLCell($descWidth-$einheitWidth,$html),0,'L'); // 4 = abstand //ALT + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + } + else + { + if($this->getStyleElement('breite_artikelbeschreibung')=='1') + { + $this->MultiCell($descWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$this->WriteHTML($html),0,'L'); // 4 = abstand + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + else + { + $this->MultiCell($descWidth,($zeilenuntertext/2),$this->WriteHTMLCell($descWidth,$html),0,'L'); // 4 = abstand //ALT + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + } + } else { + if($this->getStyleElement('artikeleinheit')=='1') + { + if($this->getStyleElement('breite_artikelbeschreibung')) + { + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + else + { + $this->MultiCell($descWidth-$einheitWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand //ALT + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + } + else + { + if($this->getStyleElement('breite_artikelbeschreibung')=='1') + { + $this->MultiCell($descWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + else + { + $this->MultiCell($descWidth,($zeilenuntertext/2),trim($item['desc']),0,'L'); // 4 = abstand //ALT + if(!empty($item['steuertext'])){ + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + } + } + + $this->Cell($taxWidth); + $this->Cell($amWidth); + $this->Ln(); + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + + $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); + $this->SetFont($this->GetFont(),'',$zeilenuntertext); + $this->Cell($posWidth); + $this->Cell($itemNoWidth); + if($this->doctype==='arbeitsnachweis') { + $this->Cell($taxWidth); + } + if($this->getStyleElement('artikeleinheit')=='1'){ + $this->MultiCell($descWidth - $einheitWidth, 4, '', 0); // 4 = abstand zwischen Artikeln + } + else{ + $this->MultiCell($descWidth, 4, '', 0); // 4 = abstand zwischen Artikeln + } + $this->Cell($taxWidth); + $this->Cell($amWidth); + $this->Ln(); + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + $yAfterDescription = $this->GetY(); + } else { + + $zeilenuntertext = $this->getStyleElement('zeilenuntertext'); + $this->SetY($position_y_end_name); + $yBeforeDescription = $this->GetY(); + $this->SetFont($this->GetFont(),'',$zeilenuntertext); + $this->Cell($posWidth); + $this->Cell($itemNoWidth); + if($this->doctype==='arbeitsnachweis') + { + $this->Cell($taxWidth); + } + if($this->getStyleElement('artikeleinheit')=='1') + { + $this->MultiCell($descWidth-$einheitWidth,3,trim($item['desc']),0); // 4 = abstand + if(!empty($item['steuertext'])) + { + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + else + { + $this->MultiCell($descWidth,3,trim($item['desc']),0); // 4 = abstand + if(!empty($item['steuertext'])) + { + $this->SetX($this->GetX()+$posWidth+$itemNoWidth); + $this->MultiCell($descWidth-$einheitWidth+$taxWidth + $sumWidth + $rabattWidth,($zeilenuntertext/2),$item['steuertext'],0,'L'); + } + } + + if(!empty($staffelpreiseanzeigen)){ + $this->MultiCell($posWidth+$itemNoWidth+$descWidth+$amWidth+$taxWidth+$sumWidth+$priceWidth,($zeilenuntertext/2),trim($staffelpreistext),0,'R'); + } + + $this->Cell($taxWidth); + $this->Cell($amWidth); + $this->Ln(); + $this->SetFont($this->GetFont(),'',$tabelleninhalt); + $yAfterDescription = $this->GetY(); + } + + $itemNoWidth = $itemNoWidthold; + $posWidth = $posWidthold; + + + + if( + ($this->doctype == "auftrag" && $this->getStyleElement("beleg_artikelbild")) || + ($this->doctype == "lieferschein" && $this->getStyleElement("lieferschein_artikelbild")) || + ($this->doctype == "rechnung" && $this->getStyleElement("rechnung_artikelbild")) || + ($this->doctype == "bestellung" && $this->getStyleElement("bestellung_artikelbild")) || + ($this->doctype == "gutschrift" && $this->getStyleElement("gutschrift_artikelbild")) || + ($this->doctype == "angebot" && $this->getStyleElement("angebot_artikelbild")) + ){ + $datei = $this->app->DB->Select("SELECT datei FROM `datei_stichwoerter` WHERE subjekt='Shopbild' AND objekt='Artikel' AND parameter='" . $item['artikel'] . "' ORDER by sort ASC LIMIT 1"); + if(!empty($datei)){ + $datei = $this->app->DB->Select("SELECT id FROM datei_version WHERE datei = '$datei' ORDER BY id DESC LIMIT 1"); + } + $startpage = $this->page; + if(!empty($datei)){ + $xBeforePic = $this->GetX(); + $folder = $this->app->erp->GetDMSPath($datei); + if(file_exists($folder . '/' . $datei)){ + if(!class_exists('image')) include_once(__DIR__ . '/../class.image.php'); + $img = new image($this->app); + $breite = 20 * 10; + $hoehe = $breite; + + [$width, $height] = getimagesize($folder . '/' . $datei); + if($width > 0 && $height > 0){ + $scalex = $breite / $width; + $scaley = $hoehe / $height; + if($scalex < $scaley){ + $hoehe /= $scaley / $scalex; + $hoehe = ceil($hoehe); + }else{ + $breite /= $scalex / $scaley; + $breite = ceil($breite); + } + + $cachefolder = $this->app->erp->CreateDMSPath($this->app->Conf->WFuserdata . '/dms/' . $this->app->Conf->WFdbname . '/cache', $datei, true) . "/"; + $dateiname = $cachefolder . $datei . '_' . $breite . '_' . $hoehe; + + if(!is_file($dateiname)) $img->scaledPicByFileId($datei, $breite, $hoehe, false, 'jpg'); + if(is_file($dateiname)){ + [$width, $height] = getimagesize($dateiname); + //$value['datei'] = array('file'=>$folder.'/cache/'.$datei.'_'.$breite.'_'.$breite,'width'=>$width/10,'height'=>$height/10); + + $this->SetX($posWidth + (int)$this->getStyleElement("abstand_seitenrandlinks") - 5); + $dateityp = mime_content_type($dateiname); + $dateityp = substr($dateityp,6); + if($dateityp == ''){ + $dateityp = 'jpg'; + } + + if($startpageBeforeDescription != $this->page){ + $this->SetY($this->abseite2y); + $this->SetX($posWidth + (int)$this->getStyleElement("abstand_seitenrandlinks") - 5); + $position_y_end_name = $this->abseite2y; + } + $this->Image($dateiname, $this->GetX(), $position_y_end_name + 2, $width / 10, $hoehe / 10,$dateityp); + $this->SetXY($this->GetX(), $position_y_end_name + 20); + $yAfterPic = $this->GetY(); + } + } + } + + if($yAfterPic < $yAfterDescription){ + $this->SetY($yAfterDescription); + } + + $this->SetX($xBeforePic); + + $y_nach_bild = $this->GetY(); + + if($yAfterDescription < $yAfterPic+5 && $startpage == $this->page){ + $this->SetY($y_nach_bild+5); + } + if($this->GetY() > 240){ + $this->AddPage(); + } + + } + + } + } + + for ($l=$pos; $l <= $pos+$jitposfix ; $l++) { + //Letzten Artikel durcharbeiten + $this->DrawZwischenpositionen($l+$jitposfixbase, $umsatzsteuerermaessigtProzent,$umsatzsteuernormalProzent); + } + + //$this->Line($this->GetX(), $this->GetY(), $this->getStyleElement("abstand_seitenrandlinks")+195-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); + + $this->Line($this->getStyleElement("abstand_seitenrandlinks")+1, $this->GetY(), 210-$this->getStyleElement("abstand_seitenrandrechts"), $this->GetY()); + } + + function DrawZwischenpositionen($pos,$umsatzsteuerermaessigt = null,$umsatzsteuernormal = null) { + $ret = false; + if(is_null($umsatzsteuerermaessigt)) + { + $umsatzsteuerermaessigt = $this->app->erp->GetSteuersatzErmaessigt(false,$this->doctypeid,$this->table); + } + if(is_null($umsatzsteuernormal)) + { + $umsatzsteuernormal = $this->app->erp->GetSteuersatzNormal(false,$this->doctypeid,$this->table); + } + if($this->table != 'lieferschein' && $this->table != 'preisanfrage') + { + $zwischenpositionen = $this->app->DB->SelectArr("SELECT * FROM beleg_zwischenpositionen WHERE doctype='".$this->table."' AND doctypeid='".$this->doctypeid."' AND pos='$pos' ORDER by sort"); + }else{ + $zwischenpositionen = $this->app->DB->SelectArr("SELECT * FROM beleg_zwischenpositionen WHERE doctype='".$this->table."' AND doctypeid='".$this->doctypeid."' AND pos='$pos' AND postype <> 'gruppensumme' AND postype <> 'gruppensummemitoptionalenpreisen' AND postype <> 'zwischensumme' ORDER by sort"); + } + + $projekt = $this->app->DB->Select("SELECT projekt FROM ".$this->table." WHERE id = '".$this->doctypeid."' LIMIT 1"); + $czwischenpositionen = !empty($zwischenpositionen)?count($zwischenpositionen):0; + for($i=0;$i<$czwischenpositionen;$i++) + { + $data = json_decode($zwischenpositionen[$i]['wert'], true); + switch($zwischenpositionen[$i]['postype']) + { + case "gruppe": + $ret = true; + $schriftgroesse = $this->FontSizePt; + $schriftgroesse_alt = $schriftgroesse; + if($schriftgroesse == 0)$schriftgroesse = 7; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + if($schriftgroesse == 0)$schriftgroesse = 7; + $this->SetFontSize($schriftgroesse); + } + $fett = true; + if(isset($data['Fett'])) + { + if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; + if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; + } + $unterstrichen = false; + if(isset($data['Unterstrichen'])) + { + $unterstrichen = $data['Unterstrichen']; + } + $this->underline = $unterstrichen; + $html = ($fett?"":"").$data['name'].($fett?"":""); + if(!empty($data['Abstand_Oben'])) + { + $this->Ln((int)$data['Abstand_Oben']); + }else{ + $this->Ln(0); + } + $schriftgroesse = 7; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + } + $this->SetFontSize($schriftgroesse_alt); + $x = $this->GetX(); + $abstand_links = 0; + if(isset($data['Abstand_Links'])) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + } + + $this->MultiCell(0,4,$this->WriteHTML($html)); + $this->SetX($x); + $this->Ln(); + $this->underline = false; + if($data['kurztext']!="") + { + + if(isset($data['Kurztext_Unterstrichen'])) + { + $this->underline = $data['Kurztext_Unterstrichen']; + } + $x = $this->GetX(); + $abstand_links = 0; + if(isset($data['Kurztext_Abstand_Links'])){ + $abstand_links = (int)$data['Kurztext_Abstand_Links']; + $this->SetX($x+$abstand_links); + } + elseif(isset($data['Abstand_Links'])) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + } + $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); + $this->SetX($x); + if(!empty($data['Abstand_Unten'])) + { + $this->Ln((int)$data['Abstand_Unten']); + }else{ + $this->Ln(10); + } + } + $this->SetFontSize($schriftgroesse_alt); + $this->underline = false; + break; + + case "bild": + if($data['bild']) + { + $nochtext = ''; + if($data['kurztext']!="") + { + $kurztexta = explode('{BILD}', $data['kurztext'], 2); + }else { + $kurztexta[] = ''; + } + if(count($kurztexta) > 1)$nochtext = $kurztexta[1]; + $data['kurztext'] = $kurztexta[0]; + + $__x = $this->GetX(); + //$ret = true; + $schriftgroesse = $this->FontSizePt; + $schriftgroesse_alt = $schriftgroesse; + if($schriftgroesse == 0)$schriftgroesse = 7; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + if($schriftgroesse == 0)$schriftgroesse = 7; + $this->SetFontSize($schriftgroesse); + } + $fett = true; + if(isset($data['Fett'])) + { + if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; + if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; + } + $unterstrichen = false; + if(isset($data['Unterstrichen'])) + { + $unterstrichen = $data['Unterstrichen']; + } + $this->underline = $unterstrichen; + $html = ($fett?"":"").$data['name'].($fett?"":""); + if(!empty($data['Abstand_Oben'])) + { + $this->Ln((int)$data['Abstand_Oben']); + }else{ + $this->Ln(0); + } + $schriftgroesse = 7; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + } + $this->SetFontSize($schriftgroesse_alt); + $x = $this->GetX(); + $abstand_links = 0; + if(isset($data['Abstand_Links'])) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + } + + $this->MultiCell(0,4,$this->WriteHTML($html)); + $this->SetX($x); + $this->Ln(); + $this->underline = false; + if($data['kurztext']!="") + { + + if(isset($data['Kurztext_Unterstrichen'])) + { + $this->underline = $data['Kurztext_Unterstrichen']; + } + $x = $this->GetX(); + $abstand_links = 0; + if(isset($data['Kurztext_Abstand_Links'])){ + $abstand_links = (int)$data['Kurztext_Abstand_Links']; + $this->SetX($x+$abstand_links); + } + elseif(isset($data['Abstand_Links'])) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + } + $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); + $this->SetX($x); + if($nochtext == '') + { + if(!empty($data['Abstand_Unten'])) + { + $this->Ln((int)$data['Abstand_Unten']); + }else{ + $this->Ln(10); + } + } + } + $this->SetFontSize($schriftgroesse_alt); + $this->underline = false; + + $posWidth = $this->getStyleElement("breite_position"); + $amWidth = $this->getStyleElement("breite_menge"); + $itemNoWidth = $this->getStyleElement("breite_nummer"); + $datei = $data['bild']; + if(!empty($datei)) + { + $datei = $this->app->DB->Select("SELECT id FROM datei_version WHERE datei = '$datei' ORDER BY id DESC LIMIT 1"); + } + if(!empty($datei)) + { + $folder = $this->app->erp->GetDMSPath($datei); + if(file_exists($folder.'/'.$datei)) + { + if(!class_exists('image'))include_once(__DIR__.'/../class.image.php'); + $img = new image($this->app); + if(isset($data['bildbreite']) && (int)$data['bildbreite'] > 0) + { + $breite = $data['bildbreite'] * 10; + }else{ + $breite = 30 * 10; + } + if(isset($data['bildhoehe']) && (int)$data['bildhoehe'] > 0) + { + $hoehe = $data['bildhoehe'] * 10; + }else{ + $hoehe = $breite; + } + [$width, $height] = getimagesize($folder.'/'.$datei); + if($width > 0 && $height > 0) + { + $scalex = $breite / $width; + $scaley = $hoehe / $height; + if($scalex < $scaley) + { + $hoehe /= $scaley / $scalex; + $hoehe = ceil($hoehe); + }else{ + $breite /= $scalex / $scaley; + $breite = ceil($breite); + } + + $cachefolder = $this->app->erp->CreateDMSPath($this->app->Conf->WFuserdata.'/dms/'.$this->app->Conf->WFdbname.'/cache', $datei, true)."/"; + $dateiname = $cachefolder.$datei.'_'.$breite.'_'.$hoehe; + + if(!is_file($dateiname))$img->scaledPicByFileId($datei, $breite, $hoehe, false, 'jpg'); + if(is_file($dateiname)) + { + [$width, $height] = getimagesize($dateiname); + //$value['datei'] = array('file'=>$folder.'/cache/'.$datei.'_'.$breite.'_'.$breite,'width'=>$width/10,'height'=>$height/10); + $x = $this->GetX(); + $y = $this->GetY(); + $this->SetX($posWidth+$itemNoWidth+(int)$this->getStyleElement("abstand_seitenrandlinks")); + $this->Image($dateiname, $this->GetX(), $this->GetY(),$width / 10, $hoehe / 10, 'jpg'); + if($nochtext == '') + { + $this->Cell($picwidth,6,'',0,0,'C'); + } + $this->SetXY($this->GetX(), $y + $height / 10 + ($nochtext == ''?5:0)); + } + } + } + } + $this->SetXY($__x, $this->GetY()); + + if($nochtext !== '') + { + $data['kurztext'] = $nochtext; + $__x = $this->GetX(); + $ret = true; + $schriftgroesse = $this->FontSizePt; + $schriftgroesse_alt = $schriftgroesse; + if($schriftgroesse == 0)$schriftgroesse = 7; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + if($schriftgroesse == 0)$schriftgroesse = 7; + $this->SetFontSize($schriftgroesse); + } + $fett = true; + if(isset($data['Fett'])) + { + if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; + if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; + } + + $this->SetFontSize($schriftgroesse_alt); + $x = $this->GetX(); + $this->underline = false; + if($data['kurztext']!="") + { + + if(isset($data['Kurztext_Unterstrichen'])) + { + $this->underline = $data['Kurztext_Unterstrichen']; + } + $x = $this->GetX(); + $abstand_links = 0; + if(isset($data['Kurztext_Abstand_Links'])){ + $abstand_links = (int)$data['Kurztext_Abstand_Links']; + $this->SetX($x+$abstand_links); + } + elseif(isset($data['Abstand_Links'])) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + } + $this->MultiCell(0,4,$this->WriteHTML($data['kurztext'])); + $this->SetX($x); + if(!empty($data['Abstand_Unten'])) + { + $this->Ln((int)$data['Abstand_Unten']); + }else{ + $this->Ln(10); + } + } + $this->SetFontSize($schriftgroesse_alt); + $this->underline = false; + } + } + break; + case "seitenumbruch": + $this->AddPage(); + break; + + case "gruppensumme": + case "gruppensummemitoptionalenpreisen": + case "zwischensumme": + $ret = true; + $posWidth = $this->getStyleElement("breite_position"); + $amWidth = $this->getStyleElement("breite_menge"); + $itemNoWidth = $this->getStyleElement("breite_nummer"); + $einheitWidth = $this->getStyleElement("breite_einheit"); + $descWidth = $this->getStyleElement("breite_artikel"); + $taxWidth = $this->getStyleElement("breite_steuer"); + + if($this->doctype=="arbeitsnachweis") + { + $itemNoWidth = 20; + $taxWidth = 40; + $descWidth = 95; + } + else if($this->doctype!="lieferschein" && $this->doctype!="produktion" && $this->doctype!="preisanfrage") { + if($descWidth <=0) + $descWidth = 76; + + if($taxWidth <=0) + $taxWidth = 15; + } + else + { + $itemNoWidth = 30; + $descWidth = 91; + if($taxWidth <=0) + $taxWidth = 15; + } + $priceWidth = 20; + $sumWidth = 20; + $rabattWidth = 15; + + + $schriftgroesse = $this->FontSizePt; + $schriftgroesse_alt = $schriftgroesse; + if($schriftgroesse == 0)$schriftgroesse = 4; + if(!empty($data['Schriftgroesse'])) + { + $schriftgroesse = $data['Schriftgroesse']; + if($schriftgroesse == 0)$schriftgroesse = 4; + $this->SetFontSize($schriftgroesse); + } + $fett = true; + if(isset($data['Fett'])) + { + if($data['Fett'] === false || $data['Fett'] === 'false')$fett = false; + if($data['Fett'] === true || $data['Fett'] === 'true')$fett = true; + } + $unterstrichen = false; + if(isset($data['Unterstrichen'])) + { + $unterstrichen = $data['Unterstrichen']; + } + $this->underline = $unterstrichen; + + switch($zwischenpositionen[$i]['postype']) + { + case "gruppensumme": + case "gruppensummemitoptionalenpreisen": + $maxpos_untergruppedrueber = (int)$this->app->DB->Select("SELECT pos FROM beleg_zwischenpositionen WHERE doctype='".$this->doctype."' AND doctypeid='".$this->doctypeid."' AND pos < '$pos' AND postype='gruppe' ORDER by pos DESC LIMIT 1"); + + if($this->doctype=="angebot") + { + $subwhere = " AND (explodiert_parent = 0 OR 0 = ifnull((SELECT id FROM angebot_position WHERE id = ap.explodiert_parent AND berechnen_aus_teile = 1 LIMIT 1),0))"; + if($zwischenpositionen[$i]['postype'] !== 'gruppensummemitoptionalenpreisen'){ + $subwhere = ' AND optional!=1 '.$subwhere; + } + $zwischenpositionen[$i]['postype'] = 'gruppensumme'; + } + if($this->doctype=="bestellung") + { + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM(preis*menge) FROM ".$this->doctype."_position WHERE ".$this->doctype."='".$this->doctypeid."' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); + }else{ + $anzeigesteuerbelege = $this->app->DB->Select("SELECT anzeigesteuerbelege FROM projekt WHERE id = ".$projekt); + if( + ( + ( + $this->anrede=="firma" || + $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt,$this->table,$this->id) || + $this->doctype=="bestellung" || + $this->getStyleElement("immernettorechnungen",$projekt)=="1" || + $anzeigesteuerbelege =='1' + ) && + $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") || + $this->ust_befreit + ) { + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); + }else{ + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge)* + (1 + if(ifnull(steuersatz,-1) < 0,if(umsatzsteuer = 'befreit',0,if(umsatzsteuer = 'ermaessigt',$umsatzsteuerermaessigt,$umsatzsteuernormal)),steuersatz + )/100) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' AND sort >'$maxpos_untergruppedrueber' $subwhere")); + } + } + break; + default: + //zwischensumme + if($this->doctype=="angebot") + { + $subwhere = " AND optional!=1 AND (explodiert_parent = 0 OR 0 = ifnull((SELECT id FROM angebot_position WHERE id = ap.explodiert_parent AND berechnen_aus_teile = 1 LIMIT 1),0))"; + } + if($this->doctype=="bestellung") + { + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM(preis*menge) FROM ".$this->doctype."_position WHERE ".$this->doctype."='".$this->doctypeid."' AND sort <='$pos' $subwhere")); + }else{ + if((($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt,$this->table,$this->id) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") || $this->ust_befreit ) { + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' $subwhere")); + }else{ + $summe = $this->formatMoney($this->app->DB->Select("SELECT SUM((preis-(preis/100*rabatt))*menge)* + (1 + if(ifnull(steuersatz,-1) < 0,if(umsatzsteuer = 'befreit',0,if(umsatzsteuer = 'ermaessigt',$umsatzsteuerermaessigt,$umsatzsteuernormal)),steuersatz + )/100) FROM " . $this->doctype . "_position ap WHERE " . $this->doctype . "='" . $this->doctypeid . "' AND sort <='$pos' $subwhere")); + } + } + break; + } + + $beschriftung_zeile = ucfirst($zwischenpositionen[$i]['postype']); + + if($data['name']=="") + $html = ($fett?"":"").$beschriftung_zeile.($fett?"":""); + else + $html = ($fett?"":"").$data['name'].($fett?"":""); + if(!empty($data['Abstand_Oben'])) + { + $this->Ln((int)$data['Abstand_Oben']); + }else{ + $this->Ln(0); + } + $x = $this->GetX(); + + if(isset($data['Abstand_Links']) && $data['Abstand_Links'] > 0) + { + $abstand_links = (int)$data['Abstand_Links']; + $this->SetX($x+$abstand_links); + }else{ + $abstand_links = $posWidth +$itemNoWidth; + } + + $this->SetX($x+$abstand_links); + $this->Cell($descWidth,4,$this->WriteHTML($html)); + $this->SetX($x+$abstand_links+$descWidth); + //$this->SetX($x); + + $rahmen_links = false; + $rahmen_rechts = false; + $rahmen_oben = false; + $rahmen_unten = false; + if(isset($data['Rahmen_Links'])) + { + $rahmen_links = $data['Rahmen_Links']; + } + if(isset($data['Rahmen_Rechts'])) + { + $rahmen_rechts = $data['Rahmen_Rechts']; + } + if(isset($data['Rahmen_Oben'])) + { + $rahmen_oben = $data['Rahmen_Oben']; + } + if(isset($data['Rahmen_Unten'])) + { + $rahmen_unten = $data['Rahmen_Unten']; + } + $rahmen = ''; + if($rahmen_links)$rahmen .= 'L'; + if($rahmen_rechts)$rahmen .= 'R'; + if($rahmen_oben)$rahmen .= 'T'; + if($rahmen_unten)$rahmen .= 'B'; + $ausrichtung = 'R'; + if(isset($data['Text_Ausrichtung'])) + { + $ausrichtung = $data['Text_Ausrichtung']; + } + $this->Cell($priceWidth+$amWidth+$taxWidth+$priceWidth,4,$summe,$rahmen,0,$ausrichtung); + if(!empty($data['Abstand_Unten'])) + { + $this->Ln((int)$data['Abstand_Unten']); + }else{ + $this->Ln(10); + } + $this->SetFontSize($schriftgroesse_alt); + $this->underline = false; + break; + } + } + return $ret; + } + + + /* + totals ( + totalArticles - Summe aller Artikelpreise + modeOfDispatch - Versandart + priceOfDispatch - Versandkosten + modeOfPayment - Zahlungsweise + priceOfPayment - Kosten der Zahlungsweise + total = totalArticles + priceOfDispatch + priceOfPayment + totalTaxV - Summe voller Steuersatz + totalTaxR - Summe reduzierter Steuersatz + ) + */ + public function renderTotals() { + + if($this->doctype === 'angebot' && $this->app->DB->Select("SELECT gesamtsummeausblenden FROM angebot WHERE id = '".$this->doctypeid."'")){ + $this->Ln(8); + return ''; + } + + if($this->doctype === 'inventur' && $this->app->DB->Select("SELECT noprice FROM inventur WHERE id = '".$this->id."'")){ + $this->Ln(8); + return ''; + } + + $this->SetY($this->GetY()+1); + + $differenz_wegen_abstand = $this->getStyleElement('abstand_gesamtsumme_lr'); + + if($this->doctype!='lieferschein' && $this->doctype!='arbeitsnachweis' && $this->doctype!='preisanfrage') { + //$this->Line(110, $this->GetY(), 190, $this->GetY()); + $this->Ln(1); + $this->SetFont($this->GetFont(),'',$this->getStyleElement('schriftgroesse_gesamt')); + $this->Cell($differenz_wegen_abstand,2,'',0); + if($this->getStyleElement('kleinunternehmer')!='1' && $this->doctype!='zahlungsavis'){ + $nettoText = $this->app->erp->Beschriftung('dokument_gesamtnetto'); + $nettoAmount = $this->formatMoney(round((double)$this->totals['totalArticles'], 2), 2).' '.$this->waehrung; + $doctype = $this->doctype; + $doctypeid = !empty($this->doctypeid)?$this->doctypeid: $this->id; + $this->app->erp->RunHook('class_briefpapier_render_netto', 4, $doctype, $doctypeid, $nettoText, $nettoAmount); + $this->Cell(30,5,$nettoText,0,0,'L'); + $this->Cell(40,5,$nettoAmount,0,'L','R'); + } else { + //kleinunzernehmer + $this->Cell(30,5,'',0,0,'L'); + $this->Cell(40,5,'',0,'L','R'); + } + $this->Ln(); + + if(isset($this->totals['modeOfDispatch'])) { + $versand = 'Versand: '.$this->totals['modeOfDispatch']; + } + else { + $versand = 'Versandkosten: '; + } + if(isset($this->totals['priceOfDispatch'])) { + $this->Cell($differenz_wegen_abstand,2,'',0); + $this->Cell(30,5,$versand,0,'L','L'); + $this->Cell(40,5,$this->formatMoney((double)$this->totals['priceOfDispatch'], 2).' '.$this->waehrung,0,'L','R'); + } + //$this->Ln(); + + if(isset($this->totals['priceOfPayment']) && $this->totals['priceOfPayment']!='0.00'){ + $this->Cell($differenz_wegen_abstand,2,'',0); + $this->Cell(30,5,$this->totals['modeOfPayment'],0,'L','L'); + $this->Cell(40,5,$this->formatMoney((double)$this->totals['priceOfPayment'], 2).' '.$this->waehrung,0,'L','R'); + $this->Ln(); + } + + $this->SetY($this->GetY()); + $this->SetFont($this->GetFont(),'',$this->getStyleElement("schriftgroesse_gesamt_steuer")); + + + if(isset($this->totals['totalTaxV']) && $this->totals['totalTaxV']!="0.00"){ + $this->Cell($differenz_wegen_abstand,1,'',0); + + if($this->getStyleElement('kleinunternehmer')!='1'){ + if(!empty($this->doctype) && !empty($this->id) && is_numeric($this->id)){ + $projekt = $this->app->DB->Select('SELECT projekt FROM `' . $this->doctype . '` WHERE id = ' . $this->id); + $adresse = $this->app->DB->Select('SELECT adresse FROM `' . $this->doctype . '` WHERE id = ' . $this->id); + }else{ + $projekt = 0; + $adresse = 0; + } + + if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + { + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$this->app->erp->GetSteuersatzNormal(false,$this->id,$this->table).' %',0,'L','L'); //1 + } + else { + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$this->app->erp->GetSteuersatzNormal(false,$this->id,$this->table).' %',0,'L','L'); + } + $this->Cell(40,3,$this->formatMoney((double)$this->totals['totalTaxV'], 2).' '.$this->waehrung,0,'L','R'); + } else { + //kleinunternehmer + $this->Cell(30,3,'',0,'L','L'); + $this->Cell(40,3,'',0,'L','R'); + } + $this->Ln(); + } + $projekt = $this->projekt; + $adresse = $this->app->DB->Select("SELECT adresse FROM ".($this->table?$this->table:$this->doctype)." WHERE id = '".$this->id."' LIMIT 1"); + if(!empty($this->totals['totalTaxR']) && $this->totals['totalTaxR']!='0.00'){ + $this->Cell($differenz_wegen_abstand,1,'',0); + + if($this->getStyleElement('kleinunternehmer')!='1'){ + + if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + { + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$this->app->erp->GetSteuersatzErmaessigt(false,$this->id,$this->table).' %',0,'L','L'); //1 + } + else { + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$this->app->erp->GetSteuersatzErmaessigt(false,$this->id,$this->table).' %',0,'L','L'); + } + + $this->Cell(40,3,$this->formatMoney(round((double)$this->totals['totalTaxR'],2), 2).' '.$this->waehrung,0,'L','R'); + } else { + //kleinunternehmer + $this->Cell(30,3,'',0,'L','L'); + $this->Cell(40,3,"",0,'L','R'); + } + + $this->Ln(); + } + + if(!empty($this->totals['summen'])) + { + ksort($this->totals['summen'], SORT_NUMERIC); + foreach($this->totals['summen'] as $k => $value) + { + if($value == 0) + { + continue; + } + $this->Cell($differenz_wegen_abstand,1,'',0); + + if($this->getStyleElement('kleinunternehmer')!='1'){ + if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + { + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$k.' %',0,'L','L'); //1 + }else { + //$this->Cell(30,3,$this->app->erp->Beschriftung('dokument_inklmwst').' '.$k.' %',0,'L','L'); 09.12.2018 ab heute auskommentiert wegen 829087 + $this->Cell(30,3,$this->app->erp->Beschriftung('dokument_zzglmwst').' '.$k.' %',0,'L','L'); + } + + $this->Cell(40,3,$this->formatMoney(round($value,2), 2).' '.$this->waehrung,0,'L','R'); + } else { + //kleinunternehmer + $this->Cell(30,3,'',0,'L','L'); + $this->Cell(40,3,"",0,'L','R'); + } + + $this->Ln(); + + } + + } + + if(!isset($this->totals['totalTaxR']) && !isset($this->totals['totalTaxV']) && !isset($this->totals['summen']) && $this->doctype!="zahlungsavis") + { + $this->Cell($differenz_wegen_abstand,3,'',0); + + if($this->getStyleElement('kleinunternehmer')!='1') + { + if($this->app->erp->AnzeigeBelegNettoAdresse($this->anrede, $this->doctype, $projekt, $adresse,$this->id)) + //if(($this->anrede=="firma" || $this->app->erp->AnzeigeBelegNetto($this->anrede,$projekt) || $this->doctype=="bestellung" || $this->getStyleElement("immernettorechnungen",$projekt)=="1") + // && $this->getStyleElement("immerbruttorechnungen",$projekt)!="1") + { + if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland + { + $this->Cell(30, 3, $this->app->erp->Beschriftung('dokument_zzglmwst') . ' 0.00 %', 0, 'L', 'L'); //1 + } + } + else { + if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland + { + $this->Cell(30, 3, $this->app->erp->Beschriftung('dokument_inklmwst') . ' 0.00 %', 0, 'L', 'L'); + } + } + + if(!($this->ust_befreit==3 && $this->getStyleElement('steuerfrei_inland_ausblenden')=='1')) //steuerfrei inland + { + $this->Cell(40, 3, '0,00 ' . $this->waehrung, 0, 'L', 'R'); + } + } else { + //kleinunternehmer + $this->Cell(30,3,'',0,'L','L'); + $this->Cell(40,3,'',0,'L','R'); + } + $this->Ln(); + } + $this->SetY($this->GetY()+2); + //$this->Line(110, $this->GetY(), 190,$this->GetY()); + } + + $this->SetFont($this->GetFont(),'B',$this->getStyleElement('schriftgroesse_gesamt')); + $this->Cell($differenz_wegen_abstand,5,'',0); + if($this->doctype=='offer'){ + $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); + } + elseif($this->doctype=='creditnote'){ + $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); + } + else if($this->doctype=='arbeitsnachweis'){ + $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); + } + else if($this->doctype=='zahlungsavis'){ + $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); + } + else{ + $this->Cell(30, 5, $this->app->erp->Beschriftung('dokument_gesamt_total'), 0, 'L', 'L'); + } + + if($this->doctype=='arbeitsnachweis'){ + $this->Cell(40, 5, $this->totals['total'] . ' ', 0, 'L', 'R'); + } + else { + if($this->getStyleElement('kleinunternehmer')!='1'){ + $this->Cell(40, 5, $this->formatMoney(round((double)$this->totals['total'], 2), 2) . ' ' . $this->waehrung, 0, 'L', 'R'); + } + else{ + $this->Cell(40, 5, $this->formatMoney(round((double)$this->totals['totalArticles'], 2), 2) . ' ' . $this->waehrung, 0, 'L', 'R'); + } + } + + $this->Ln(); + if($this->getStyleElement('briefpapier_ohnedoppelstrich')!='1') + { + $this->Line($differenz_wegen_abstand+5, $this->GetY(), 210-$this->getStyleElement('abstand_seitenrandrechts'),$this->GetY()); + $this->Line($differenz_wegen_abstand+5, $this->GetY()+1, 210-$this->getStyleElement('abstand_seitenrandrechts'),$this->GetY()+1); + } + + $this->SetY($this->GetY()+10); + } + + function displayAnhaenge($output='D') + { + SuperFPDF::__construct('P','mm','A4'); + $this->seite_von_sichtbar = 1; + + + + // if($this->getStyleElement("schriftart")!="") + // $this->SetFont($this->getStyleElement("schriftart")); + + if($this->getStyleElement('schriftart')!='' && $this->getStyleElement('schriftart')!='Arial' && + $this->getStyleElement('schriftart')!='Courier' && $this->getStyleElement('schriftart')!='Helvetica' + && $this->getStyleElement('schriftart')!='Times' && $this->getStyleElement('schriftart')!='Arial'){ + $this->AddFont($this->getStyleElement('schriftart'),'',strtolower($this->getStyleElement('schriftart')).'.php'); + $this->AddFont($this->getStyleElement('schriftart'),'I',strtolower($this->getStyleElement('schriftart')).'.php'); + $this->AddFont($this->getStyleElement('schriftart'),'B',strtolower($this->getStyleElement('schriftart')).'.php'); + } + if(!empty($this->addpdf) && is_array($this->addpdf)) + { + + foreach($this->addpdf as $addpdf) + { + + $filename = $addpdf; + + $pn = $this->setSourceFile($filename); + //$this->AddPage(); + //$this->SetXY(0,0); + for($i = 1; $i <= $pn ; $i++) + { + $fn =& $this->current_filename; + $mediabox = $this->parsers[$fn]->getPageMediaBox($i); + //$this->app->erp->LogFile(addslashes(json_encode($mediabox))); + if($i >= 1) + { + if(isset($mediabox['w']) && (float)$mediabox['w'] > 210.1 ) + { + $this->AddPage('L'); + } else { + $this->AddPage(); + } + $this->SetXY(0,0); + } + $tplidx = $this->ImportPage($i); + $this->useTemplate($tplidx); + } + } + } + $this->filename = $this->app->erp->Dateinamen($this->filename); + $this->Output($this->filename,$output); + exit; + } + + /** + * @param float $value + * @param int|null $decimals + * + * @return string + */ + protected function formatMoney($value, $decimals = null) + { + $decimals = $decimals !== null ? (int)$decimals : $this->anzahlkomma; + $currency = $this->waehrung; + return $this->app->erp->formatMoney($value, $currency,$decimals); + } +} diff --git a/www/pages/ajax.php b/www/pages/ajax.php index bb6b9791..36137e01 100644 --- a/www/pages/ajax.php +++ b/www/pages/ajax.php @@ -1,5356 +1,5359 @@ -app=$app; - if($intern) { - return; - } - $this->app->ActionHandlerInit($this); - - $this->app->ActionHandler("filter","AjaxFilter"); - $this->app->ActionHandler("table","AjaxTable"); - $this->app->ActionHandler("labels","AjaxLabels"); - $this->app->ActionHandler("validator","AjaxValidator"); - $this->app->ActionHandler("ansprechpartner","AjaxAnsprechpartner"); - $this->app->ActionHandler("lieferadresse","AjaxLieferadresse"); - $this->app->ActionHandler("verzolladresse","AjaxVerzolladresse"); - $this->app->ActionHandler("adressestammdaten","AjaxAdresseStammdaten"); - $this->app->ActionHandler("tooltipsuche","AjaxTooltipSuche"); - $this->app->ActionHandler("tableposition","AjaxTablePosition"); - $this->app->ActionHandler("tablefilter", "AjaxTableFilter"); - $this->app->ActionHandler("articlematrixselection", "AjaxArticleMatrixSelection"); - $this->app->ActionHandler("moduleunlock", "AjaxModuleUnlock"); - $this->app->ActionHandler("thumbnail", "AjaxThumbnail"); - $this->app->ActionHandler("autosavekonfiguration", "AjaxAutoSaveKonfiguration"); - $this->app->ActionHandler("autosaveuserparameter", "AjaxAutoSaveUserParameter"); - $this->app->ActionHandler("getuserparameter","AjaxGetUserParameter"); - $this->app->ActionHandler("getdateititel","AjaxGetDateiTitel"); - $this->app->ActionHandler("editdateititel","AjaxEditDateiTitel"); - $this->app->ActionHandler("profilbild","AjaxProfilbild"); - $this->app->ActionHandler("getgewicht","AjaxGetGewicht"); - $this->app->ActionHandler("upload","AjaxUpload"); - $this->app->ActionHandler("sidebar","AjaxSidebar"); - $this->app->ActionHandler("livetable","AjaxLiveTable"); - $this->app->ActionHandlerListen($app); - } - - /** - * @return JsonResponse - */ - public function AjaxSidebar(): JsonResponse - { - $userId = $this->app->User->GetID(); - $cmd = $this->app->Secure->GetGET('cmd'); - - switch ($cmd) { - case 'set_collapsed': - $state = $this->app->Secure->GetGET('value') === 'true'; - /** @var Xentral\Modules\User\Service\UserConfigService $userConfig */ - $userConfig = $this->app->Container->get('UserConfigService'); - $userConfig->set('sidebar_collapsed', $state,$userId); - $data = ['success' => true, 'collapsed' => $state]; - break; - - default: - $data = ['success' => false, 'error' => 'Incomplete request']; - break; - } - - return new JsonResponse( - $data, - $data['success'] === false ? JsonResponse::HTTP_BAD_REQUEST : JsonResponse::HTTP_OK - ); - } - - public function AjaxUpload() - { - $fromUrl = $this->app->Secure->GetGET('fromurl'); - $fromUrl = pathinfo($fromUrl); - $fromUrl = $fromUrl['basename']; - if(strpos($fromUrl, 'index.php?') === 0) { - $fromUrl = substr($fromUrl, 10); - } - $fromUrl = explode('&', $fromUrl); - $parts = []; - foreach($fromUrl as $urlpart) { - $urlpartA = explode('=', $urlpart); - $parts[$urlpartA[0]] = isset($urlpartA[1])?$urlpartA[1]:''; - } - if(!empty($_FILES)) { - $this->app->erp->RunHook('ajaxupload', 1, $parts); - } - - header('Content-Type: application/json'); - echo json_encode([]); - $this->app->ExitXentral(); - } - - public function AjaxGetGewicht() - { - $seriennummer = $this->app->Secure->GetPOST('seriennummer'); - ///$mindestgewicht = (float)$this->app->Secure->GetPOST('mindestgewicht'); - $gewicht = str_replace(',','.',$this->app->erp->GetAdapterboxAPIWaage($seriennummer)); - if(!is_numeric($gewicht)) { - $gewicht = 0; - } - //if($gewicht < $mindestgewicht)$gewicht = $mindestgewicht; - echo json_encode(array('gewicht'=>number_format($gewicht ,1,'.',''))); - $this->app->ExitXentral(); - } - - public function AjaxLabels() - { - /** @var \Xentral\Modules\Label\LabelModule $labelModule */ - $labelModule = $this->app->Container->get('LabelModule'); - - $cmd = $this->app->Secure->GetGET('cmd'); - switch ($cmd) { - - case 'collect': - // Aktive Labels für eine DataTable-Seite abrufen - $collection = $this->app->Secure->GetPOST('collection'); - - $data = $this->FindLabelsByCollection($collection); - header('Content-Type: application/json'); - echo json_encode(['success' => true, 'data' => $data]); - $this->app->erp->ExitWawi(); - break; - - case 'list': - // Label-Typen auflisten + Zugewiesene Typen markieren - $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); - $referenceTable = $this->app->Secure->GetPOST('reference_table'); - - $labelTypes = $this->FindLabelTypesByReference($referenceTable, $referenceId); - header('Content-Type: application/json'); - echo json_encode($labelTypes); - $this->app->erp->ExitWawi(); - break; - - case 'assign': - // Label-Zuweisung erstellen - $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); - $referenceTable = $this->app->Secure->GetPOST('reference_table'); - $labelType = $this->app->Secure->GetPOST('type'); - - try { - $labelModule->assignLabel($referenceTable, $referenceId, $labelType); - } catch (LabelExceptionInterface $exception) { - header('HTTP/1.1 404 Not Found'); - header('Content-Type: application/json'); - echo json_encode(['success' => false, 'error' => 'Zuweisung nicht möglich. Fehler: ' . $exception->getMessage()]); - $this->app->erp->ExitWawi(); - return; - } - - // Ausgabe - $data = $this->FindLabelsByReference($referenceTable, $referenceId); - header('Content-Type: application/json'); - echo json_encode(['success' => true, 'data' => $data]); - $this->app->erp->ExitWawi(); - break; - - case 'unassign': - // Label-Zuweisung löschen - $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); - $referenceTable = $this->app->Secure->GetPOST('reference_table'); - $labelType = $this->app->Secure->GetPOST('type'); - - try { - $labelModule->unassignLabel($referenceTable, $referenceId, $labelType); - } catch (LabelExceptionInterface $exception) { - header('HTTP/1.1 404 Not Found'); - header('Content-Type: application/json'); - echo json_encode(['success' => false, 'error' => 'Zuweisung löschen nicht möglich. Fehler: ' . $exception->getMessage()]); - $this->app->erp->ExitWawi(); - return; - } - - // Ausgabe - $data = $this->FindLabelsByReference($referenceTable, $referenceId); - header('Content-Type: application/json'); - echo json_encode(['success' => true, 'data' => $data]); - $this->app->erp->ExitWawi(); - break; - } - } - - /** - * @param string $referenceTable - * @param int $referenceId - * - * @return array - */ - protected function FindLabelsByReference($referenceTable, $referenceId) - { - /** @var \Xentral\Modules\Label\LabelModule $labelModule */ - $labelModule = $this->app->Container->get('LabelModule'); - $labels = $labelModule->findLabelsByReference($referenceTable, $referenceId); - - $target = sprintf('labels-%s-%s', $referenceTable, $referenceId); - $result = [$target => []]; - - foreach ($labels as $item) { - $item['target'] = $target; - $item['title'] = htmlspecialchars($item['title']); - $item['bgcolor'] = $item['hexcolor']; - unset($item['hexcolor']); - unset($item['id']); - - $result[$target][] = $item; - } - - return $result; - } - - /** - * @param array $collection - * - * @return array - */ - protected function FindLabelsByCollection($collection) - { - /** @var \Xentral\Modules\Label\LabelModule $labelModule */ - $labelModule = $this->app->Container->get('LabelModule'); - - $result = []; - foreach ($collection as $referenceTable => $referenceIds) { - $referenceTable = (string)$referenceTable; - if (empty($referenceTable)) { - continue; - } - - // Für jede angefragte Referenz ein Ergebnis liefern; Leeres Ergebnis als Default - foreach ($referenceIds as $referenceId) { - $target = sprintf('labels-%s-%s', $referenceTable, $referenceId); - $result[$target] = []; - } - - // Label-Gruppen anlegen - $labelGroupId = $this->app->DB->Select( - "SELECT lg.id FROM label_group AS lg WHERE lg.group_table = '{$referenceTable}'" - ); - if (empty($labelGroupId)) { - $groupTitle = ucwords($referenceTable); - $this->app->DB->Insert( - "INSERT INTO label_group (id, group_table, title, created_at) - VALUES (NULL, '{$referenceTable}', '{$groupTitle}', CURRENT_TIMESTAMP)" - ); - } - - $labels = $labelModule->findLabelsByReferences($referenceTable, $referenceIds); - foreach ($labels as $item) { - $target = sprintf('labels-%s-%s', $item['reference_table'], $item['reference_id']); - if (!isset($result[$target])) { - $result[$target] = []; - } - $item['target'] = $target; - $item['title'] = htmlspecialchars($item['title']); - $item['bgcolor'] = $item['hexcolor']; - $item['referenceTable'] = $item['reference_table']; - $item['referenceId'] = $item['reference_id']; - unset($item['reference_table']); - unset($item['reference_id']); - unset($item['hexcolor']); - unset($item['id']); - - $result[$target][] = $item; - } - } - - return $result; - } - - /** - * @param string $referenceTable - * @param int $referenceId - * - * @return array - */ - protected function FindLabelTypesByReference($referenceTable, $referenceId) - { - /** @var \Xentral\Modules\Label\LabelModule $labelModule */ - $labelModule = $this->app->Container->get('LabelModule'); - $labelTypes = $labelModule->findLabelTypesByReference($referenceTable, $referenceId); - - foreach ($labelTypes as &$labelType) { - $labelType['id'] = (int)$labelType['id']; - $labelType['target'] = 'labels-' . $referenceTable . '-' . $referenceId; - $labelType['selected'] = !empty($labelType['label_id']); - if ((int)$labelType['label_id'] > 0) { - $labelType['key'] = 'label-' . (int)$labelType['label_id']; - } - $labelType['bgcolor'] = $labelType['hexcolor']; - $labelType['referenceTable'] = $referenceTable; - $labelType['referenceId'] = $referenceId; - unset($labelType['hexcolor']); - } - - return $labelTypes; - } - - public function AjaxValidator() - { - $rule = $this->app->Secure->GetPOST('rule'); - $value = $this->app->Secure->GetPOST('value'); - $mandatoryId = (int)$this->app->Secure->GetPOST('mandatoryid'); - - /** @var \Xentral\Modules\MandatoryFields\MandatoryFieldsModule $mandatoryFields */ - $mandatoryFields = $this->app->Container->get('MandatoryFieldsModule'); - - try{ - $data = $mandatoryFields->validate($rule,$value,$mandatoryId)->toArray(); - } catch(UnknownTypeException $e){ - $data = ['error' => true, 'message' => 'Validatorregel nicht gültig.']; - } catch(MandatoryFieldNotFoundException $e){ - $data = ['error' => true, 'message' => 'Die Validierungsregel konnte nicht gefunden werden.']; - } - header('Content-Type: application/json'); - echo json_encode($data); - $this->app->ExitXentral(); - } - - public function AjaxGetDateiTitel() - { - $status = 0; - $cmds = $this->CmdList(); - $cmd = $this->app->Secure->GetPOST('typ'); - $data = null; - if($this->app->erp->RechteVorhanden($cmd, 'dateien')) - { - $id = $this->app->Secure->GetPOST('id'); - $objekt = $this->app->Secure->GetPOST('typ'); - $parameter = $this->app->Secure->GetPOST('parameter'); - if($objekt === 'adresse'){ - $objekt = 'Adressen'; - } - - $data = $this->app->DB->SelectRow( - "SELECT d.*, s.subjekt - FROM datei AS d - LEFT JOIN datei_stichwoerter AS s ON d.id=s.datei - LEFT JOIN datei_version AS v ON v.datei=d.id - WHERE s.objekt LIKE '$objekt' AND s.parameter='$parameter' AND d.geloescht=0 AND d.id = '$id' - LIMIT 1" - ); - - - $module = strtolower($objekt); - if($module === 'adressen'){ - $module = 'adresse'; - } - - $typen = $this->app->erp->getDateiTypen($module); - $found = false; - foreach($typen as $typ) { - if($typ['wert'] === $data['subjekt']) { - $found = true; - break; - } - } - $subjekthtml = ''; - if(!$found) { - $subjekthtml = ''; - } - foreach($typen as $typ) { - $subjekthtml .= ''; - } - /* - $subjekthtml = ''; - if($module==='adresse') - { - $subjekthtml .= ''; - } - - if($module!='') - { - $tmp = $this->app->DB->SelectArr("SELECT * FROM datei_stichwortvorlagen WHERE modul='$module' ORDER by beschriftung"); - $ctmp = $tmp?count($tmp):0; - for($i=0;$i<$ctmp;$i++) { - $subjekthtml .= ''; - } - } - - $tmp = $this->app->DB->SelectArr("SELECT * FROM datei_stichwortvorlagen WHERE modul='' ORDER by beschriftung"); - $ctmp = $tmp?count($tmp):0; - for($i=0;$i<$ctmp;$i++) { - $subjekthtml .= ''; - } - */ - - if($data){ - $data['subjekthtml'] = $subjekthtml; - } - - } - - echo json_encode($data); - exit; - } - - public function AjaxEditDateiTitel() - { - $status = 0; - $cmds = $this->CmdList(); - $cmd = $this->app->Secure->GetPOST('typ'); - $data = null; - if($this->app->erp->RechteVorhanden($cmd, 'dateien')) - { - $id = $this->app->Secure->GetPOST('id'); - $objekt = $this->app->Secure->GetPOST('typ'); - $parameter = $this->app->Secure->GetPOST('parameter'); - $titel = $this->app->Secure->GetPOST('titel'); - $beschreibung = $this->app->Secure->GetPOST('beschreibung'); - $subjekt = $this->app->Secure->GetPOST('subjekt'); - if($objekt == 'adresse') - { - $objekt = 'Adressen'; - } - $ersteller = $this->app->DB->real_escape_string($this->app->User->GetName()); - $datei = $this->app->DB->SelectArr("SELECT d.id, s.id as sid FROM datei d LEFT JOIN datei_stichwoerter s ON d.id=s.datei LEFT JOIN datei_version v ON v.datei=d.id WHERE s.objekt LIKE '$objekt' AND s.parameter='$parameter' AND d.geloescht=0 AND d.id = '$id' LIMIT 1"); - if($datei) - { - $sid = $datei[0]['sid']; - if($subjekt && $sid) - { - $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = '".$this->app->DB->real_escape_string($subjekt)."' WHERE id = '$sid' LIMIT 1"); - } - $this->app->DB->Update("UPDATE datei SET titel = '$titel', beschreibung = '$beschreibung' WHERE id = '$id' LIMIT 1"); - if(!empty($_FILES['datei']) && $_FILES['datei']['tmp_name']!='') - { - $dateiname = $_FILES['datei']['name']; - $this->app->erp->AddDateiVersion($id,$ersteller,$dateiname, $beschreibung,$_FILES['datei']['tmp_name']); - } - $status = 1; - } - } - - echo json_encode(array('status'=>$status)); - exit; - } - - protected function CmdList() - { - return array('artikel','adresse','angebot','auftrag','rechnung','gutschrift','lieferschein','bestellung','projekt','produktion','anfrage','reisekosten','kalkulation','serviceauftrag','verbindlichkeit','kasse','geschaeftsbrief_vorlagen','wiedervorlage','wiki'); - } - - /** - * @param int $userId - * @param string|null $alt - * @param string|null $imgClass - * @param int|null $widthHeight - * - * @return string - */ - public function getProfileHtml($userId, $alt = null, $imgClass=null, $widthHeight = null): string - { - $userId = (int)$userId; - $addressId = 0; - $shortUserName = ''; - $user = $userId <= 0?null:$this->app->DB->SelectRow( - sprintf( - "SELECT u.adresse, u.`username` - FROM `user` AS `u` - WHERE u.id=%d - LIMIT 1", - $userId - ) - ); - if(!empty($user)) { - $addressId = $user['adresse']; - $shortUserName = substr($user['username'],0,2); - } - - $fileId = $this->getFileVersionFromProfileImage($addressId); - if($this->getProfilePictureFromFileVersionId($fileId) !== null) { - $imgString = sprintf( - '%s'; - } - - return sprintf('%s', $shortUserName); - } - - /** - * @param int $addressId - * - * @return int|null - */ - public function getFileVersionFromProfileImage($addressId): ?int - { - $addressId = (int)$addressId; - if($addressId <= 0) { - return null; - } - $fileVersionId = (int)$this->app->DB->Select( - sprintf( - "SELECT dv.id - FROM `datei_stichwoerter` AS `ds` - INNER JOIN `datei` AS `d` ON ds.datei = d.id - INNER JOIN `datei_version` AS `dv` ON dv.datei = d.id - WHERE d.geloescht = 0 AND objekt LIKE 'Adressen' AND parameter = '%d' AND subjekt LIKE 'Profilbild' - ORDER BY dv.id DESC - LIMIT 1", - $addressId - ) - ); - if($fileVersionId <= 0) { - return null; - } - - return $fileVersionId; - } - - /** - * @param int $fileVersionId - * - * @return bool - */ - public function getProfilePictureFromFileVersionId($fileVersionId): ?array - { - $fileVersionId = (int)$fileVersionId; - if($fileVersionId <= 0) { - return null; - } - $userdata = isset($this->app->Conf->WFuserdata)?$this->app->Conf->WFuserdata:str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME'])."../userdata"; - $path = $userdata.'/dms/'.$this->app->Conf->WFdbname; - $cachefolder = $path.'/cache'; - $path = $this->app->erp->GetDMSPath($fileVersionId, $path); - $cachefolder = $this->app->erp->GetDMSPath($fileVersionId.'_100_100', $cachefolder, true); - if(!file_exists($cachefolder.'/'.$fileVersionId.'_100_100')) { - if(file_exists($path.'/'.$fileVersionId)) { - $type = mime_content_type($path.'/'.$fileVersionId); - switch($type) { - case 'image/jpg': - case 'image/jpeg': - $img = new image($this->app); - $str = $img->scaledPicByFileId($fileVersionId, 100, 100); - if((string)$str === '') { - return null; - } - return [ - 'header' => 'Content-type: image/jpg', - 'image' => $str, - ]; - break; - case 'image/png': - $img = new image($this->app); - $str = $img->scaledPicByFileId($fileVersionId, 100, 100); - if((string)$str === '') { - return null; - } - return [ - 'header' => 'Content-type: image/png', - 'image' => $str, - ]; - break; - case 'image/gif': - $img = new image($this->app); - $str = $img->scaledPicByFileId($fileVersionId, 100, 100); - if((string)$str === '') { - return null; - } - return [ - 'header' => 'Content-type: image/gif', - 'image' => $str, - ]; - break; - case 'application/pdf': - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); - if((string)$str === '') { - return null; - } - - return [ - 'header' => 'Content-type: image/svg', - 'picture' => $str, - ]; - break; - } - } - } - if(file_exists($cachefolder.'/'.$fileVersionId.'_100_100')){ - $type = mime_content_type($cachefolder . '/' . $fileVersionId . '_100_100'); - if(strpos($type, 'image') !== false){ - $str = file_get_contents($cachefolder . '/' . $fileVersionId . '_100_100'); - if((string)$str === '') { - return null; - } - - return [ - 'header' => 'Content-type: ' . $type, - 'picture' => $str, - ]; - } - } - - return null; - } - - public function AjaxProfilbild() - { - $userId = (int)$this->app->Secure->GetGET('id'); - $addressId = $userId === $this->app->User->GetID() - ?$this->app->User->GetAdresse(): - (int)$this->app->DB->Select(sprintf('SELECT `adresse` FROM `user` WHERE `id` = %d', $userId)); - $dateiversion = $this->getFileVersionFromProfileImage($addressId); - $picture = $this->getProfilePictureFromFileVersionId($dateiversion); - if($picture !== null) { - header($picture['header']); - echo $picture['picture']; - exit; - } - - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/profil.png'); - header('Content-type: image/png'); - echo $str; - exit; - } - - public function AjaxThumbnail() - { - $cmds = $this->CmdList(); - $cmd = trim($this->app->Secure->GetGET('cmd')); - $id = (int)$this->app->Secure->GetGET('id'); - - if(!empty($cmd) && $id - && (!in_array($cmd, $cmds) || (in_array($cmd, $cmds) && $this->app->erp->RechteVorhanden($cmd,'dateien')))) { - $datei = $this->app->DB->SelectRow( - sprintf( - "SELECT dv.id, ds.parameter, dv.dateiname - FROM datei_version AS dv - INNER JOIN datei_stichwoerter ds ON ds.datei = dv.datei - WHERE dv.datei = %d AND (ds.objekt like '%s'".($cmd === 'adresse'?" OR ds.objekt like 'Adressen' ":'').") - ORDER BY dv.datei DESC, dv.version DESC - LIMIT 1", - $id, $cmd - ) - ); - if(empty($datei)) { - if ($this->app->erp->Firmendaten('iconset_dunkel')) { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); - } else { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); - } - header('Content-type: image/png'); - echo $str; - exit; - } - if(!empty($datei['parameter'])) { - if($cmd === 'projekt') { - if(!$this->app->erp->UserProjektRecht($datei['parameter'])) { - if ($this->app->erp->Firmendaten('iconset_dunkel')) { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); - } else { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); - } - header('Content-type: image/png'); - echo $str; - exit; - } - } - else{ - $projekt = $this->app->DB->Select( - sprintf( - 'SELECT `projekt` FROM `%s` WHERE `id` = %d LIMIT 1', - $cmd, $datei[0]['parameter'] - ) - ); - if(!$this->app->erp->UserProjektRecht($projekt)) { - if ($this->app->erp->Firmendaten('iconset_dunkel')) { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); - } - else { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); - } - header('Content-type: image/png'); - echo $str; - exit; - } - } - } - //Rechte prüfen - - $userdata = isset($this->app->Conf->WFuserdata) - ?$this->app->Conf->WFuserdata - :(str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']).'../userdata'); - $path = $userdata.'/dms/'.$this->app->Conf->WFdbname; - $cachefolder = $path.'/cache'; - $_cachefolder = $cachefolder; - $cachefolder = $this->app->erp->GetDMSPath($datei['id'].'_100_100', $cachefolder, true); - if(!file_exists($cachefolder.'/'.$datei['id'].'_100_100')) { - $cachefolder = $this->app->erp->CreateDMSPath($_cachefolder, $datei['id']); - $datei_orig = $this->app->erp->GetDateiPfadVersion($datei['id']); - if(file_exists($datei_orig)) { - $type = mime_content_type($datei_orig); - switch($type) - { - case 'image/jpg': - case 'image/jpeg': - $img = new image($this->app); - $str = $img->scaledPicByFileId($datei['id'], 100, 100); - header('Content-type: image/jpg'); - echo $str; - exit; - break; - case 'image/png': - $img = new image($this->app); - $str = $img->scaledPicByFileId($datei['id'], 100, 100); - header('Content-type: image/png'); - echo $str; - exit; - break; - case 'image/gif': - $img = new image($this->app); - $str = $img->scaledPicByFileId($datei['id'], 100, 100); - header('Content-type: image/gif'); - echo $str; - exit; - break; - case 'application/pdf': - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); - header('Content-type: image/png'); - echo $str; - exit; - break; - default: - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); - if(substr(strtolower($datei['dateiname']),-4) === '.gif'){ - header('Content-type: image/gif'); - echo $str; - exit; - } - if(substr(strtolower($datei['dateiname']),-4) === '.png'){ - header('Content-type: image/png'); - echo $str; - exit; - } - if(substr(strtolower($datei['dateiname']),-4) === '.jpg' - || substr(strtolower($datei['dateiname']),-4) === 'jpeg'){ - header('Content-type: image/jpg'); - echo $str; - exit; - } - break; - } - } - } - - if(file_exists($cachefolder.'/'.$datei['id'].'_100_100')) { - $type = is_file($path.'/'.$datei['id'])? false : mime_content_type($path.'/'.$datei['id']); - if($type === false) { - $type = mime_content_type($cachefolder.'/'.$datei['id'].'_100_100'); - } - if(strpos($type,'image') !== false) { - header('Content-type: '.$type); - $str = file_get_contents($cachefolder.'/'.$datei['id'].'_100_100'); - echo $str; - exit; - } - $str = file_get_contents($cachefolder.'/'.$datei['id'].'_100_100'); - if(substr(strtolower($datei['dateiname']),-4) === '.gif') { - header('Content-type: image/gif'); - echo $str; - exit; - } - if(substr(strtolower($datei['dateiname']),-4) === '.png') { - header('Content-type: image/png'); - echo $str; - exit; - } - if(substr(strtolower($datei['dateiname']),-4) === '.jpg' - || substr(strtolower($datei['dateiname']),-5) === '.jpeg') { - header('Content-type: image/jpg'); - echo $str; - exit; - } - } - else{ - if ($this->app->erp->Firmendaten('iconset_dunkel')) { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); - } else { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); - } - header('Content-type: image/png'); - echo $str; - exit; - } - } - else{ - if ($this->app->erp->Firmendaten('iconset_dunkel')) { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); - } else { - $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); - } - header('Content-type: image/png'); - echo $str; - } - exit; - } - - public function AjaxModuleUnlock() { - if($this->app->erp->RechteVorhanden('welcome','unlock') && - ($salt = $this->app->Secure->GetGET('salt'))) - { - $this->app->DB->Delete("DELETE from module_lock where salt = '".$salt."'"); - } - $this->app->erp->ExitWawi(); - } - - public function AjaxTableFilter() { - - /*header("Content-Type: text/html; charset=utf-8");*/ - - $do = $this->app->Secure->GetGET('do'); - $filter = $this->app->Secure->GetGET('filter'); - - switch ($do) { - case 'getParameters': - $params = $this->app->User->GetParameter('table_filter_' . $filter); - echo base64_decode($params); - break; - case 'setParameters': - $params = base64_encode(json_encode($_GET)); - $this->app->User->SetParameter('table_filter_' . $filter, $params); - break; - case 'clearParameters': - $this->app->User->SetParameter('table_filter_' . $filter,''); - break; - default: - return false; - break; - } - - $this->app->erp->ExitWawi(); - } - - public function AjaxArticleMatrixSelection() - { - $menge = $this->app->Secure->GetPOST('menge'); - $auswahl = $this->app->Secure->GetPOST('auswahl'); - $cmd = $this->app->Secure->GetGET('cmd'); - $vorgangsId = (int)$this->app->Secure->GetGET('id'); - $vorgangsTyp = $this->app->Secure->GetGET('typ'); - if ($vorgangsId === 0) { - $this->app->erp->ExitWawi(); - } - - if ($cmd === 'get') { - $articleMatrixSelection = $this->GetArticleMatrixSelection($vorgangsTyp, $vorgangsId); - header('Content-Type: application/json'); - echo json_encode($articleMatrixSelection); - $this->app->erp->ExitWawi(); - } - - if ($cmd === 'set') { - // Vorhandene Auswahl laden und aktuelle Auswahl hinzufügen - // Notwendig, da sich der Auswahlprozess über mehrere Seiten erstrecken kann. - $articleMatrix = $this->GetArticleMatrixSelection($vorgangsTyp, $vorgangsId); - - foreach ($menge as $artikelId => $artikelAnzahl) { - // Nur Mengen größer Null merken - if (!empty($artikelAnzahl)) { - $articleMatrix['menge'][(int)$artikelId] = (int)$artikelAnzahl; - } - // Auswahl wurde entfernt > Menge ebenfalls leeren - if (isset($menge[$artikelId]) && !isset($auswahl[$artikelId])) { - unset($articleMatrix['auswahl'][(int)$artikelId],$articleMatrix['menge'][(int)$artikelId]); - } - } - // Nur aktive Checkboxen merken - foreach ($auswahl as $artikelId => $artikelAuswahl) { - if ($artikelAuswahl === 'on') { - $articleMatrix['auswahl'][(int)$artikelId] = true; - } - } - - $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, $articleMatrix); - $this->app->erp->ExitWawi(); - } - - // Artikelmatrix-Auswahl zurücksetzen - if ($cmd === "reset") { - $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, []); - $this->app->erp->ExitWawi(); - } - } - - protected function GetArticleMatrixSelection($vorgangsTyp, $vorgangsId) - { - if (empty($vorgangsTyp) || (int)$vorgangsId === 0) { - return [ - 'auswahl' => [], - 'menge' => [], - ]; - } - - $selection = $this->app->User->GetParameter("article_matrix_selection_{$vorgangsTyp}_{$vorgangsId}"); - $matrix = json_decode($selection, true); - if (empty($matrix)) { - $matrix = []; - } - - // Alter des Eintrags kontrollieren; nach 24 Stunden ohne Änderung > Eintrag verwerfen - $yesterday = time() - (60 * 60 * 24); - if (empty($matrix['time']) || (int)$matrix['time'] < $yesterday) { - $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, []); - $matrix = []; - } - - if (empty($matrix['auswahl'])) { - $matrix['auswahl'] = []; - } - if (empty($matrix['menge'])) { - $matrix['menge'] = []; - } - - return $matrix; - } - - protected function SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, $data = []) - { - if ((int)$vorgangsId === 0) { - return; - } - if (empty($vorgangsTyp)) { - return; - } - if (!is_array($data)) { - $data = []; - } - - // Aktuellen Timestamp hinzufügen/überschreiben - $data['time'] = time(); - - // Auswahl pro User und Vorgang merken - $this->app->User->SetParameter("article_matrix_selection_{$vorgangsTyp}_{$vorgangsId}", json_encode($data)); - } - - public function AjaxTooltipSuche() - { - $term = $this->app->Secure->GetGET('term'); - - if(is_numeric($term)) - { - $rechnung = $this->app->DB->SelectArr("SELECT id,belegnr,soll,ist FROM rechnung WHERE belegnr='$term'"); - $gutschrift = $this->app->DB->SelectArr("SELECT id,belegnr,soll,ist FROM gutschrift WHERE belegnr='$term'"); - $auftrag = $this->app->DB->SelectArr("SELECT id,belegnr FROM auftrag WHERE belegnr='$term'"); - $internet = $this->app->DB->SelectArr("SELECT id,belegnr FROM auftrag WHERE internet='$term'"); - $kunde = $this->app->DB->SelectArr("SELECT id,name FROM adresse WHERE kundennummer='$term'"); - } - if(!empty($rechnung) && is_array($rechnung)) - { - foreach($rechnung as $value){ - echo '
Rechnung '.$value['belegnr'].' SOLL:'.$value['soll'].' IST:'.$value['ist'].'
'; - } - } - - if(!empty($auftrag) && is_array($auftrag)) - { - foreach($auftrag as $value){ - echo 'Auftrag '.$value['belegnr']; - } - } - - - - if(!empty($internet) && is_array($internet)) - { - foreach($internet as $value){ - echo 'Internet Auftrag '.$value['belegnr']; - } - } - - - /*if($internetnummer) - echo "Internetnummer";*/ - - - if(!empty($kunde) && is_array($kunde)) - { - foreach($kunde as $value){ - echo 'Kunde '.$value['name']; - } - } - - - echo 'ENDE '; - - $this->app->erp->ExitWawi(); - - } - - public function AjaxAdresseStammdaten() - { - $id = $this->app->Secure->GetGET('id'); - if($id <= 0) - { - $this->app->erp->ExitWawi(); - } - - //name abteilung unterabteilung land strasse ort plz - - $values = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$id' LIMIT 1"); - if(!empty($values)){ - foreach ($values[0] as $key => $value) { - $values[0][$key] = $this->app->erp->ReadyForPDF($value); - } - - echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['titel'] . '#*#' . $values[0]['id'] . - '#*#' . $values[0]['email'] . - '#*#' . $values[0]['telefon'] . - '#*#' . $values[0]['telfax'] . - '#*#' . $values[0]['anschreiben'] . - '#*#' . $values[0]['gln'] - ); - } - $this->app->erp->ExitWawi(); - - } - - public function AjaxVerzolladresse() - { - $id = $this->app->Secure->GetGET('id'); - if($id <= 0) - { - $this->app->erp->ExitWawi(); - } - - //name abteilung unterabteilung land strasse ort plz - - $values = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$id' LIMIT 1"); - if(!empty($values)){ - foreach ($values[0] as $key => $value) { - if($key !== 'zollinformationen') { - $values[0][$key] = $this->app->erp->ReadyForPDF($value); - } - } - echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['titel'] . '#*#' . base64_encode($values[0]['zollinformationen']) . '#*#'); - } - $this->app->erp->ExitWawi(); - } - - public function AjaxLieferadresse() - { - $id = $this->app->Secure->GetGET('id'); - if($id <= 0) - { - $this->app->erp->ExitWawi(); - } - - //name abteilung unterabteilung land strasse ort plz - - $values = $this->app->DB->SelectArr("SELECT * FROM lieferadressen WHERE id='$id' LIMIT 1"); - if(!empty($values)){ - foreach ($values[0] as $key => $value) { - $values[0][$key] = $this->app->erp->ReadyForPDF($value); - } - echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['id'] . '#*#' . $values[0]['gln'] . '#*#' . $values[0]['ustid'] . '#*#' . $values[0]['ust_befreit'] . '#*#' . $values[0]['lieferbedingung']. '#*#' . $values[0]['email']); - } - $this->app->erp->ExitWawi(); - - } - - - - public function AjaxAnsprechpartner() - { - $id = $this->app->Secure->GetGET('id'); - if($id <= 0) - { - $this->app->erp->ExitWawi(); - } - $values = $this->app->DB->SelectArr("SELECT * FROM ansprechpartner WHERE id='$id' LIMIT 1"); - if(!empty($values[0])){ - foreach ($values[0] as $key => $value) { - $values[0][$key] = $this->app->erp->ReadyForPDF($value); - } - echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['email'] . '#*#' . $values[0]['telefon'] . '#*#' . $values[0]['telefax'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . - '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['typ'] . '#*#' . $values[0]['anschreiben'] . '#*#' . $values[0]['titel'] . '#*#' . $values[0]['id']); - } - $this->app->erp->ExitWawi(); - } - - public function AjaxAutoSaveKonfiguration() - { - $name = $this->app->Secure->GetPOST('name'); - $value = $this->app->Secure->GetPOST('value'); - $this->app->erp->SetKonfigurationValue($name,base64_decode($value)); - $this->app->erp->ExitWawi(); - } - - public function AjaxAutoSaveUserParameter() - { - $name = $this->app->Secure->GetPOST('name'); - $value = $this->app->Secure->GetPOST('value'); - $this->app->User->SetParameter($name,base64_decode($value)); - $this->app->erp->ExitWawi(); - } - - - public function AjaxGetUserParameter() - { - $name = $this->app->Secure->GetPOST('name'); - $names = $this->app->Secure->GetPOST('names'); - if(!empty($names)) - { - $names = explode(',', $names); - $elems = explode(',',$this->app->Secure->GetPOST('elems')); - - $values = $this->app->User->GetParameter($names); - if(!empty($values)) - { - foreach($values as $k => $v) - { - $values[$k]['elem'] = $elems[$k]; - } - } - echo json_encode($values); - }else{ - echo json_encode(array('name'=>$name,'elem'=>$this->app->Secure->GetPOST('elem'),'value'=>$this->app->User->GetParameter($name))); - } - $this->app->erp->ExitWawi(); - } - - public function AjaxFilterWhere($term, $fields) - { - if(empty($fields)) - { - return '1'; - } - while(strpos($term,' ') !== false) - { - $term = str_replace(' ',' ', $term); - } - $term = trim($term); - $term2 = $term; - $term3 = $term; - $term2 = $this->app->erp->ConvertForDBUTF8($term); - $term3 = $this->app->erp->ConvertForDB($term); - $terma = explode( ' ', $term); - $term2a = explode( ' ', $term2); - $term3a = explode( ' ', $term3); - if(count($terma) === 1) - { - $wherea = []; - foreach($fields as $v) { - $wherea[] = $v . " LIKE '%" . $term . "%'"; - if($term2 !== $term && $term2 !== ''){ - $wherea[] = $v . " LIKE '%" . $term2 . "%'"; - } - if($term3 !== $term && $term3 !== $term2 && $term3!==''){ - $wherea[] = $v . " LIKE '%" . $term3 . "%'"; - } - } - return ' ('.implode(' OR ', $wherea).') '; - } - $wherea = []; - foreach($fields as $v) { - if(!empty($term2) && $term2 !== $term){ - $tmp = []; - //foreach ($terma as $v2) { - $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma, $term2a); - //} - $wherea[] = implode(' AND ', $tmp); - } - elseif(!empty($term3) && $term3 !== $term){ - $tmp = []; - //foreach ($terma as $v2) { - $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma, $term3a); - //} - $wherea[] = implode(' AND ', $tmp); - } - else{ - $tmp = []; - //foreach ($terma as $v2) { - $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma); - //} - $wherea[] = implode(' AND ', $tmp); - } - } - - return ' ('.implode(' OR ', $wherea).') '; - } - - public function AjaxFilter() - { - //$term = $this->app->Secure->GetGET("term"); - $term = $this->app->Secure->GetGET('term'); - $termorig = $term; - $rmodule = $this->app->Secure->GetGET('rmodule'); - $raction = $this->app->Secure->GetGET('raction'); - $rid = (int)$this->app->Secure->GetGET('rid'); - $pruefemodule = array('artikel','auftrag','angebot','rechnung','lieferschein','gutschrift','bestellung','produktion'); - $filter_projekt = 0; - if($raction === 'edit' && $rid && in_array($rmodule, $pruefemodule)) - { - $projekt = $this->app->DB->Select("SELECT projekt FROM $rmodule WHERE id = '$rid' LIMIT 1"); - if($projekt) - { - $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id = '$projekt' LIMIT 1"); - //if($eigenernummernkreis) - $filter_projekt = $projekt; - } - } - $term2 = $term; - $term3 = $term; - $term = $this->app->erp->ConvertForDBUTF8($term); - $term2 = $this->app->erp->ConvertForDB($term2); - if($term2=='') { - $term2 = $term; - } - $term = str_replace(' ','%',$term); - $term2 = str_replace(' ','%',$term2); - $term3 = str_replace(' ','%',$term3); - //$term = $this->app->erp->ConvertForDBUTF8($term); - //$term = str_replace(' ','%',$term); - $filtername = $this->app->Secure->GetGET('filtername'); - - $term = trim($term); - $term2 = trim($term2); - - switch($filtername) - { - case "adressenamegruppe": - $gruppe = $this->app->Secure->GetGET('gruppe'); - $gruppea = explode(',',$gruppe); - $gruppenwhere = ' 0 '; - foreach($gruppea as $v) - { - if($v){ - $gruppenw[] = " ar.parameter = '$v' "; - } - } - if(!empty($gruppenw)) - { - $gruppenwhere = ' ('.implode(' OR ', $gruppenw).') '; - } - - $felder = array('a.email','a.name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT concat(a.id, ' ',a.name) as name2 FROM adresse a - INNER JOIN adresse_rolle ar ON a.id = ar.adresse AND $gruppenwhere AND ar.objekt LIKE 'Gruppe' AND (bis = '0000-00-00' OR bis >= curdate()) - WHERE ($subwhere) AND a.geloescht <> 1 ".$this->app->erp->ProjektRechte('a.projekt')." - ORDER BY a.name LIMIT 20 - "); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name2']}"; - } - break; - - case "adressename": - $arr = $this->app->DB->SelectArr("SELECT a.email, (SELECT name FROM adresse a2 WHERE a2.kundennummer = a.kundennummer ".$this->app->erp->ProjektRechte('a2.projekt')." order by ".($filter_projekt?" a2.projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1) as name2 FROM adresse a WHERE (a.email LIKE '%$term%' OR a.name LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte('a.projekt')." GROUP by email ORDER BY a.email, name2 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name2']}"; - } - break; -/* - -select a.kundennummer, (SELECT name FROM adresse a2 WHERE a2.kundennummer = a.kundennummer order by a2.projekt = 13 DESC, a2.projekt = 0 DESC, projekt LIMIT 1) as name FROM adresse a WHERE a.kundennummer like '10500' group by a.kundennummer -*/ - case "arbeitspaket": - if(trim($this->app->Secure->GetGET('projekt')) != ''){ - $checkprojekt = trim($this->app->Secure->GetGET('projekt')); - }else{ - $checkprojekt = $this->app->User->GetParameter("teilprojekt_filter"); - } - - if(is_numeric($checkprojekt) && $checkprojekt > 0){ - $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE id='" . $checkprojekt . "' LIMIT 1"); - } - - $limit = ''; - if($projektid <=0) - { - $checkprojekt = explode(' ',$checkprojekt); - $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung='".$checkprojekt[0]."' AND abkuerzung!='' LIMIT 1"); - if($projektid <=0){ - $limit = ' LIMIT 20 '; - } - } - - if($projektid > 0){ - $subwhere = " AND p.id='".$projektid."'"; - } else { - $subwhere=''; - } - - $felder = array('p.abkuerzung', 'ap.aufgabe'); - $subwhere2 = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(ap.id,' ',p.abkuerzung,' ',ap.aufgabe) as name2 FROM arbeitspaket ap LEFT JOIN projekt p ON p.id=ap.projekt WHERE ($subwhere2) AND ap.status!='abgeschlossen' AND ap.aufgabe!='' AND p.id > 0 $subwhere ".$limit); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name2']}"; - } - break; - case "artikeleigenschaften": - $subwhere = $this->app->erp->ProjektRechte('e.projekt'); - $felder = array('name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT name FROM artikeleigenschaften e WHERE ($subwhere) AND geloescht <> 1 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name']}"; - } - break; - case "artikeleigenschaftenwerte": - //$arr = $this->app->DB->SelectArr("SELECT DISTINCT wert FROM artikeleigenschaftenwerte WHERE wert LIKE '%$term%' OR wert LIKE '%$term2%' OR wert LIKE '%$term3%' LIMIT 20"); - //$arr2 = $this->app->DB->SelectArr("SELECT DISTINCT property_value_from FROM article_property_translation WHERE (property_value_from LIKE '%$term%' OR property_value_from LIKE '%$term2%' OR property_value_from LIKE '%$term3') AND language_from = 'DE' LIMIT 20"); - - - $arr = $this->app->DB->SelectArr("(SELECT DISTINCT wert FROM artikeleigenschaftenwerte WHERE wert LIKE '%$term%' OR wert LIKE '%$term2%' OR wert LIKE '%$term3%' LIMIT 20) UNION - (SELECT DISTINCT property_value_from as wert FROM article_property_translation WHERE (property_value_from LIKE '%$term%' OR property_value_from LIKE '%$term2%' OR property_value_from LIKE '%$term3') AND language_from = 'DE' LIMIT 20) ORDER BY wert"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = "{$arr[$i]['wert']}"; - } - break; - case "matrixprodukt_uebersetzungen": - $arr = $this->app->DB->SelectArr("(SELECT DISTINCT name_from AS name FROM matrix_article_translation WHERE name_from LIKE '%$term%' OR name_from LIKE '%$term2%' OR name_from LIKE '%$term3%' LIMIT 20) - UNION (SELECT DISTINCT name_to AS name FROM matrix_article_translation WHERE name_to LIKE '%$term%' OR name_to LIKE '%$term2%' OR name_to LIKE '%$term3%' LIMIT 20) - UNION (SELECT DISTINCT name FROM matrixprodukt_eigenschaftengruppen WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20)"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = "{$arr[$i]['name']}"; - } - break; - case "matrixprodukt_optionen_uebersetzungen": - $arr = $this->app->DB->SelectArr("(SELECT DISTINCT name_from AS name FROM matrix_article_options_translation WHERE name_from LIKE '%$term%' OR name_from LIKE '%$term2%' OR name_from LIKE '%$term3%' LIMIT 10) - UNION (SELECT DISTINCT name_to AS name FROM matrix_article_options_translation WHERE name_to LIKE '%$term%' OR name_to LIKE '%$term2%' OR name_to LIKE '%$term3%' LIMIT 20) - UNION (SELECT DISTINCT name FROM matrixprodukt_eigenschaftenoptionen WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20)"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = "{$arr[$i]['name']}"; - } - break; - case "drucker": - $felder = array('name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT name FROM drucker WHERE $subwhere LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name']}"; - } - break; - case "wiedervorlage_stages": - $felder = array('ws.name','ws.kurzbezeichnung'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr( - "SELECT CONCAT(ws.id, ' ', ws.kurzbezeichnung, ' (', IFNULL(wv.shortname, 'Standard'), ' - ', ws.name, ')') AS `name2` - FROM `wiedervorlage_stages` AS `ws` - LEFT JOIN `wiedervorlage_view` AS `wv` ON ws.view = wv.id - WHERE $subwhere - ORDER BY ws.view, ws.kurzbezeichnung LIMIT 20" - ); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name2']}"; - } - break; - case "wiedervorlage_view": - $felder = array('name', 'shortname'); - $subwhere = $this->AjaxFilterWhere($termorig, $felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', shortname, ' (',name,')') AS name2 FROM wiedervorlage_view WHERE $subwhere ORDER BY shortname LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = "{$arr[$i]['name2']}"; - } - break; - case "etiketten": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',name) as name2 FROM etiketten WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = "{$arr[$i]['name2']}"; - break; - - - case "laender": - $laender = $this->app->erp->GetSelectLaenderliste(); - $_term = explode(',',$term); - $_term = $_term[count($_term)-1]; - if($laender){ - foreach($laender as $key => $value) - { - if(stripos($key, $_term) !== false || stripos($value, $_term) !== false) - { - $newarr[] = $key.' '.$value; - } - } - } - break; - case "artikelname": - $felder = array('CONCAT(nummer,\' \',name_de)','nummer','name_de'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT name_de FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND ($artikel_freitext1_suche) AND geloescht=0 ORDER by name_de LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name_de']; - } - break; - - case "artikelgruppe": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['typ']; - } - break; - - case "artikelkategorienfull": - $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); - $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); - if($anz) - { - - $artikelbaum = array(); - $allekategorien = $this->app->DB->SelectArr("SELECT id, bezeichnung, parent FROM artikelkategorien WHERE geloescht = 0"); - foreach($allekategorien as $key=>$value){ - if($value['parent'] == 0){ - $artikelbaum[$value['id']] = $value['bezeichnung']; - foreach($allekategorien as $key2=>$value2){ - if(array_key_exists($value2['parent'], $artikelbaum)){ - $artikelbaum[$value2['id']] = $artikelbaum[$value2['parent']]." / ".$value2['bezeichnung']; - } - } - } - } - - $arr = array(); - $i = 0; - - if($term == "" || $term == "%"){ - foreach($artikelbaum as $key=>$value){ - $arr[$i] = $key." ".$value; - $i++; - } - }else{ - foreach($artikelbaum as $key=>$value){ - if(strpos(strtolower($value), strtolower($term)) !== false){ - $arr[$i] = $key.' '.$value; - $i++; - } - } - } - - } - - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - if($i<20){ - $newarr[] = $arr[$i]; - }else{ - break; - } - } - - - break; - - case "artikelkategorien": - - $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); - $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); - if($anz) - { - $arr = $this->app->DB->SelectArr("SELECT a.typ,ar.bezeichnung FROM artikel a LEFT JOIN artikelkategorien ar ON a.typ = concat(ar.id,'_kat') WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ar.bezeichnung LIKE '%$term%' ".$subwhere." GROUP BY a.typ ORDER by ar.bezeichnung "); - if($arr) - { - $typen = false; - foreach($arr as $k => $a) - { - if($a['bezeichnung'])$arr[$k]['typ'] = $a['bezeichnung']; - $typen = $arr[$k]['typ']; - } - array_multisort($typen, $arr); - $last = false; - foreach($arr as $k => $a) - { - if($last == $a['typ']) - { - unset($arr[$k]); - } else { - $last = $a['typ']; - } - } - } - - - } else { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = $arr[$i]['typ']; - } - break; - - case 'alleartikelkategorien': - $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); - $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); - if($anz) - { - $arr = $this->app->DB->SelectArr("SELECT ar.bezeichnung as typ FROM artikelkategorien ar WHERE ar.bezeichnung LIKE '%$term%' ".$subwhere." AND ar.geloescht <> 1 ORDER by ar.bezeichnung "); - } else { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); - } - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['typ']; - } - break; - case 'xcs_tables': - $felder = array('name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT name FROM xcs_table ORDER BY name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - case "artikeleanbeleg": - $doctype = $this->app->Secure->GetGET('doctype'); - $doctypeid = (int)$this->app->Secure->GetGET('doctypeid'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(if(art.ean <> '', art.ean, art.nummer),' ',art.name_de) as name FROM artikel art - INNER JOIN $doctype"."_position ap ON ap.artikel = art.id AND $doctype = '$doctypeid' - WHERE art.geloescht=0 AND ($subwhere) AND art.geloescht=0 AND art.intern_gesperrt!=1 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "artikelnummerbeleg": - $doctype = $this->app->Secure->GetGET('doctype'); - $doctypeid = (int)$this->app->Secure->GetGET('doctypeid'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(art.nummer,' ',art.name_de) as name FROM artikel art - INNER JOIN $doctype"."_position ap ON ap.artikel = art.id AND $doctype = '$doctypeid' - WHERE art.geloescht=0 AND ($artikel_freitext1_suche) AND art.geloescht=0 AND art.intern_gesperrt!=1 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "spracheniso": - $arr = $this->app->DB->SelectArr('SELECT iso FROM sprachen'); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = $arr[$i]['iso']; - } - break; - case "geschaeftsbrief_vorlagen": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',subjekt,' (',sprache,')') as name FROM geschaeftsbrief_vorlagen"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = $arr[$i]['name']; - } - break; - - case "artikeleinheit": - //$arr = $this->app->DB->SelectArr("SELECT DISTINCT einheit_de FROM artikeleinheit WHERE firma='".$this->app->User->GetFirma()."' AND einheit_de LIKE '%$term%' ORDER by einheit_de"); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT einheit_de FROM artikeleinheit WHERE einheit_de LIKE '%$term%' ORDER by einheit_de"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['einheit_de']; - break; - - - - case "ihrebestellnummer": - $adresse = $this->app->Secure->GetGET('adresse'); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT ihrebestellnummer FROM auftrag WHERE ihrebestellnummer LIKE '%$term%' AND adresse='$adresse' ORDER by ihrebestellnummer "); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['ihrebestellnummer']; - } - break; - - - case "accountart": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT art FROM adresse_accounts WHERE art LIKE '%$term%' ORDER by art"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['art']; - } - break; - - - case "ansprechpartneradresse": - $adressId = $this->app->Secure->GetGET('adresse'); - - if(is_numeric($adressId) && $adressId > 0){ - $adressId = $this->app->DB->Select("SELECT id FROM adresse WHERE id = '$adressId' LIMIT 1"); - } - - $limit = ''; - if($adressId <= 0){ - $adresse = explode(' ', $adressId); - $adressId = $this->app->DB->Select("SELECT id FROM adresse WHERE name = '".$adresse[0]."' AND name != '' LIMIT 1"); - if($adressId <= 0){ - $limit = ' LIMIT 20 '; - } - } - - if($adressId > 0){ - $subwhere = " AND a.id = '$adressId'"; - }else{ - $subwhere = ''; - } - - $felder = array('an.name'); - $subwhere2 = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(an.id, ' ', an.name, ' ', IF(a.lieferantennummer,CONCAT('(', a.name, ', Kdr: ', a.kundennummer, ' Liefr: ', a.lieferantennummer, ')'), CONCAT('(', a.name, ', Kdr: ', a.kundennummer, ')'))) AS name - FROM ansprechpartner an - LEFT JOIN adresse a ON an.adresse = a.id - WHERE ($subwhere2) AND a.id > 0 AND a.geloescht = 0 $subwhere ".$this->app->erp->ProjektRechte('a.projekt').$limit); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = "{$arr[$i]['name']}"; - } - break; - - case "ansprechpartner": - $adresse = $this->app->Secure->GetGET('adresse'); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT name FROM ansprechpartner WHERE adresse='$adresse' AND name LIKE '%$term%' AND geloescht <> 1 ORDER by name"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "hersteller": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT hersteller FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND hersteller LIKE '%$term%' ORDER by hersteller"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['hersteller']; - break; - case "rmakategorien": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM rma_vorlagen_kategorien WHERE bezeichnung LIKE '%$term%' ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "spedition_einstellungen_feld": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT feld FROM spedition_einstellungen WHERE aktiv=1 AND feld LIKE '%$term%' ORDER by feld"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['feld']; - } - break; - - case "zeiterfassung_beschreibung": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT beschreibung FROM zeiterfassung_kosten WHERE beschreibung LIKE '%$term%' ORDER by beschreibung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['beschreibung']; - } - break; - - case "eigenschaften_vorlagen": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM eigenschaften_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "ticketnummer": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(t.schluessel, ' Name: ', t.kunde, ' Betr: ', t.betreff) as schluessel FROM ticket t WHERE t.schluessel LIKE '%$term%' OR t.kunde LIKE '%$term%' OR t.betreff LIKE '%$term%' ORDER BY t.schluessel"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['schluessel']; - } - break; - - case "abosammelrechnungen": - $id = $this->app->Secure->GetGET('adresse'); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', bezeichnung) as bezeichnung FROM adresse_abosammelrechnungen WHERE bezeichnung LIKE '%$term%' AND adresse = '$id' ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - - case "arbeitsplatzgruppe": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ',bezeichnung) as bezeichnung FROM arbeitsplatzgruppen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - case "artikelarbeitsanweisung_vorlagen": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM artikelarbeitsanweisung_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - case "artikelfunktionsprotokoll_vorlagen": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM artikelfunktionsprotokoll_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - case "fahrtenbuch_kennzeichen": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT kennzeichen FROM fahrtenbuch_fahrzeuge WHERE kennzeichen LIKE '%$term%' AND aktiv = 1 ORDER BY kennzeichen"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['kennzeichen']; - break; - - case "fahrtenbuch_strecke": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT strecke FROM fahrtenbuch_vorlagen WHERE (strecke LIKE '%$term%' OR strecke LIKE '%$term2%' OR strecke LIKE '%$term3%') AND aktiv = 1 ORDER BY strecke"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['strecke']; - break; - - case "verpackungsgruppe": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT verpackungsgruppe FROM verpackungen_details WHERE verpackungsgruppe LIKE '%$term%' ORDER by verpackungsgruppe"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['verpackungsgruppe']; - break; - - case "dropshipping_gruppe": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM dropshipping_gruppe WHERE bezeichnung LIKE '%$term%' ORDER BY bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - - - case "layoutvorlage": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', name) AS name FROM layoutvorlagen WHERE name LIKE '%$term%' ORDER BY name"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "uservorlage": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM uservorlage WHERE bezeichnung LIKE '%$term%' ORDER by bezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - - case "lagergrund": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT TRIM(REPLACE(REPLACE(referenz,'Umlagern fü :',''),'Differenz:','')) as ergebnis FROM lager_bewegung WHERE REPLACE(referenz,'Differenz:','') LIKE '%$term%' AND referenz NOT LIKE '%Inventur%' AND referenz NOT LIKE '%Charge%' AND referenz NOT LIKE '%Lieferschein%' - AND referenz NOT LIKE '%Manuell%' AND referenz NOT LIKE '%Wareneingang%' AND referenz NOT LIKE '%Lieferungen%' LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['ergebnis']; - break; - - - - case "auftrag_zahlungseingang": - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' ',REPLACE(a.name,',',''),' ',r.internet,' GESAMT: ',r.gesamtsumme,' (Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status) as name - FROM auftrag r LEFT JOIN adresse a ON a.id=r.adresse WHERE r.belegnr!='' - AND (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%' OR IFNULL(r.internet,'') LIKE '%$term%' ) ORDER by r.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "rechnung_zahlungseingang": - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' Soll:',r.soll,' Ist:',r.ist,' ',' Diff:',(r.soll-r.ist)*-1,' ', - if(r.zahlungszielskonto > 0,if(isnull(r.skontobetrag),CONCAT('SK:',r.zahlungszielskonto,'%(',FORMAT((r.soll/100)*r.zahlungszielskonto,2),') '),concat('SK:',FORMAT(100*r.skontobetrag / r.soll,2),'%(',FORMAT(r.skontobetrag,2),')')),''),REPLACE(a.name,',',''),'(Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status - ,IF(IFNULL(ab.internet,'')!='',CONCAT(' Intenet: ',ab.internet),'') - ) as name - FROM rechnung r - LEFT JOIN auftrag ab ON r.auftragid = ab.id - LEFT JOIN adresse a ON a.id=r.adresse - WHERE r.belegnr!='' AND - (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' - OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%' - OR IFNULL(ab.internet,'') LIKE '%$term%' - ) - AND r.zahlungsstatus!='bezahlt' - ORDER by r.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "gutschrift_zahlungseingang": - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' SOLL: ',r.soll,' IST:',r.ist,' ',REPLACE(a.name,',',''),' (Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status) as name - FROM gutschrift r LEFT JOIN adresse a ON a.id=r.adresse WHERE r.belegnr!='' AND (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') AND (r.manuell_vorabbezahlt IS NULL OR r.manuell_vorabbezahlt='0000-00-00') ORDER by r.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - - case "gutschrift": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) AS name - FROM gutschrift WHERE belegnr != '' AND belegnr != '0' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." ORDER BY belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "angebot": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM angebot WHERE belegnr!='' AND belegnr!='0' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "bestellung": - $status = $this->app->Secure->GetGET('status'); - switch($status) { - case 'freigegeben': - case 'abgeschlossen': - case 'versendet': - case 'strorniert': - break; - default: - $status = ''; - break; - } - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM bestellung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".($status != ''?" AND status = '".$status."' ":'').$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "preisanfrage": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM preisanfrage WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "bestellunggesamtsumme": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',".$this->app->erp->FormatPreis("gesamtsumme",2).",' ',waehrung,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM bestellung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - - case "auftrag_position_dienstleistung": - $arr = $this->app->DB->SelectArr("SELECT ap.menge, ap.id as auftragspositionid,CONCAT(a.belegnr,'-',ap.sort,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y'),' ',ap.bezeichnung) as name - FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag LEFT JOIN artikel art ON art.id=ap.artikel WHERE art.dienstleistung=1 AND a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR ap.bezeichnung LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ORDER by a.belegnr DESC LIMIT 20"); - foreach($arr as $value){ - $sollzeit = number_format($value['menge'],2); - $istzeit = $this->app->DB->Select("SELECT SUM(Time_to_sec(Timediff(z.von,z.bis))/3600) FROM zeiterfassung z WHERE z.auftragpositionid = '{$value['auftragspositionid']}'"); - $newarr[] = $value['name'] . " ( " . number_format(($istzeit*-1),2) . " von " . $sollzeit . ")"; - } - break; - - case "alle_auftrag_positionen": - $arr = $this->app->DB->SelectArr("SELECT ap.menge, ap.id as auftragspositionid,CONCAT(a.belegnr,'-',ap.sort,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y'),' ',ap.bezeichnung) as name - FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR ap.bezeichnung LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ORDER by a.belegnr DESC LIMIT 20"); - foreach($arr as $value){ - $sollzeit = number_format($value['menge'],2); - $istzeit = $this->app->DB->Select("SELECT SUM(Time_to_sec(Timediff(z.von,z.bis))/3600) FROM zeiterfassung z WHERE z.auftragpositionid = '{$value['auftragspositionid']}'"); - $newarr[] = $value['name'] . " ( " . number_format(($istzeit*-1),2) . " von " . $sollzeit . ")"; - } - break; - - case "auftragihrebestellnummer": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y'), - if(ihrebestellnummer!='',CONCAT(' ',ihrebestellnummer),''),if(internebezeichnung!='',CONCAT(' ',internebezeichnung),'')) as name - FROM auftrag WHERE belegnr!='0' AND belegnr!='' AND status!='angelegt' AND - (name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' OR ihrebestellnummer LIKE '%$term%' OR internebezeichnung LIKE '%$term%' - OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "auftrag": - $status = $this->app->Secure->GetGET('status'); - switch($status) { - case 'freigegeben': - case 'abgeschlossen': - case 'strorniert': - break; - default: - $status = ''; - break; - } - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.belegnr,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y')) as name - FROM auftrag a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." ".($status != ''?" AND a.status = '".$status."' ":'')." ORDER by a.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "auftragmitrechnung": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.belegnr,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y')) as name - FROM auftrag a - INNER JOIN rechnung r ON a.id = r.auftragid AND r.belegnr <> '' - WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') GROUP BY a.id ORDER by a.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "auftrag_freigegeben": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM auftrag WHERE belegnr!='0' AND belegnr!='' AND status='freigegeben' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "rechnung_freigegeben": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM rechnung WHERE belegnr!='0' AND belegnr!='' AND status='freigegeben' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "produktion": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM produktion WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - - case "arbeitsnachweis": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM arbeitsnachweis WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "lieferschein": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM lieferschein WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case 'rechnung': - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM rechnung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - case 'retoure': - $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name - FROM retoure WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "rechnungmitauftrag": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' ',r.name,' ',DATE_FORMAT(r.datum,'%d.%m.%Y')) as name - FROM rechnung r - INNER JOIN auftrag a ON r.auftragid = a.id - LEFT JOIN projekt p ON p.id=r.projekt - WHERE r.belegnr!='0' AND r.belegnr!='' AND (r.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR DATE_FORMAT(r.datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." GROUP BY r.id ORDER by r.belegnr DESC LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "vpeartikel": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT vpe FROM verkaufspreise WHERE geloescht=0 AND vpe LIKE '%$term%' ORDER by vpe"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['vpe']; - break; - - case "herstellerlink": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT herstellerlink FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND herstellerlink LIKE '%$term%' ORDER by herstellerlink"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['herstellerlink']; - break; - - - case 'lagerplatz': - case 'lagerplatzstandardlager': - $onlyStdLager = $filtername === 'lagerplatzstandardlager'; - $stdLager = 0; - if($rmodule === 'produktionszentrum' || $rmodule==='produktion') { - if($onlyStdLager > 0 && $rid > 0) { - $stdLager = (int)$this->app->DB->Select( - sprintf( - 'SELECT standardlager FROM produktion WHERE id = %d', - $rid - ) - ); - } - } - $withzwischenlager = $this->app->Secure->GetGET('zwischenlager'); - $withstadardlager = $this->app->Secure->GetGET('withstandardlager'); - $sql = "SELECT lp.kurzbezeichnung - FROM lager_platz AS lp - LEFT JOIN lager AS l ON l.id=lp.lager - WHERE lp.geloescht=0 AND ('$stdLager' = '0' OR l.id = '$stdLager') - AND lp.kurzbezeichnung LIKE '%$term%' ". - $this->app->erp->ProjektRechte('l.projekt').' - ORDER BY lp.kurzbezeichnung'; - $arr = $this->app->DB->SelectArr($sql); - if(empty($arr)) { - $arr = []; - } - if($withzwischenlager) { - $arr2 = $this->app->DB->SelectArr( - "SELECT 'Zwischenlager' AS kurzbezeichnung FROM (SELECT 1) a WHERE 'Zwischenlager' LIKE '%$term%' " - ); - if(!empty($arr2)) { - $arr = array_merge($arr, $arr2); - } - } - if($withstadardlager) { - $arr2 = $this->app->DB->SelectArr( - "SELECT 'Standardlager' AS kurzbezeichnung FROM (SELECT 1) a WHERE 'Standardlager' LIKE '%$term%'" - ); - if(!empty($arr2)) { - $arr = array_merge($arr, $arr2); - } - } - if(!empty($arr)) { - sort($arr); - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['kurzbezeichnung']; - } - break; - case 'artikelfremdnummern': - $article = explode(' ', $this->app->Secure->GetGET('artikel')); - $article = reset($article); - $articleId = (int)$this->app->Secure->GetGET('artikelid'); - $bezeichnung = $this->app->Secure->GetGET('bezeichnung'); - $shopid = (int)$this->app->Secure->GetGET('shopid'); - if(empty($articleId) && !empty($article)) { - $articleId = $this->app->DB->Select( - sprintf( - "SELECT id - FROM artikel - WHERE nummer = '%s' AND nummer <> '' AND geloescht <> 1 - ORDER BY intern_gesperrt - LIMIT 1", - $article - ) - ); - } - if(!empty($articleId)) { - $newarr = $this->app->DB->SelectFirstCols( - sprintf( - "SELECT DISTINCT af.nummer - FROM artikelnummer_fremdnummern AS af - WHERE af.artikel = %d AND af.aktiv = 1 AND (af.bezeichnung = '%s' OR '%s' = '') - AND af.nummer LIKE '%%%s%%' AND af.shopid = %d", - $articleId, $bezeichnung, $bezeichnung, $term, $shopid - ) - ); - } - - break; - case "bezeichnungfremdnr": - $arr = $this->app->DB->SelectArr('SELECT DISTINCT af.bezeichnung FROM artikelnummer_fremdnummern af'); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - if(!in_array('ID', $newarr)){ - $newarr[] = 'ID'; - } - if(!in_array('SKU', $newarr)){ - $newarr[] = 'SKU'; - } - - break; - case "lagerplatzprojekt": - $arr = $this->app->DB->SelectArr('SELECT lp.kurzbezeichnung - FROM lager_platz AS lp - INNER JOIN lager l ON lp.lager = l.id AND (l.projekt = 0 OR (1 '.$this->app->erp->ProjektRechte('l.projekt').")) - WHERE lp.geloescht=0 AND lp.kurzbezeichnung LIKE '%$term%' - ORDER BY lp.kurzbezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['kurzbezeichnung']; - } - break; - case "sperrlagerplatz": - $arr = $this->app->DB->SelectArr("SELECT kurzbezeichnung FROM lager_platz WHERE geloescht=0 AND sperrlager = 1 AND kurzbezeichnung LIKE '%$term%' ORDER by kurzbezeichnung"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['kurzbezeichnung']; - break; - case 'lagerplatzartikel': - $artikel = (int)$this->app->Secure->GetGET('artikel'); - $pos = (int)$this->app->Secure->GetGET('pos'); - $doctype = strtolower($this->app->Secure->GetGET('doctype')); - $join = ''; - if($pos > 0 && $doctype === 'lieferschein' && $artikel > 0) { - $seriennummern = $this->app->DB->Select( - sprintf( - 'SELECT `seriennummern` FROM artikel WHERE id = %d LIMIT 1', - $artikel - ) - ); - if($seriennummern !== 'keine' && !empty($seriennummern)) { - $cSn = $this->app->DB->SelectArr( - sprintf( - 'SELECT IFNULL(COUNT(id), 0) - FROM `beleg_chargesnmhd` - WHERE doctype = \'%s\' AND pos = %d AND type = \'sn\' AND wert <> \'\' - ', - $doctype, $pos - ) - ); - $position = $this->app->DB->SelectRow( - sprintf('SELECT menge, geliefert FROM lieferschein_position WHERE id = %d', - $pos - ) - ); - if($cSn == $position['menge']) { - $join = sprintf(' INNER JOIN - ( - SELECT lagerplatz - FROM `beleg_chargesnmhd` - WHERE doctype = \'%s\' AND parameter = %d - GROUP BY lagerplatz - ) AS bc ON lp.id = bc.lagerplatz ', - $doctype, $pos - ); - } - } - } - $arr = $this->app->DB->SelectArr( - sprintf('SELECT lp.kurzbezeichnung - FROM lager_platz AS lp - INNER JOIN lager_platz_inhalt AS lpi on lp.id = lpi.lager_platz - %s - WHERE lpi.artikel=%d AND lp.geloescht=0 AND lp.kurzbezeichnung LIKE \'%%%s%%\' - GROUP BY lp.kurzbezeichnung - ORDER by lp.kurzbezeichnung', - $join, $artikel, $term - ) - ); - if(empty($arr)) { - break; - } - foreach($arr as $row) { - $newarr[] = $row['kurzbezeichnung']; - } - break; - - case "lager": - $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." ORDER by 1"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - case 'lager_produktion': - $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l JOIN lager_platz lp ON l.id = lp.lager WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." AND lp.allowproduction = 1 ORDER BY 1"); - - if(empty($arr)){ - $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." ORDER by 1"); - } - - $carr = !empty($arr)?count($arr):0; - for($i=0; $i < $carr; $i++) - $newarr[] = $arr[$i]['bezeichnung']; - break; - - case "aktionscode": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(code,' ',beschriftung) as name FROM aktionscode_liste - WHERE (beschriftung LIKE '%$term%' OR code LIKE '%$term%' OR code LIKE '%$term2%' OR code LIKE '%$term3%') AND ausblenden!=1 ORDER by code"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "waehrung": - if($this->app->DB->Select("SELECT id FROM waehrung_umrechnung LIMIT 1")) { - - - $arr = $this->app->DB->SelectArr(" - ( - SELECT DISTINCT waehrung_nach as name FROM waehrung_umrechnung - WHERE (waehrung_nach LIKE '%$term%') ORDER by waehrung_nach - ) - UNION - ( - SELECT DISTINCT waehrung_von as name FROM waehrung_umrechnung - WHERE (waehrung_von LIKE '%$term%') - - ORDER by waehrung_von - ) - ORDER by name"); - }else{ - - $waehrungen = $this->app->erp->GetWaehrung(); - if($waehrungen) - { - foreach($waehrungen as $v) - { - if($v) { - $sqla[] = " (SELECT '$v' as name FROM (SELECT 1) AS X WHERE - '$v' LIKE '%$term%' - ) "; - } - } - $arr = $this->app->DB->SelectArr("SELECT t.name FROM ( ".implode(' UNION ', $sqla)." ) t ORDER BY name "); - } - } - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - - - break; - - case "sachkonto": - $cmd = $this->app->Secure->GetGET("cmd"); - - if($cmd!="") $projekt = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung='".$this->app->DB->real_escape_string($cmd)."' LIMIT 1"); - - $checkprojekt = ($projekt > 0?$this->app->DB->Select("SELECT COUNT(id) FROM kontorahmen WHERE projekt='$projekt'"):0); - $checkprojektnull = $this->app->DB->Select("SELECT COUNT(id) FROM kontorahmen WHERE projekt=0 OR projekt IS NULL"); - - if($checkprojekt > 0) - { - $andprojekt = "AND (projekt='$projekt' OR projekt = 0 OR projekt IS NULL)"; - } else { - if($checkprojektnull>0) - { - $andprojekt = " AND (projekt=0 OR projekt IS NULL) "; - } else { - $andprojekt = ""; - } - } - - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(sachkonto,' ',beschriftung) as name FROM kontorahmen - WHERE (beschriftung LIKE '%$term%' OR sachkonto LIKE '%$term%' OR sachkonto LIKE '%$term2%' OR sachkonto LIKE '%$term3%' OR beschriftung LIKE '%$term2%' OR beschriftung LIKE '%$term3%') AND ausblenden!=1 $andprojekt ORDER by sachkonto"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "lieferbedingungen": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(lieferbedingungen) as name FROM lieferbedingungen - WHERE (lieferbedingungen LIKE '%$term%' OR lieferbedingungen LIKE '%$term2%' OR lieferbedingungen LIKE '%$term3%') ORDER by lieferbedingungen"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "zeiterfassungvorlage": - $arr = $this->app->DB->SelectArr("SELECT vorlage as name FROM zeiterfassungvorlage - WHERE (vorlage LIKE '%$term%' OR vorlage LIKE '%$term2%' OR vorlage LIKE '%$term3%') AND ausblenden!=1 ORDER by vorlage"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - case "zeiterfassungvorlagedetail": - $vorlage = $this->app->Secure->GetPOST('vorlage'); - $arr = $this->app->DB->SelectRow("SELECT vorlagedetail as name, art, projekt, teilprojekt, kunde, abrechnen FROM zeiterfassungvorlage WHERE vorlage = '$vorlage' LIMIT 1"); - - if($arr['projekt'] > 0){ - $arr['projekt'] = $this->app->DB->Select("SELECT CONCAT(abkuerzung, ' ', name) FROM projekt WHERE id = '".$arr['projekt']."' LIMIT 1"); - }else{ - $arr['projekt'] = ''; - } - - if($arr['teilprojekt'] > 0){ - $projektid = $this->app->DB->Select("SELECT projekt FROM arbeitspaket WHERE id = '".$arr['teilprojekt']."' LIMIT 1"); - if($projektid > 0){ - $projektabk = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$projektid' LIMIT 1"); - if($projektabk != ""){ - $arr['teilprojekt'] = $this->app->DB->Select("SELECT CONCAT('".$arr['teilprojekt']."', ' ', '$projektabk', ' ', aufgabe) FROM arbeitspaket WHERE id = '".$arr['teilprojekt']."' LIMIT 1"); - }else{ - $arr['teilprojekt'] = ''; - } - }else{ - $arr['teilprojekt'] = ''; - } - }else{ - $arr['teilprojekt'] = ''; - } - - if($arr['kunde'] > 0){ - $arr['kunde'] = $this->app->DB->Select("SELECT CONCAT(kundennummer, ' ', name) FROM adresse WHERE id = '".$arr['kunde']."' LIMIT 1"); - } - - if($arr['art'] == ''){ - $arr['art'] = 'Arbeit'; - } - - - $newarr[] = $arr['name']; - $newarr[] = $arr['art']; - $newarr[] = $arr['projekt']; - $newarr[] = $arr['teilprojekt']; - $newarr[] = $arr['kunde']; - $newarr[] = $arr['abrechnen']; - break; - case "zeiterfassungprojektdetail": - $projekt = explode(' ',$this->app->Secure->GetPOST('projekt')); - $projektkennung = $projekt[0]; - - $kunde = $this->app->DB->Select("SELECT CONCAT(a.kundennummer,' ',a.name,' (',a.ort,')') AS kunde FROM projekt p JOIN adresse a ON p.kunde=a.id WHERE a.geloescht=0 AND p.abkuerzung='$projektkennung' LIMIT 1"); - $newarr[] = $kunde; - break; - - case "zolltarifnummer": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM zolltarifnummer WHERE beschreibung LIKE '%$term%' OR nummer LIKE '%$term%' ORDER by nummer"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - - case "kostenstelle": - $felder = array('CONCAT(nummer,\' \',beschreibung)','nummer','beschreibung'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM kostenstellen WHERE $subwhere ORDER by nummer"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "verrechnungsart": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM verrechnungsart WHERE beschreibung LIKE '%$term%' OR nummer LIKE '%$term%' ORDER by nummer"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - case "kundenrechnung": - case "kundenauftrag": - case "kundenlieferschein": - case "kundenangebot": - case "kundenproformarechnung": - $adresse = (int)$this->app->Secure->GetGET('adresse'); - if(!$adresse) - { - $kunde = explode(' ',$this->app->Secure->GetGET('kunde')); - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer = '".$kunde[0]."' AND kundennummer <> '' LIMIT 1"); - } - $beleg = str_replace('kunden','',$filtername); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',if(belegnr <> '',belegnr,'ENTWURF'),' ',kundennummer,' ',name) as name FROM $beleg WHERE (belegnr LIKE '%$term%' OR name LIKE '%$term%' OR kundennummer LIKE '$%term%') AND (status = 'angelegt' OR status = 'freigegeben') - ".($adresse?" AND adresse = '$adresse' ":'')." ".$this->app->erp->ProjektRechte('projekt')." - ORDER by belegnr LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - case "lieferantenpreisanfrage": - case "lieferantenbestellung": - $adresse = (int)$this->app->Secure->GetGET('adresse'); - if(!$adresse) - { - $lieferant = explode(' ',$this->app->Secure->GetGET('lieferant')); - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE lieferantennummer = '".$lieferant[0]."' AND lieferantennummer <> '' LIMIT 1"); - } - $beleg = str_replace('lieferanten','',$filtername); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',if(belegnr <> '',belegnr,'ENTWURF'),' ',lieferantennummer,' ',name) as name FROM $beleg WHERE (belegnr LIKE '%$term%' OR name LIKE '%$term%' OR lieferantennummer LIKE '$%term%') AND (status = 'angelegt' OR status = 'freigegeben') - ".($adresse?" AND adresse = '$adresse' ":'')." ".$this->app->erp->ProjektRechte('projekt')." - ORDER by belegnr LIMIT 20" ); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['name']; - break; - - // Suche nach einzelner Artikelnummer - case 'artikelnummer': - case 'artikelnummerseriennummer': - $isSeriennummer = $filtername === 'artikelnummerseriennummer'; - $tmp_where = ''; - if($isSeriennummer) { - $tmp_where = " AND seriennummern <> '' AND seriennummern <> 'keine' "; - } - $projekt = $this->app->Secure->GetGET('projekt'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - //$checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); - //$eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); - - //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = " AND projekt='$checkprojekt' "; - //else $tmp_where = ""; - - - $arr = $this->app->DB->SelectArr( - "SELECT CONCAT(nummer,' ',name_de) as `name` - FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where ". - $this->app->erp->ProjektRechte('art.projekt'). ' LIMIT 20' - ); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "artikelnummerstueckliste": - $tmp_where = ''; - $projekt = $this->app->Secure->GetGET('projekt'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - - $artikel_artikelnummer_suche = $this->app->erp->Firmendaten('artikel_artikelnummer_suche'); - - if($artikel_artikelnummer_suche){ - $felder[] = 'e.bestellnummer'; - $felder[] = 'v.kundenartikelnummer'; - } - - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - if($artikel_artikelnummer_suche){ - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(nummer,' ',name_de) as name - FROM artikel AS art - LEFT JOIN einkaufspreise e ON art.id = e.artikel AND e.bestellnummer != '' AND e.geloescht = 0 AND e.bestellnummer IS NOT NULL AND - (IFNULL(e.gueltig_bis,'0000-00-00') > NOW() OR IFNULL(e.gueltig_bis,'0000-00-00')='0000-00-00') - LEFT JOIN verkaufspreise v ON art.id = v.artikel AND v.kundenartikelnummer != '' AND v.geloescht = 0 AND v.kundenartikelnummer IS NOT NULL AND - (IFNULL(v.gueltig_bis,'0000-00-00') > NOW() OR IFNULL(v.gueltig_bis,'0000-00-00')='0000-00-00') - WHERE art.geloescht=0 AND ($subwhere) AND art.intern_gesperrt!=1 $tmp_where ". - $this->app->erp->ProjektRechte('art.projekt'). "LIMIT 20"); - }else{ - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where ". - $this->app->erp->ProjektRechte('art.projekt'). "LIMIT 20"); - } - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - - case "artikelnummermitseriennummern": - $tmp_where = ''; - $projekt = $this->app->Secure->GetGET('projekt'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND seriennummern<>'keine' $tmp_where ". - $this->app->erp->ProjektRechte('art.projekt'). 'LIMIT 20'); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "artikelmengeinbeleg": - $beleg = $this->app->Secure->GetGet('beleg'); - $belegid = $this->app->Secure->GetGet('id'); - $artikel = explode(' ',$this->app->Secure->GetPost('vorlage')); - $artikelnummer = $artikel[0]; - $artikelid = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer='$artikelnummer' AND geloescht=0 LIMIT 1"); - if($artikelid){ - $menge = $this->app->DB->Select('SELECT '.$this->app->erp->FormatMenge('SUM(menge)').' FROM '.$beleg."_position WHERE artikel='$artikelid' AND $beleg='$belegid'"); - } - if(!$menge){ - $menge='0'; - } - - $newarr[] = $menge; - break; - // Suche nach mehreren Artikelnummern (kommagetrennt) - case "artikelnummer_multi": - $tmp_where = ''; - if(strpos($term,',')!==false) { - $term = substr($term, (strripos($term,',')+1)); - } - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "portoartikel": - $tmp_where = ''; - //$projekt = $this->app->Secure->GetGET('projekt'); - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - //$checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); - //$eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); - - //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = " AND projekt='$checkprojekt' "; - //else $tmp_where = ""; - - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND porto = 1 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "juststuecklistenartikel": - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND stueckliste = 1 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "stuecklistenartikel": - $projekt = $this->app->Secure->GetGET('projekt'); - $tmp_where = ''; - if($projekt != '') - { - if(is_numeric($projekt)) - { - $tmp_where = " AND projekt = '$projekt' "; - }else{ - $projekt = $this->app->DB->Select("SELECT id FROM projekt WHERE ifnull(geloescht,0) = 0 AND abkuerzung = '$projekt' LIMIT 1"); - if($projekt){ - $tmp_where = " AND projekt = '$projekt' "; - } - } - } - $juststueckliste = $this->app->Secure->GetGET('juststueckliste'); - if($juststueckliste) - { - $swhere = ''; - }else{ - $swhere = ' AND juststueckliste = 0 '; - } - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND stueckliste = 1 $swhere $tmp_where LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++) { - $newarr[] = $arr[$i]['name']; - } - break; - break; - - case "artikelstueckliste": - $stuecklistenartikel = $this->app->Secure->GetGET('stuecklistenartikel'); - $artikelID = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer = '$stuecklistenartikel'"); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer,' ',a.name_de) AS name FROM artikel a LEFT JOIN stueckliste s ON a.id=s.artikel WHERE s.stuecklistevonartikel='$artikelID' AND a.geloescht=0 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++){ - $newarr[] = $arr[$i]['name']; - } - break; - - case "artikelinstueckliste": - $stuecklistenartikel = trim($this->app->Secure->GetGET('art')); - if($stuecklistenartikel != ''){ - $stuecklistenartikel = explode(' ', $stuecklistenartikel); - $stuecklistenartikelnr = $stuecklistenartikel[0]; - $stuecklistenartikelid = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer = '$stuecklistenartikelnr' LIMIT 1"); - if($stuecklistenartikelid != "" && $stuecklistenartikelid > 0){ - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer, ' ', a.name_de) as name FROM artikel a LEFT JOIN stueckliste s ON a.id = s.artikel WHERE a.geloescht = 0 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR a.herstellernummer LIKE '%$term%' OR a.ean LIKE '%$term%') AND a.intern_gesperrt != 1 AND s.stuecklistevonartikel = '$stuecklistenartikelid'"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - } - } - break; - - case "partlistfrom": - $article_id = $this->app->Secure->GetGET('article_id'); - $arr = $this->app->DB->SelectArr(" - SELECT concat(art.nummer,' ',art.name_de) as name - FROM artikel art - INNER JOIN (SELECT DISTINCT stuecklistevonartikel FROM stueckliste WHERE artikel = '$article_id') s - ON art.id = s.stuecklistevonartikel - WHERE (concat(art.nummer,' ',art.name_de) LIKE '%$term%' OR concat(art.nummer,' ',art.name_de) LIKE '%$term2%' OR concat(art.nummer,' ',art.name_de) LIKE '%$term3%') - "); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = $arr[$i]['name']; - } - break; - - break; - - case "artikelnummertagespreise": - $projekt = $this->app->Secure->GetGET('projekt'); - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - $checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); - $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); - - if($checkprojekt > 0 && $eigenernummernkreis=='1') - { - $tmp_where = " AND projekt='$checkprojekt' "; - } - else { - $tmp_where = ''; - } - - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel WHERE geloescht=0 AND tagespreise = 1 AND (nummer LIKE '%$term%' OR name_de LIKE '%$term%' OR nummer LIKE '%$term2%' OR name_de LIKE '%$term2%' OR nummer LIKE '%$term3%' OR name_de LIKE '%$term3%' OR herstellernummer LIKE '%$term%' OR ean LIKE '%$term%' ".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "keinelagerartikelnummer": - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name - FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 - AND (lagerartikel!='1' OR dienstleistung=1) AND porto!=1 AND stueckliste!=1 LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "lagerartikelnummer": - - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name - FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 - AND lagerartikel='1' LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "lagerartikelnummerohnechargemhdseriennummer": - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name - FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 - AND lagerartikel='1' AND chargenverwaltung = 0 AND mindesthaltbarkeitsdatum <> 1 AND (seriennummern = '' OR seriennummern = 'keine') ".$this->app->erp->ProjektRechte('projekt')." LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "lagerartikelkategorie": - $felder = array('bezeichnung'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT bezeichnung FROM artikelkategorien WHERE ($subwhere) AND geloescht=0"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "chargenartikel": - $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name - FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 - AND chargenverwaltung > 0 ".$this->app->erp->ProjektRechte('projekt')." LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "artikelnummerlager": - $lager_platz = (int)$this->app->Secure->GetGET('lager_platz'); - $lwhere = ''; - if($lager_platz){ - $lwhere = " and lpi.lager_platz = '$lager_platz' "; - } - $felder = array('ar.nummer','ar.name_de','ar.herstellernummer','ar.ean','CONCAT(ar.nummer,\' \',ar.name_de)'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'ar.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - // heute 13.07. das INNER zu einem LEFT gemacht - $arr = $this->app->DB->SelectArr("SELECT CONCAT(ar.nummer,' ',ar.name_de) as name - FROM artikel ar LEFT JOIN lager_platz_inhalt lpi ON ar.id=lpi.artikel WHERE ($subwhere) AND ar.geloescht=0 AND ar.intern_gesperrt!=1 - AND ar.lagerartikel='1' $lwhere GROUP BY CONCAT(ar.nummer,' ',ar.name_de) ".$this->app->erp->ProjektRechte('ar.projekt')." LIMIT 20"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - - case "artikelnummerprojektpos": - $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); - - if($this->app->erp->Firmendaten('artikel_freitext1_suche')) - { - $felder[] = 'a.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $projekt = $this->app->User->GetParameter('pos_list_projekt'); - $projekArr = $this->app->DB->SelectRow( - sprintf( - 'SELECT id, pos_artikelnurausprojekt,eanherstellerscan - FROM projekt WHERE id = %d - LIMIT 1', - (int)$projekt - ) - ); - $checkprojekt = 0; - $eigenernummernkreis = 0; - $eanherstellerscan = 0; - if(!empty($projekArr)){ - $checkprojekt = $projekArr['id']; - $eigenernummernkreis = $projekArr['pos_artikelnurausprojekt']; - $eanherstellerscan = $projekArr['eanherstellerscan']; - } - if($checkprojekt > 0 && $eigenernummernkreis=='1') { - $tmp_where = " AND a.projekt='$checkprojekt' "; - } - else { - $tmp_where = ''; - } - - // besser ist wenn man die immer scannt da es oberflächen gibt wo das projekt nicht angegeben werden kann - if(0)//$eanherstellerscan) - { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name, a.id FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term2%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term3%' OR a.herstellernummer LIKE '%$term%' OR a.ean LIKE '%$term%'".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") $tmp_where ORDER by a.id DESC LIMIT 20"); - } - else { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name, a.id FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ($subwhere) $tmp_where ORDER by a.id DESC LIMIT 20"); - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - { - $check_lagerartikel = $this->app->DB->Select("SELECT lagerartikel FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - if($check_lagerartikel) - { - $summe_im_lager = (float)$this->app->DB->Select("SELECT ifnull(SUM(li.menge),0) FROM lager_platz_inhalt li LEFT JOIN lager_platz lp ON lp.id=li.lager_platz WHERE li.artikel='".$arr[$i]['id']."'"); - if($summe_im_lager > 0) - { - $artikel_reserviert = (float)$this->app->DB->Select("SELECT ifnull(SUM(menge),0) FROM lager_reserviert WHERE artikel='".$arr[$i]['id']."' AND (datum>=NOW() OR datum='0000-00-00')"); - }else $artikel_reserviert = 0; - } - if($check_lagerartikel && ($summe_im_lager - $artikel_reserviert) <= 0) { - $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; - } else { - $lager=''; - } - $newarr[] = $arr[$i]['name'].$lager; - - } - break; - - - - case "artikelnummerprojekt": - $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $projekt = $this->app->Secure->GetGET('projekt'); - $checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); - $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); - $eanherstellerscan = $this->app->DB->Select("SELECT eanherstellerscan FROM projekt WHERE id='$projekt'"); - - if($checkprojekt > 0 && $eigenernummernkreis=='1') { - $tmp_where = " AND a.projekt='$checkprojekt' "; - } - else { - $tmp_where = ''; - } - - // besser ist wenn man die immer scannt da es oberflächen gibt wo das projekt nicht angegeben werden kann - if(0)//$eanherstellerscan) - { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR a.herstellernummer LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term2%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term3%' OR a.ean LIKE '%$term%'".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") $tmp_where ORDER by a.id DESC LIMIT 20"); - } - else { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ($subwhere) $tmp_where ORDER by a.id DESC LIMIT 20"); - - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - - case "lagerartikelnummerprojekt": - $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); - - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - if($artikel_freitext1_suche) - { - $felder[] = 'art.freifeld1'; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer,' ',a.name_de,' (',p.abkuerzung,')') as name FROM artikel a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.porto=0 AND a.intern_gesperrt!=1 - AND ( - $subwhere - ) LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - - case "verkaufartikelnummerprojekt": - $letzte_menge = null; - $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); - $projekt = $this->app->Secure->GetGET('projekt'); - $projectRow = empty($projekt)?null: $this->app->DB->SelectRow( - sprintf( - 'SELECT `id`, `eigenernummernkreis`, `projektlager` FROM `projekt` WHERE `id` = %d', $projekt - ) - ); - $checkprojekt = empty($projectRow)?null:$projectRow['id'];// $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); - $eigenernummernkreis = empty($projectRow)?null:$projectRow['eigenernummernkreis'];//$this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); - $projectStorage = !empty($projectRow['projektlager'])?$checkprojekt:0; - $smodule = $this->app->Secure->GetGET('smodule'); - $sid = $this->app->Secure->GetGET('sid'); - $document = $this->app->DB->SelectRow(sprintf('SELECT * FROM `%s` WHERE `id` = %d', $smodule, $sid)); - - $adresse = $document['adresse'];// $this->app->DB->Select("SELECT adresse FROM $smodule WHERE id='$sid' LIMIT 1"); - $waehrung = $document['waehrung'];//$this->app->DB->Select("SELECT waehrung FROM $smodule WHERE id='$sid' LIMIT 1"); - $posanz = (int)$this->app->DB->Select("SELECT count(id) FROM $smodule"."_position WHERE $smodule = '$sid'"); - - if($posanz == 0) - { - $waehrung = ''; - } - - $anzeigebrutto = false; - if($smodule == 'auftrag' || $smodule == 'rechnung' || $smodule == 'gutschrift' || $smodule == 'angebot' || $smodule == 'proformarechnung') - { - $_anrede = $this->app->DB->Select("SELECT typ FROM $smodule WHERE id = '$sid' LIMIT 1"); - $_projekt = $this->app->DB->Select("SELECT projekt FROM $smodule WHERE id = '$sid' LIMIT 1"); - $funktion = ucfirst($smodule).'MitUmsatzeuer'; - if($this->app->erp->AnzeigePositionenBrutto($_anrede, $smodule, $_projekt, $adresse,$sid) && $this->app->erp->$funktion($sid)) - { - $anzeigebrutto = true; - } - } - - $tmp_where = $this->app->erp->ProjektRechte('p.id', true, '', array(0, $projekt)); - //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = $this->app->erp->ProjektRechte(); - //else $tmp_where = ""; - $felder = array('a.nummer','a.name_de','a.ean','a.herstellernummer','a.name_de','CONCAT(a.nummer,\' \',a.name_de)'); - if($artikel_freitext1_suche) - { - $felder[] = 'a.freifeld1'; - } - - $artikel_artikelnummer_suche = $this->app->erp->Firmendaten('artikel_artikelnummer_suche'); - - if($artikel_artikelnummer_suche){ - $felder[] = 'v.kundenartikelnummer'; - $felder[] = 'e.bestellnummer'; - - $artikelnummer_suche_join = " - LEFT JOIN `einkaufspreise` AS `e` ON e.artikel=a.id AND e.geloescht = 0 - AND e.bestellnummer IS NOT NULL AND (e.gueltig_bis IS NULL OR e.gueltig_bis = '0000-00-00' OR e.gueltig_bis >= CURDATE()) - AND (e.gueltig_bis > NOW() OR e.gueltig_bis='0000-00-00' OR e.gueltig_bis IS NULL) "; - if($waehrung === 'EUR') { - $artikelnummer_suche_join .= " AND (e.waehrung='EUR' OR e.waehrung = '') "; - } - elseif($waehrung != ''){ - $artikelnummer_suche_join .= " AND e.waehrung='{$waehrung}' "; - } - $artikelnummer_suche_join .= "LEFT JOIN `verkaufspreise` AS `v` ON v.artikel=a.id AND v.geloescht = 0 - AND v.kundenartikelnummer IS NOT NULL - AND (v.gueltig_bis > NOW() OR v.gueltig_bis='0000-00-00' OR v.gueltig_bis IS NULL) "; - if($waehrung === 'EUR') { - $artikelnummer_suche_join .= " AND (v.waehrung='EUR' OR v.waehrung = '') "; - } - elseif($waehrung != ''){ - $artikelnummer_suche_join .= " AND v.waehrung = '{$waehrung}' "; - } - - $artikelnummer_suche_where = ''; - }else{ - $artikelnummer_suche_join = ""; - $artikelnummer_suche_where = ""; - } - - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr( - "SELECT DISTINCT a.id as id, - CONCAT( - a.nummer,' ',a.name_de,' (',p.abkuerzung,if(a.lagerartikel=1,'',''),')', - if(a.herstellernummer!='',CONCAT(' (PN: ',a.herstellernummer,')'),'') - ) as `name` , a.lagerartikel, a.porto, a.keinrabatterlaubt, a.juststueckliste, a.stueckliste - FROM `artikel` AS `a` - LEFT JOIN `projekt` AS `p` ON p.id=a.projekt - ".$artikelnummer_suche_join." - WHERE a.geloescht=0 AND a.intern_gesperrt!=1 - ".$artikelnummer_suche_where." - AND ($subwhere) $tmp_where LIMIT 20"); - - - $rabatt = $this->app->DB->Select("SELECT realrabatt FROM $smodule WHERE id='$sid' LIMIT 1"); - $sql_erweiterung = ''; - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++) { - - $arr[$i]['name'] = $this->app->DB->Select("SELECT CONCAT(nummer,' ',name_de,if(herstellernummer!='',CONCAT(' (PN: ',herstellernummer,')'),'') ) FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $keinrabatterlaubt = $arr[$i]['keinrabatterlaubt'];//$this->app->DB->Select("SELECT keinrabatterlaubt FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $checkporto = $arr[$i]['porto'];//$this->app->DB->Select("SELECT porto FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $gruppenarray = $this->app->erp->GetGruppen($adresse); - $cgruppenarray = !empty($gruppenarray)?count($gruppenarray):0; - if($cgruppenarray >0) - { - $sql_erweiterung = ' OR '; - } - for($gi=0;$gi<$cgruppenarray;$gi++) - { - $sql_erweiterung .= " gruppe='".$gruppenarray[$gi]."' "; - - if($gi<$cgruppenarray-1){ - $sql_erweiterung .= ' OR '; - } - } - - $vkarr = $this->app->erp->GeneratePreisliste($arr[$i]['id'],$adresse,$rabatt, $waehrung); - - $check_lagerartikel = $arr[$i]['lagerartikel'];//$this->app->DB->Select("SELECT lagerartikel FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $isJit = $arr[$i]['juststueckliste']; - //$newarr[]=$arr[$i]['name']." ($label Inkl. Rabatt ".$rabatt."%: ".$this->app->erp->Rabatt($arr[$i]['preis'],$rabatt).")"; - if($isJit) { - $preproducedpartlist = $this->app->erp->getPreproducedPartlistFromArticle($arr[$i]['id']); - if(!empty($preproducedpartlist) - && ($partlistsellable = $this->app->erp->ArtikelAnzahlVerkaufbar($preproducedpartlist, $projektlager)) - ) { - $lager = ' (Verfügbar: '.round($partlistsellable,4); - } - else { - $lager = (float)$this->app->erp->ArtikelAnzahlLagerStueckliste($arr[$i]['id'], $projectStorage); - if($lager == 0) { - $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; - } - else { - $lager = ' (Verfügbar: '.round($lager,4); - } - } - } - elseif($this->app->erp->LagerFreieMenge($arr[$i]['id']) <= 0 && $check_lagerartikel){ - $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; - } - else{ - if($this->app->erp->Firmendaten('lagerbestand_in_auftragspositionen_anzeigen')){ - $artikel_reserviert = $this->app->DB->Select('SELECT '.$this->app->erp->FormatMenge('SUM(menge)')." FROM lager_reserviert WHERE artikel='".$arr[$i]['id']."' AND (datum>=NOW() OR datum='0000-00-00')"); - - $lager=' (Verfügbar: '.$this->app->erp->LagerFreieMenge($arr[$i]['id']); - if($artikel_reserviert) - { - $lager .= ' Reserviert: '.$artikel_reserviert; - } - else { - $lager .= ' Reserviert: 0'; - } - $lager .= ') '; - }else{ - $lager=''; - } - } - $cvkarr = !empty($vkarr)?count($vkarr):0; - $letzte_menge = null; - for($vi=0;$vi<$cvkarr;$vi++) - { - if(isset($vkarr[$vi]['ab_menge'])) - { - $vkarr[$vi]['ab_menge'] = round($vkarr[$vi]['ab_menge'], 8); - } - $tmprabatt = $rabatt; - if($vkarr[$vi]['art']=='Kunde' && ($vkarr[$vi]['adresse']<=0 || $vkarr[$vi]['adresse']=='')){ - $vkarr[$vi]['art'] = 'Standardpreis'; - } - - $preis = 0; - if($letzte_menge !=$vkarr[$vi]['ab_menge']) - { - if($keinrabatterlaubt=='1' || $checkporto=='1') - { - $preis = $vkarr[$vi]['preis']; //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); - - $newarr[]=$arr[$i]['name']." $lager ab Menge ".$vkarr[$vi]['ab_menge'].' | Preis: '.$preis. - ' ('.$vkarr[$vi]['art'].' - Kein Rabatt erlaubt) '; - - } else { - if($this->app->erp->IsSpezialVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse)) - { - $tmprabatt=0; - $rabatt_string = ' - Kein Rabatt auf Spezialpreis'; - $uvp_string = '(UVP: '.$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse).") "; - } else { - if($tmprabatt > 0) { - $rabatt_string = ' Inkl. Rabatt '.$tmprabatt.'%'; - $uvp_string = '(UVP: '.$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse).") "; - } else { - $rabatt_string = ''; - $uvp_string = ''; - } - } - - if($anzeigebrutto) - { - $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id = '".$arr[$i]['id']."' LIMIT 1"); - if($umsatzsteuer == 'ermaessigt') - { - $vkarr[$vi]['preis'] = round($vkarr[$vi]['preis']* (1+ (float)$this->app->DB->Select("SELECT steuersatz_ermaessigt FROM $smodule WHERE id = '$sid' LIMIT 1")/100),8); - }elseif($umsatzsteuer != 'befreit') - { - $vkarr[$vi]['preis'] = round($vkarr[$vi]['preis'] * (1+ (float)$this->app->DB->Select("SELECT steuersatz_normal FROM $smodule WHERE id = '$sid' LIMIT 1")/100),8); - } - } - - if($this->app->erp->Firmendaten('viernachkommastellen_belege')){ - $preis = number_format(rtrim($vkarr[$vi]['preis'], 0), 4, ',', '.'); //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); - } - else{ - $preis = number_format(rtrim($vkarr[$vi]['preis'], 0), 2, ',', '.'); //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); - } - - $newarr[]=$arr[$i]['name'].($vkarr[$vi]['vpe']!=''?' (Menge in VPE: '.$vkarr[$vi]['vpe'].")":"")." $lager ab Menge ".$vkarr[$vi]['ab_menge']." | Preis: ".$preis. - " $uvp_string(".$vkarr[$vi]['art'].$rabatt_string.') '; - } - } - } - - if($vi==0) - { - $rabattartikel = $this->app->DB->Select("SELECT rabatt FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $rabattartikel_prozent = $this->app->DB->Select("SELECT rabatt_prozent FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - $arr[$i]['name'] = $this->app->DB->Select("SELECT CONCAT(nummer,' ',name_de,if(herstellernummer!='',CONCAT(' (PN: ',herstellernummer,')'),'')) FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); - - if($rabattartikel=='1'){ - $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: $rabattartikel_prozent% Rabatt auf Gesamtsumme ohne Porto"; - } - else { - $preis = $this->app->erp->GetVerkaufspreis($arr[$i]['id'],1,$adresse,$waehrung); - if($preis > 0){ - $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: $preis"; - } - else{ - $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: nicht vorhanden"; - } - } - } - } - break; - - case "einkaufartikelnummerprojekt": - - $smodule = $this->app->Secure->GetGET('smodule'); - $sid = $this->app->Secure->GetGET('sid'); - - $waehrung = $this->app->DB->Select("SELECT `waehrung` FROM `{$smodule}` WHERE `id`='{$sid}' LIMIT 1"); - - $felder = [ - 'a.nummer', - 'a.name_de', - 'e.bezeichnunglieferant', - 'e.bestellnummer', - ]; - - $artikel_artikelnummer_suche = (int)$this->app->erp->Firmendaten('artikel_artikelnummer_suche'); - - if($artikel_artikelnummer_suche > 0){ - $felder[] = 'v.kundenartikelnummer'; - - $artikelnummer_suche_join = 'LEFT JOIN `verkaufspreise` `v` ON v.artikel=a.id' - .' AND v.geloescht = 0 AND v.kundenartikelnummer IS NOT NULL ' - . " AND (v.gueltig_bis > NOW() OR v.gueltig_bis='0000-00-00' OR v.gueltig_bis IS NULL) "; - if($waehrung === 'EUR') { - $artikelnummer_suche_join .= "AND (v.waehrung='EUR' OR v.waehrung = '')"; - } - elseif($waehrung != ''){ - $artikelnummer_suche_join .= "AND v.waehrung='{$waehrung}'"; - } - $artikelnummer_suche_where = ''; - }else{ - $artikelnummer_suche_join = ""; - $artikelnummer_suche_where = ""; - } - - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $adresse = (int)$this->app->Secure->GetGET('adresse'); - - $sql = "SELECT - CONCAT( - a.nummer, - ' ', - a.name_de, - ' | Bezeichnung bei Lieferant ', - IFNULL(e.bestellnummer,'nicht vorhanden'), - ' ', - LEFT(IFNULL(e.bezeichnunglieferant,'nicht vorhanden'),50), - ' | ', - ' ab Menge ', - ".$this->app->erp->FormatMenge("IFNULL(e.ab_menge,1)").", - ' | Preis ', - ".$this->app->erp->FormatPreis("IFNULL(e.preis,0)").", - ' | VPE ', - ".$this->app->erp->FormatMenge("IF(IFNULL(e.vpe,1)='',1,IFNULL(e.vpe,1))")." - ) as `name` - FROM `artikel` AS `a` - LEFT JOIN `projekt` AS `p` ON p.id=a.projekt - LEFT JOIN `einkaufspreise` AS `e` ON e.artikel=a.id " - .($waehrung!=""?"AND IFNULL(e.waehrung,'$waehrung')='$waehrung'":""). - $artikelnummer_suche_join." - WHERE a.tagespreise = 0 AND a.geloescht=0 AND a.intern_gesperrt!=1 - AND (e.gueltig_bis > NOW() OR e.gueltig_bis='0000-00-00' OR e.gueltig_bis IS NULL)". - $artikelnummer_suche_where." - AND (IFNULL(e.adresse,0)='$adresse' OR a.allelieferanten=1) - AND $subwhere " - .$this->app->erp->ProjektRechte("a.projekt")." - GROUP BY a.nummer,a.name_de,e.bezeichnunglieferant,e.bestellnummer, e.preis, e.ab_menge, e.vpe LIMIT 20"; - - $arr = $this->app->DB->SelectArr($sql); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "lieferantname": - $felder = array('a.nummer','a.name_de','e.bezeichnunglieferant','e.bestellnummer'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT name FROM adresse - WHERE geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ( - name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' - ) order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "lieferant": - //$arr = $this->app->DB->SelectArr("SELECT CONCAT(a.lieferantennummer,' ',a.name) as name FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.lieferantennummer!='' AND lieferantennummer!='0' AND (a.name LIKE '%$term%' OR a.lieferantennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte()." order by a.name LIMIT 20"); - /* - $arr = $this->app->DB->SelectArr("SELECT a.lieferantennummer, - - (SELECT - CONCAT(a2.lieferantennummer, ' ',a2.name) - FROM adresse a2 WHERE a2.lieferantennummer = a.lieferantennummer ".$this->app->erp->ProjektRechte("a2.projekt")." ORDER BY - ".($filter_projekt?" a2.projekt = '$filter_projekt' DESC, ":"")." a2.projekt LIMIT 1 - )as name2 - FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.lieferantennummer!='' AND lieferantennummer!='0' AND (a.name LIKE '%$term%' OR a.lieferantennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte()." group by a.lieferantennummer order by name2 LIMIT 20"); - */ - $felder = array("concat(a.lieferantennummer,' ',a.name, if(a.ort!='', CONCAT(' ',a.ort),''))"); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - - $arr = $this->app->DB->SelectArr("SELECT concat(a.lieferantennummer,' ',a.name, if(a.ort!='', CONCAT(' (',a.ort,')'),'')) as name2 - FROM adresse a INNER JOIN (SELECT a2.lieferantennummer, ".($filter_projekt?" min( if(a2.projekt = ".$filter_projekt.", -1,a2.projekt))":" min(a2.projekt) ")." as mprojekt FROM adresse a2 - LEFT JOIN adresse_rolle ar2 ON a2.id = ar2.adresse AND ar2.projekt > 0 ".$this->app->erp->ProjektRechte("ar2.projekt")." - WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.lieferantennummer!='' AND a2.lieferantennummer!='0' AND (1 ".$this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb')." OR not isnull(ar2.id) ) - group by a2.lieferantennummer) adr - ON a.lieferantennummer = adr.lieferantennummer AND ".($filter_projekt?"(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)":"a.projekt = adr.mprojekt")." - LEFT JOIN adresse_rolle ar ON a.id = ar.adresse AND ar.projekt > 0 - WHERE a.geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ($subwhere) - group by a.lieferantennummer order by name2 LIMIT 20 - - "); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name2']; - } - break; - - case "lieferantartikel": - $felder = array("concat(a.lieferantennummer,' ',a.name)"); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $artikel = (int)$this->app->Secure->GetGET('artikel'); - $arr = $this->app->DB->SelectArr("SELECT concat(a.lieferantennummer,' ',a.name) as name2 - FROM adresse a INNER JOIN (SELECT a2.lieferantennummer, ".($filter_projekt?" min( if(a2.projekt = ".$filter_projekt.", -1,a2.projekt))":" min(a2.projekt) ")." as mprojekt FROM adresse a2 - WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.lieferantennummer!='' AND a2.lieferantennummer!='0' ".$this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb')." - group by a2.lieferantennummer) adr - ON a.lieferantennummer = adr.lieferantennummer AND ".($filter_projekt?"(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)":"a.projekt = adr.mprojekt")." - INNER JOIN einkaufspreise ep ON ep.adresse = a.id AND ep.artikel = '$artikel' - WHERE a.geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ($subwhere) ".$this->app->erp->ProjektRechte("a.projekt")." group by a.lieferantennummer order by name2 LIMIT 20 - - "); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name2']; - } - break; - - case "adressegruppevertriebbearbeiter": - - $typ = $this->app->Secure->GetGET('typ'); - if($typ === 'vertrieb'){ - $gruppe = $this->app->erp->Firmendaten('group_sales'); - }elseif($typ === 'bearbeiter'){ - $gruppe = $this->app->erp->Firmendaten('group_employee'); - }else{ - $gruppe = ''; - } - - $gruppeJoin = ''; - $gruppeWhere = ''; - - if($gruppe !== ''){ - $gruppeKennziffer = explode(' ', $gruppe); - $gruppeKennziffer = $gruppeKennziffer[0]; - $gruppeId = $this->app->DB->Select("SELECT id FROM gruppen WHERE kennziffer = '$gruppeKennziffer' LIMIT 1"); - if($gruppeId > 0){ - $gruppeJoin = - ' LEFT JOIN `adresse_rolle` AS `ar` ON a.id = ar.adresse'; - - $gruppeWhere = - ' AND ar.subjekt = \'Mitglied\' AND ar.objekt = \'Gruppe\' AND ar.parameter = \''.$gruppeId.'\' - AND ar.von <= CURDATE() AND (ar.bis = \'0000-00-00\' OR ar.bis >= CURDATE())'; - } - } - - $felder = - array( - '(CASE - WHEN a.lieferantennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\' Liefr: \',a.lieferantennummer,\')\') - WHEN a.kundennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\')\') - WHEN a.mitarbeiternummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Mitr: \',a.mitarbeiternummer,\')\') - END)' - ); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $sql = - 'SELECT - (CASE - WHEN a.lieferantennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\' Liefr: \',a.lieferantennummer,\')\') - WHEN a.kundennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\')\') - WHEN a.mitarbeiternummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Mitr: \',a.mitarbeiternummer,\')\') - END) AS `name` - FROM `adresse` AS `a` '.$gruppeJoin.' - WHERE a.geloescht=0 - AND ('.$subwhere.') '.$gruppeWhere.$this->app->erp->ProjektRechte('a.projekt').' - ORDER BY a.name LIMIT 20'; - - $arr = $this->app->DB->SelectArr($sql); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - - break; - - case "adresse": - $felder = array("if(a.lieferantennummer,CONCAT(a.name,' ',a.kundennummer,' ',a.lieferantennummer,')'),CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,')'))"); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $sql = "SELECT if(a.lieferantennummer,CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,' Liefr: ',a.lieferantennummer,')'),CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,')')) as `name` - FROM adresse a WHERE a.geloescht=0 AND ($subwhere) ".$this->app->erp->ProjektRechte('a.projekt')." - order by a.name LIMIT 20"; - $arr = $this->app->DB->SelectArr($sql); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "adressemitvertrieb": - $felder = array("concat(a.name, - if(a.kundennummer <> '' OR a.lieferantennummer <> '' OR a.mitarbeiternummer <> '', - concat(if(a.kundennummer <> '',concat(' ',a.kundennummer),''), if(a.kundennummer <> '' AND a.lieferantennummer <> '',' ',''),if(a.lieferantennummer <> '',concat(' ',a.lieferantennummer),'') - ,if((a.kundennummer <> '' OR a.lieferantennummer <> '') AND a.mitarbeiternummer <> '',' ',''), - if(a.mitarbeiternummer <> '',concat(' ',a.mitarbeiternummer),'') - ) - ,'') - )"); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT concat(a.id, ' ',a.name, - if(a.kundennummer <> '' OR a.lieferantennummer <> '' OR a.mitarbeiternummer <> '', - concat(' (',if(a.kundennummer <> '',concat('Kdr: ',a.kundennummer),''), if(a.kundennummer <> '' AND a.lieferantennummer <> '',' ',''),if(a.lieferantennummer <> '',concat('Liefr: ',a.lieferantennummer),'') - ,if((a.kundennummer <> '' OR a.lieferantennummer <> '') AND a.mitarbeiternummer <> '',' ',''), - if(a.mitarbeiternummer <> '',concat('Mitr: ',a.mitarbeiternummer),'') - ,')') - ,'') - ) - as name - - FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND ($subwhere) AND ((1 ".$this->app->erp->ProjektRechte().") OR a.id = '".$this->app->User->GetAdresse()."') order by a.name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case 'kundepos': - $aktprojekt = $this->app->User->GetParameter('pos_list_projekt'); - $felder = array("CONCAT(ifnull(a.kundennummer,''),' ',a.name,if(a.projekt > 0,CONCAT(' (',p.abkuerzung,')'),''),if(ifnull(a.freifeld1,'')!='',CONCAT(' (',a.freifeld1,')'),''))"); - - $swhere = ''; - if($aktprojekt && !$this->app->DB->Select("SELECT pos_kundenalleprojekte FROM projekt WHERE id = '$aktprojekt' LIMIT 1") && $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id = '$aktprojekt' LIMIT 1")){ - $swhere = " AND p.id = '$aktprojekt' "; - } - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.kundennummer,' ',a.name,if(a.projekt > 0,CONCAT(' (',p.abkuerzung,')'),''),if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.kundennummer!='' AND a.kundennummer!='0' AND ($subwhere) $swhere order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case 'kunde': - - $felder = array("CONCAT(a.kundennummer, ' ',a.name,if(ifnull(a.freifeld1,'')!='',CONCAT(' (',ifnull(a.freifeld1,''),')'),''),' ',a.plz,' ',a.ort)"); - if($term2 === $term){ - $term2 = ''; - } - if($term3 === $term){ - $term3 = ''; - } - $terma = explode('%', trim(str_replace('%%','%',$term),'%')); - $terma2 = explode('%', trim(str_replace('%%','%',$term2),'%')); - $terma3 = explode('%', trim(str_replace('%%','%',$term3),'%')); - foreach($felder as $v) - { - $subwherea[] = " $v LIKE '%$term%' "; - if($term2 !== '') - { - $subwherea[] = " $v LIKE '%$term2%' "; - } - if($term3 !== '') - { - $subwherea[] = " $v LIKE '%$term3%' "; - } - } - $terma21 = ''; - $terma22 = ''; - $terma31 = ''; - $terma32 = ''; - if(count($terma2) > 1) - { - $terma22 = $terma2[count($terma2)-1]; - unset($terma2[count($terma2)-1]); - $terma21 = implode('%', $terma2); - } - if(count($terma3) > 1) - { - $terma32 = $terma3[count($terma3)-1]; - unset($terma3[count($terma3)-1]); - $terma31 = implode('%', $terma3); - } - - if(count($terma) > 1) { - $terma12 = $terma[count($terma)-1]; - unset($terma[count($terma)-1]); - $terma11 = implode('%', $terma); - $subwheretmpa1 = null; - $subwheretmpa2 = null; - foreach($felder as $v) { - if($v !== 'a.ort') - { - $subwheretmpa1[] = " $v LIKE '%$terma11%' "; - $subwheretmpa2[] = " $v LIKE '%$terma12%' "; - if($terma21 !== '') - { - $subwheretmpa1[] = " $v LIKE '%$terma21%' "; - $subwheretmpa2[] = " $v LIKE '%$terma22%' "; - } - if($terma31 !== '') - { - $subwheretmpa1[] = " $v LIKE '%$terma31%' "; - $subwheretmpa2[] = " $v LIKE '%$terma32%' "; - } - } - } - $subwheretmpa3[] = " a.ort LIKE '%$terma12%' "; - $subwheretmpa4[] = " a.ort LIKE '%$terma11%' "; - if($terma21 !== '') - { - $subwheretmpa3[] = " a.ort LIKE '%$terma22%' "; - $subwheretmpa4[] = " a.ort LIKE '%$terma21%' "; - } - if($terma31 !== '') - { - $subwheretmpa3[] = " a.ort LIKE '%$terma32%' "; - $subwheretmpa4[] = " a.ort LIKE '%$terma31%' "; - } - - $subwherea[] = " ((".implode(' OR ', $subwheretmpa3).") AND (".implode(" OR ", $subwheretmpa1).") ) "; - $subwherea[] = " ((".implode(' OR ', $subwheretmpa4).") AND (".implode(" OR ", $subwheretmpa2).") ) "; - } - - //$subwhere = implode(' OR ', $subwherea); - - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - if($this->app->DB->Select('SELECT id FROM projekt WHERE geloescht <> 1 AND eigenernummernkreis = 1 LIMIT 1')){ - $sql = "SELECT CONCAT(a.kundennummer, ' ',a.name,if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name, a.ort - FROM adresse AS a - INNER JOIN - ( - SELECT a2.kundennummer, " . ($filter_projekt ? " min( if(a2.projekt = " . $filter_projekt . ", -1,a2.projekt))" : " min(a2.projekt) ") . " as mprojekt - FROM adresse a2 - WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.kundennummer!='' AND a2.kundennummer!='0' " . $this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb') . " - group by a2.kundennummer - ) AS adr - ON a.kundennummer = adr.kundennummer AND " . ($filter_projekt ? "(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)" : "a.projekt = adr.mprojekt") . " - WHERE ($subwhere) - " . $this->app->erp->ProjektRechte('a.projekt', true, 'a.vertrieb') . ' - GROUP BY a.kundennummer, a.name, a.ort - ORDER BY `name` LIMIT 20 - '; - } - else { - $sql = " - SELECT CONCAT(a.kundennummer, ' ',a.name,if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name, a.ort - FROM adresse AS a - WHERE ($subwhere) AND kundennummer <> '' AND kundennummer <> '0' AND a.geloescht <> 1 - " . $this->app->erp->ProjektRechte('a.projekt', true, 'a.vertrieb') . ' - GROUP BY a.kundennummer, a.name, a.ort - ORDER BY `name` LIMIT 20 - '; - } - $arr = $this->app->DB->SelectArr($sql); - - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - { - if($arr[$i]['ort']!=''){ - $newarr[] = $arr[$i]['name'] . ' (' . $arr[$i]['ort'] . ')'; - } - else{ - $newarr[] = $arr[$i]['name']; - } - } - break; - case "mitarbeiter": - $felder = array('mitarbeiternummer','name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(mitarbeiternummer,' ',name) as name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "mitarbeiterid": - $felder = array('mitarbeiternummer','name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',name) as name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "mitarbeiteraktuell": - $felder = array('mitarbeiternummer','name'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.mitarbeiternummer,' ',a.name) as name FROM adresse a LEFT JOIN adresse_rolle ar ON a.id = ar.adresse WHERE a.geloescht=0 AND a.mitarbeiternummer!='' AND a.mitarbeiternummer!='0' AND ($subwhere) AND ar.subjekt = 'Mitarbeiter' AND (ar.bis = '0000-00-00' OR ar.bis >= CURDATE()) ORDER BY name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "mitarbeitername": - $felder = array('name','mitarbeiternummer'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "emailadresse": - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - $subwhere1 = ''; - $subwhere2 = ''; - if($this->app->Secure->GetGET('kundennummer')!="") - { - //$adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer like '".$this->app->Secure->GetGET('kundennummer')."' ".($filter_projekt?" AND (projekt = '$filter_projekt' or projekt = 0) ":"")." LIMIT 1"); - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer like '".$this->app->Secure->GetGET('kundennummer')."' AND geloescht <> 1 ORDER BY ".($filter_projekt?" projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); - if($adresse) - { - $subwhere1 .= " AND adresse = '$adresse' "; - $subwhere2 .= " AND id = '$adresse' "; - } - } - - if($this->app->Secure->GetGET('kd_lf_ma_nummer')!="") - { - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE (kundennummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."' OR lieferantennummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."' OR mitarbeiternummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."') AND geloescht <> 1 ORDER BY ".($filter_projekt?" projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); - if($adresse) - { - $subwhere1 .= " AND adresse = '$adresse' "; - $subwhere2 .= " AND id = '$adresse' "; - } - } - - if($this->app->Secure->GetGET('kd_id')){ - $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE id = '".$this->app->Secure->GetGET('kd_id')."' AND geloescht != 1 ORDER BY ".($filter_projekt?"projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); - if($adresse){ - $subwhere1 .= " AND adresse = '$adresse' "; - $subwhere2 .= " AND id = '$adresse' "; - } - } - - $limit = "LIMIT 20"; - if ($this->app->Secure->GetGET('limit')) { - $limit = "LIMIT 1"; - } - - if($limit=="LIMIT 1") - { - $arr = $this->app->DB->SelectArr("SELECT email FROM ansprechpartner WHERE email <> '' $subwhere1 AND geloescht <> 1 order by name $limit"); - } else { - $arr = $this->app->DB->SelectArr("SELECT email FROM ansprechpartner WHERE (name LIKE '%$term%' OR email LIKE '%$term%') and email <> '' $subwhere1 AND geloescht <> 1 order by name $limit"); - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['email']; - } - if($limit=="LIMIT 1") - { - $arr = $this->app->DB->SelectArr("SELECT email FROM adresse WHERE geloescht!='1' $subwhere2 order by name $limit"); - } - else - { - $arr = $this->app->DB->SelectArr("SELECT email FROM adresse WHERE (name LIKE '%$term%' OR email LIKE '%$term%') and email <> '' AND geloescht!='1' $subwhere2 order by name $limit"); - } - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['email']; - } - - $newarr = array_unique($newarr); - sort($newarr); - break; - case "emailbackup": - $arr = $this->app->DB->SelectArr("SELECT email FROM emailbackup"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['email']; - } - - $newarr = array_unique($newarr); - sort($newarr); - break; - case "emailname": - - $felder = array("CONCAT(name,' -ltrep-',email,'-gtrep-')",'name','email'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' -ltrep-',email,'-gtrep-') as name FROM ansprechpartner WHERE ($subwhere) AND geloescht <> 1 order by name LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - - $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' -ltrep-',email,'-gtrep-') as name FROM adresse WHERE ($subwhere) AND geloescht!='1' order by name LIMIT 20"); - - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++){ - $newarr[] = $arr[$i]['name']; - } - - $newarr = array_unique($newarr); - sort($newarr); - $isChangeLtGt = true; - break; - - case "shopname": - $arr = $this->app->DB->SelectArr("SELECT s.bezeichnung FROM shopexport s LEFT JOIN projekt p ON p.id=s.projekt WHERE s.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("s.projekt")); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "shopnameid": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',bezeichnung) as bezeichnung FROM shopexport WHERE bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("projekt").""); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "gruppekennziffer": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g LEFT JOIN projekt p ON p.id=g.projekt - WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "preisgruppekennziffer": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g LEFT JOIN projekt p ON p.id=g.projekt - WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.art = 'preisgruppe' AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "gruppe": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.name,' ',g.kennziffer) as bezeichnung FROM gruppen g - LEFT JOIN projekt p ON p.id=g.projekt WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "verband": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' ',kennziffer) as bezeichnung FROM gruppen WHERE (name LIKE '%$term%' OR kennziffer LIKE '%$term%') AND aktiv=1 AND art='verband'"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "verbindlichkeit": - $felder = array("CONCAT(v.belegnr, v.betrag, a.name, v.rechnung, a.lieferantennummer, a.lieferantennummer_buchhaltung, ".$this->app->erp->FormatPreis('v.betrag',2).")", - 'v.id','IFNULL(v.belegnr, \'\')','v.betrag','a.name','v.rechnung','a.lieferantennummer','a.lieferantennummer_buchhaltung',$this->app->erp->FormatPreis('v.betrag',2)); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - if(strpos($term,',')!==false) - { - $term = substr($term,strripos($term,',')); - $term = str_replace(',','',$term); - } - - $sql = - "SELECT CONCAT(v.id, - IF(IFNULL(v.belegnr, '') <> '' AND v.belegnr!=v.id, - CONCAT(' Nr. ',v.belegnr),''), - ' Betrag: ',".$this->app->erp->FormatPreis('v.betrag',2).", - if(v.skonto <> 0,CONCAT(' mit Skonto ',v.skonto,'% ', - ".$this->app->erp->FormatPreis("v.betrag-((v.betrag/100.0)*v.skonto)",2)."),''),' ', - ' Ist: ',".$this->app->erp->FormatPreis('v.betragbezahlt',2).", - ' Offen: ',".$this->app->erp->FormatPreis( - 'IF(v.betrag - v.betragbezahlt > ((v.betrag/100.0)*v.skonto), - v.betrag - v.betragbezahlt,0)',2 - ).", - - a.name,' (Lieferant ',a.lieferantennummer,if(a.lieferantennummer_buchhaltung!='' AND a.lieferantennummer <> a.lieferantennummer_buchhaltung,CONCAT(' ',a.lieferantennummer_buchhaltung),''),') RE ',v.rechnung,' Rechnungsdatum ',DATE_FORMAT(v.rechnungsdatum,'%d.%m.%Y')) as bezeichnung - FROM verbindlichkeit AS v - LEFT JOIN adresse AS a ON a.id=v.adresse - WHERE ($subwhere) AND bezahlt!=1 AND status!='storniert' - ORDER by v.id DESC"; //AND v.status!='bezahlt' // heute wieder raus - - $arr = $this->app->DB->SelectArr($sql); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - - case "projektname": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(p.abkuerzung,' ',p.name) as name FROM projekt p WHERE p.geloescht=0 AND status <> 'abgeschlossen' AND (p.name LIKE '%$term%' OR p.name LIKE '%$term2%' OR p.name LIKE '%$term3%' OR p.abkuerzung LIKE '%$term%' OR p.abkuerzung LIKE '%$term2%' OR p.abkuerzung LIKE '%$term3%') ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - - case "uebertragung_account": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(u.id,' ',u.bezeichnung) as name FROM uebertragungen_account u WHERE (u.bezeichnung LIKE '%$term%') ".$this->app->erp->ProjektRechte('u.projekt')); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - break; - case "api_account": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(u.id,' ',u.bezeichnung) as name FROM api_account u WHERE (u.bezeichnung LIKE '%$term%') ".$this->app->erp->ProjektRechte('u.projekt')); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - break; - case "gruppen_kategorien": - $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.id,' ',g.bezeichnung) as name FROM gruppen_kategorien g - LEFT JOIN projekt p ON p.id=g.projekt WHERE (g.bezeichnung LIKE '%$term%' ) ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - case "gruppenkategoriegruppen": - $kategorie = (int)$this->app->Secure->GetGET('gkid'); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g - LEFT JOIN projekt p ON p.id=g.projekt WHERE kategorie = '$kategorie' AND (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - - break; - case 'steuersatz': - $newarr[] = $this->app->erp->Firmendaten('steuersatz_normal').' normal'; - $newarr[] = $this->app->erp->Firmendaten('steuersatz_ermaessigt').' ermaessigt'; - $newarr = array_merge($newarr, $this->app->DB->SelectFirstCols( - "SELECT concat( - `satz`,' ',`bezeichnung`, ' ',`country_code`, - IF(`type` != '', CONCAT(' ',`type`),''), - IF( - `valid_from` = '0000-00-00' OR `valid_from` IS NULL, - '', - CONCAT(' gültig ab: ',DATE_FORMAT(valid_from,'%d.%m.%Y')) - ), - IF( - `valid_to` = '0000-00-00' OR `valid_to` IS NULL, - '', - CONCAT(' gültig bis: ',DATE_FORMAT(valid_to,'%d.%m.%Y')) - ) - ) as `name` - FROM `steuersaetze` WHERE `aktiv` = 1 - AND concat( - `satz`,' ',`bezeichnung`,' ',`country_code`, - IF(`type` != '', CONCAT(' ',`type`),''), - IF( - `valid_from` = '0000-00-00' OR `valid_from` IS NULL, - '', - CONCAT(' gültig ab: ',DATE_FORMAT(valid_from,'%d.%m.%Y')) - ), - IF( - `valid_to` = '0000-00-00' OR `valid_to` IS NULL, - '', - CONCAT(' gültig bis: ',DATE_FORMAT(valid_to,'%d.%m.%Y')) - ) - ) LIKE '%$term%'" - )); - break; - case "eigenschaftname": - $arr = $this->app->DB->SelectArr("SELECT name FROM artikeleigenschaften WHERE geloescht != 1 AND name like '%$term%' ORDER BY name "); - if($arr) - { - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['name']; - } - break; - } - break; - case "eigenschaftwert": - $eigenschaftname = $this->app->DB->real_escape_string(urldecode($this->app->Secure->GetGET('eigenschaftname'))); - if($eigenschaftname !== '') - { - $arr = $this->app->DB->SelectArr("SELECT DISTINCT aw.wert FROM artikeleigenschaftenwerte aw - INNER JOIN artikeleigenschaften ae ON aw.artikeleigenschaften = ae.id AND ae.geloescht <> 1 - WHERE aw.wert like '%$term%' AND ae.name = '$eigenschaftname' ORDER BY aw.wert "); - }else{ - $arr = $this->app->DB->SelectArr("SELECT DISTINCT aw.wert FROM artikeleigenschaftenwerte aw - INNER JOIN artikeleigenschaften ae ON aw.artikeleigenschaften = ae.id AND ae.geloescht <> 1 - WHERE aw.wert like '%$term%' ORDER BY aw.wert"); - } - if($arr) - { - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) - $newarr[] = $arr[$i]['wert']; - break; - } - - - break; - case "angebot_position": - $angebot = $this->app->Secure->GetGET('angebot'); - $angebotposition = $this->app->Secure->GetGET('angebotposition'); - $arr = $this->app->DB->SelectArr("SELECT CONCAT(ap.sort,' ',ap.nummer) as bezeichnung FROM angebot_position ap INNER JOIN angebot a ON ap.angebot = a.id AND a.id = '$angebot' - LEFT JOIN projekt p ON p.id=a.projekt - WHERE (ap.sort LIKE '%$term%' OR ap.nummer LIKE '%$term%') AND ap.explodiert_parent = 0 AND ap.id <> '$angebotposition' ".$this->app->erp->ProjektRechte()); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - break; - case "supportapp_gruppen": - $suchbegriff = $this->app->DB->real_escape_string($this->app->Secure->GetGET('term')); - $suchbegriff = trim($suchbegriff); - $arr = $this->app->DB->SelectArr("SELECT bezeichnung FROM supportapp_gruppen WHERE aktiv = '1' AND bezeichnung LIKE '%$suchbegriff%'"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['bezeichnung']; - } - break; - break; - case "datevkonto": - $arr = $this->app->DB->SelectArr("SELECT DISTINCT t.gegenkonto FROM - ( (SELECT concat(datevkonto, ' ',bezeichnung) as gegenkonto FROM konten WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1) - UNION ALL (SELECT concat(sachkonto, ' ',beschriftung) as gegenkonto FROM kontorahmen WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1) - - ) t WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' ORDER BY t.gegenkonto"); - $carr = !empty($arr)?count($arr):0; - for($i=0;$i<$carr;$i++) { - $newarr[] = $arr[$i]['gegenkonto']; - } - break; - case 'gegenkonto': - - $kontorahmenArr = $this->app->DB->SelectPairs( - "SELECT concat(kr.sachkonto, ' ',kr.beschriftung) as a, kr.sachkonto - FROM kontorahmen as kr - WHERE kr.ausblenden <> 1" - ); - $subwhere = ' '; - if(!empty($kontorahmenArr)) { - $kontorahmenArr = array_unique(array_merge(array_keys($kontorahmenArr), array_values($kontorahmenArr))); - $subwhere = sprintf(" AND ka.gegenkonto NOT IN ('%s') ", implode("','", $kontorahmenArr)); - } - - $arr = $this->app->DB->SelectArr( - "SELECT DISTINCT t.gegenkonto - FROM - ( - ( - SELECT concat(ka.gegenkonto,' ',ka.name) as gegenkonto - FROM (SELECT ka2.gegenkonto,a.name - FROM kontoauszuege ka2 - INNER JOIN adresse a ON ka2.gegenkonto = a.kundennummer OR ka2.gegenkonto = a.lieferantennummer - WHERE ka2.gegenkonto <> '' - GROUP BY ka2.gegenkonto, a.name - ) AS ka - WHERE ka.gegenkonto <> '' $subwhere - ) - UNION ALL ( - SELECT concat(datevkonto, ' ',bezeichnung) - FROM konten - WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1 - AND concat(datevkonto, ' ',bezeichnung) LIKE '%$term%' - ) - UNION ALL ( - SELECT concat(sachkonto, ' ',beschriftung) - FROM kontorahmen - WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1 - AND concat(sachkonto, ' ',beschriftung) LIKE '%$term%' - ) - - ) t - WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' - ORDER BY t.gegenkonto" - ); - - - if($this->app->DB->error()){ - $arr = $this->app->DB->SelectArr( - "SELECT DISTINCT t.gegenkonto - FROM - ( - ( - SELECT concat(ka.gegenkonto,' ',( - SELECT a.name - FROM adresse a - WHERE (a.kundennummer=ka.gegenkonto OR a.lieferantennummer=ka.gegenkonto) AND ka.gegenkonto!='') - ) as gegenkonto - FROM kontoauszuege ka - LEFT JOIN kontorahmen kr - ON (ka.gegenkonto = kr.sachkonto OR ka.gegenkonto = concat(kr.sachkonto, ' ',kr.beschriftung)) - AND kr.ausblenden <> 1 - WHERE isnull(kr.id) AND ka.gegenkonto <> '' - GROUP BY ka.gegenkonto - ) - UNION ALL ( - SELECT concat(datevkonto, ' ',bezeichnung) - FROM konten - WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1 - AND concat(datevkonto, ' ',bezeichnung) LIKE '%$term%' - ) - UNION ALL ( - SELECT concat(sachkonto, ' ',beschriftung) - FROM kontorahmen - WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1 - AND concat(sachkonto, ' ',beschriftung) LIKE '%$term%' - ) - - ) t - WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' - ORDER BY t.gegenkonto" - ); - } - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['gegenkonto']; - } - break; - - break; - case 'versand_klaergrund': - $arr = $this->app->DB->SelectArr("SELECT DISTINCT problemcase FROM - delivery_problemcase WHERE problemcase LIKE '%$term%' ORDER BY sort, problemcase"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['problemcase']; - } - break; - case 'label_type': - $felder = array('type'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr("SELECT DISTINCT lt.type FROM label_type AS lt WHERE ($subwhere) ORDER BY type LIMIT 20"); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['type']; - } - break; - case 'versandartentype': - $felder = array('va.type'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr( - "SELECT DISTINCT va.type - FROM versandarten AS va - WHERE ($subwhere) AND va.geloescht <> 1 AND va.aktiv = 1 - ORDER BY va.type - LIMIT 20" - ); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['type']; - } - break; - case 'zahlungsweisetype': - $felder = array('va.type'); - $subwhere = $this->AjaxFilterWhere($termorig,$felder); - $arr = $this->app->DB->SelectArr( - "SELECT DISTINCT va.type - FROM zahlungsweisen AS va - WHERE ($subwhere) AND va.geloescht <> 1 AND va.aktiv = 1 - ORDER BY va.type - LIMIT 20" - ); - $carr = !empty($arr)?count($arr):0; - for($i = 0; $i < $carr; $i++) { - $newarr[] = $arr[$i]['type']; - } - break; - case 'ticketcategory': - $newarr = $this->app->DB->SelectFirstCols( - sprintf( - "SELECT CONCAT(`id`,' ',`name`) FROM `ticket_category` WHERE (`name` LIKE '%%%s%%' OR `name` LIKE '%%%s%%') %s", - $term, $term2, $this->app->erp->ProjektRechte('project_id') - ) - ); - break; - case 'shopimport_auftraege': - $shopId = $this->app->Secure->GetGET('id'); - $newarr = $this->app->DB->SelectFirstCols( - sprintf( - "SELECT CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) - FROM `shopimport_auftraege` AS `sa` - WHERE ( - CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) LIKE '%%%s%%' - OR CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) LIKE '%%%s%%' - ) AND (%d = 0 OR %d = sa.shopid) %s", - $term, $term2, $shopId, $shopId, $this->app->erp->ProjektRechte('sa.projekt') - ) - ); - - break; - default: - $newarr = null; - $this->app->erp->RunHook('ajax_filter_hook1', 5,$filtername,$newarr, $term, $term2, $term3); - } - - $tmp = null; - //if(isset($this->app->stringcleaner) && false) - if(false) - { - $cnewarr = $newarr?count($newarr):0; - for($i=0;$i<$cnewarr;$i++){ - $tmp[] = $this->app->erp->ClearDataBeforeOutput($this->app->stringcleaner->CleanString(html_entity_decode( $this->app->stringcleaner->CleanString($newarr[$i], 'nojs'), ENT_QUOTES, 'UTF-8'), 'nojs')); - } - }else{ - $cnewarr = !empty($newarr)?count($newarr):0; - for($i=0;$i<$cnewarr;$i++) { - $tmp[] = $this->app->erp->ClearDataBeforeOutput(html_entity_decode($newarr[$i], ENT_QUOTES, 'UTF-8')); - } - } - - if(!empty($isChangeLtGt)){ - $ctmp = !empty($tmp)?count($tmp):0; - for($i=0;$i<$ctmp;$i++){ - $tmp[$i] = str_replace('-gtrep-','>',str_replace('-ltrep-','<',$tmp[$i])); - } - } - - echo json_encode($tmp); - $this->app->erp->ExitWawi(); - } - - public function AjaxTablePosition() - { - - $iDisplayStart = $this->app->Secure->GetGET('iDisplayStart'); - $iDisplayLength = $this->app->Secure->GetGET('iDisplayLength'); - $iSortCol_0 = $this->app->Secure->GetGET('iSortCol_0'); - $iSortingCols = $this->app->Secure->GetGET('iSortingCols'); - $sSearch = $this->app->Secure->GetGET('sSearch'); - $sEcho = $this->app->Secure->GetGET('sEcho'); - $cmd = $this->app->Secure->GetGET('cmd'); - - - $sLimit = ''; - if ( isset($iDisplayStart) ) - { - - $sLimit = 'LIMIT '. (int)$iDisplayStart .', '. - (int)$iDisplayLength ; - } - - /* Ordering */ - if ( isset( $iSortCol_0 ) ) - { - $sOrder = 'ORDER BY '; - $ciSortingCols = (int)$iSortingCols; - for ( $i=0 ; $i<$ciSortingCols ; $i++ ) - { - $iSortingCols_tmp = $this->app->Secure->GetGET('iSortCol_'.$i); - $sSortDir_tmp = $this->app->Secure->GetGET('sSortDir_'.$i); - - $sOrder .= $this->fnColumnToFieldPosition($iSortingCols_tmp ).' - '. $sSortDir_tmp .', '; - } - $sOrder = substr_replace( $sOrder, '', -2 ); - } - - /* Filtering - NOTE this does not match the built-in DataTables filtering which does it - * word by word on any field. It's possible to do here, but concerned about efficiency - * on very large tables, and MySQL's regex functionality is very limited - */ - - - $sWhere = ''; - $where = $this->app->YUI->TablePositionSearch('',$cmd,'where'); - if ( $sSearch != '' ) - { - $searchsql = $this->app->YUI->TablePositionSearch('',$cmd,'searchsql'); - - if($where==''){ - $sWhere = ' WHERE ('; - } - else - { - if(!empty($searchsql) && count($searchsql) >0){ - $sWhere = " WHERE $where AND ("; - } - else{ - $sWhere = " WHERE $where "; - } - } - - - for($i=0;$iapp->DB->real_escape_string($sSearch )."%' OR "; - } - $sWhere .= $searchsql[$i]." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%')"; - - - } else { - if($where!=''){ - $sWhere = " WHERE $where "; - } - } - - - $searchfulltext = $this->app->YUI->TablePositionSearch('',$cmd,'searchfulltext'); - if($searchfulltext!='' && $sSearch!='') - { - $searchfulltext = ' MATCH('.$searchfulltext.") AGAINST ('$sSearch') "; - if($sWhere==''){ - $sWhere = " WHERE $searchfulltext "; - } - else{ - $sWhere .= "AND $searchfulltext "; - } - } - $tmp = $this->app->YUI->TablePositionSearch('',$cmd,'sql'); - - - $sQuery = " - $tmp - $sWhere - $sOrder - $sLimit - "; - - - $rResult = $this->app->DB->Query($sQuery); - - - - $sQuery = ' - SELECT FOUND_ROWS() - '; - $rResultFilterTotal = $this->app->DB->Query($sQuery); - if(!empty($rResultFilterTotal)){ - $aResultFilterTotal = $this->app->DB->Fetch_Array($rResultFilterTotal); - $this->app->DB->free($rResultFilterTotal); - $iFilteredTotal = $aResultFilterTotal[0]; - }else{ - $aResultFilterTotal = 0; - $iFilteredTotal = 0; - } - - /* - $sQuery = " - SELECT COUNT(id) - FROM artikel - "; - */ - $sQuery = $this->app->YUI->TablePositionSearch('',$cmd,'count'); - $rResultTotal = $this->app->DB->Query($sQuery); - $aResultTotal = $this->app->DB->Fetch_Array($rResultTotal); - $this->app->DB->free($rResultTotal); - $iTotal = $aResultTotal[0]; - - - $heading = count($this->app->YUI->TablePositionSearch('',$cmd,'heading')); - $menu = $this->app->YUI->TablePositionSearch('',$cmd,'menu'); - - $sOutput = '{'; - $sOutput .= '"sEcho": '.(int)$sEcho.', '; - $sOutput .= '"iTotalRecords": '.$iTotal.', '; - $sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', '; - $sOutput .= '"aaData": [ '; - if($rResult){ - while ($aRow = $this->app->DB->Fetch_Row($rResult)) { - $sOutput .= '['; - for ($i = 1; $i < $heading; $i++) { - $sOutput .= '"' . addslashes($aRow[$i]) . '",'; - } - - $sOutput .= '"' . addslashes(str_replace('%value%', $aRow[$i], $menu)) . '"'; - - $sOutput .= '],'; - - } - $this->app->DB->free($rResult); - } - $sOutput = substr_replace( $sOutput, '', -1 ); - $sOutput .= '] }'; - - $sOutput = str_replace("\t",'',$sOutput); - - echo json_encode(json_decode($this->app->erp->ClearDataBeforeOutput($sOutput))); - $this->app->erp->ExitWawi(); - } - - protected function AjaxTableWhereBuilder($spalte, $sSearch, $datecol = false, $numbercol = false) - { - $sSearch = str_replace('%','%',$sSearch); - $sSearcha = explode(' ', $sSearch); - $sSearch = str_replace(' ','%',$sSearch); - - - if($spalte == 'datum' || $datecol) - { - return ' ( DATE_FORMAT('.$spalte.",'%d.%m.%Y %H:%i:%s') LIKE '%".$this->app->DB->real_escape_string($sSearch )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; - } - if(strpos($spalte, 'datum')) { - $spaltea = explode('.', $spalte); - if(count($spaltea) === 2){ - return ' ( DATE_FORMAT('.$spalte.",'%d.%m.%Y %H:%i:%s') LIKE '%".$this->app->DB->real_escape_string($sSearch )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; - } - }elseif(($numbercol || $spalte === 'soll' || $spalte === 'gesamtsumme') && strpos($sSearch,',')) - { - return ' ( '.$spalte." LIKE '%".$this->app->DB->real_escape_string(str_replace(',','.',$sSearch) )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; - }elseif((strpos($spalte, 'soll') || strpos($spalte, 'gesamtsumme')) && strpos($sSearch,',')) - { - $spaltea = explode('.', $spalte); - if(count($spaltea) === 2){ - return ' ( '.$spalte." LIKE '%".$this->app->DB->real_escape_string(str_replace(',','.',$sSearch) )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; - } - } - if(count($sSearcha) > 1) - { - return ' ('.$this->AjaxTableWhereBuilderArray($spalte, $sSearcha).')'; - } - return ' ('.$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%')"; - } - - protected function AjaxTableWhereBuilderArray($column, $sSearcha, $sSearcha2 = null) - { - if(empty($column) || empty($sSearcha)) - { - return ''; - } - $csSearcha = count($sSearcha); - $tmp = []; - foreach($sSearcha as $v) - { - $tmp[strtolower($v)] = 1+(!empty($tmp[strtolower($v)])?$tmp[strtolower($v)]:0); - } - if(count($tmp) === 1) - { - $sSearch = implode('%', $sSearcha); - - $sSearch2 = $this->app->erp->ConvertForTableSearch($sSearch); - if($sSearch2 === '') - { - $sWhere = "({$column} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; - }else{ - $sWhere = "({$column} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR - {$column} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; - } - return $sWhere; - } - - if(!empty($sSearcha2)) - { - $wherea = []; - foreach($tmp as $v => $c) { - if($c > 1) - { - $vold = $v; - for($i = 1; $i < $c; $i++) - { - $v .= '%'.$vold; - } - } - $vt = $this->app->erp->ConvertForTableSearch($v); - if($vt === '' || $vt === $v) - { - $vt = $this->app->erp->ConvertForDBUTF8($v); - } - if($v === '') - { - $v = $vt; - } - if($v !== $vt && $vt !== ''){ - $wherea[] = ' (' . $column . " LIKE '%" . $v . "%' OR " . $column . " LIKE '%" . $vt . "%') "; - }else{ - - $wherea[] = ' (' . $column . " LIKE '%" . $v . "%') "; - } - } - return '('.implode(' AND ',$wherea).')'; - }else{ - $wherea = []; - foreach($tmp as $v => $c) { - if($c > 1) - { - $vold = $v; - for($i = 1; $i < $c; $i++) - { - $v .= '%'.$vold; - } - } - $wherea[] = $column." LIKE '%".$v."%'"; - } - return '('.implode(' AND ',$wherea).')'; - } - } - - - - public function AjaxTable() - { - $iDisplayStart = $this->app->Secure->GetGET('iDisplayStart'); - $iDisplayLength = $this->app->Secure->GetGET('iDisplayLength'); - $iSortCol_0 = $this->app->Secure->GetGET('iSortCol_0'); - $sSortDir_0 = $this->app->Secure->GetGET('sSortDir_0'); - $iSortingCols = $this->app->Secure->GetGET('iSortingCols'); - $sSearch = $this->app->Secure->GetGET('sSearch'); - $sEcho = $this->app->Secure->GetGET('sEcho'); - $cmd = $this->app->Secure->GetGET('cmd'); - $frommodule = $this->app->Secure->GetGET('frommodule'); - $fromclass = $this->app->Secure->GetGET('fromclass'); - $sSearch = trim($sSearch); - $sSearch = str_replace('%','\%',$sSearch); - - $sSearch2 = $sSearch; - $sSearch3 = $this->app->erp->ConvertForDB($sSearch); - $sSearch = $this->app->erp->ConvertForDBUTF8($sSearch); - if($this->app->Secure->GetGet('deferLoading')){ - echo '{"sEcho":'.(int)$sEcho.',"iTotalRecords":0,"iTotalDisplayRecords":0,"aaData":[]}'; - $this->app->ExitXentral(); - } - - - $YUIs = $this->app->YUI->TableSearch('',$cmd,'ALL','','',$frommodule, $fromclass); - $starttime = microtime(true); - $limiert = false; - if(method_exists($this->app->erp, 'BegrenzungLivetabelle')) - { - $limiert = 2*$this->app->erp->BegrenzungLivetabelle($cmd, $this->app->DB->real_escape_string( $iDisplayLength )); - } - $maxrows = 0; - if(isset($YUIs['maxrows']) && $YUIs['maxrows'] > 0) - { - $maxrows = $YUIs['maxrows']; - } - $sLimit = ''; - if($limiert) - { - $limiert += (int) $iDisplayStart ; - $iDisplayLength = $iDisplayLength ; - if(($maxrows > 0) && $iDisplayLength > $maxrows){ - $iDisplayLength = $maxrows; - } - $sLimit = 'LIMIT '. $iDisplayStart .', '. ( $limiert ); - }else{ - if ( isset($iDisplayStart) ) - { - $iDisplayLength = $iDisplayLength ; - if(($maxrows > 0) && $iDisplayLength > $maxrows) - { - $iDisplayLength = $maxrows; - } - $sLimit = 'LIMIT '. $iDisplayStart .', '. $iDisplayLength ; - } - } - /* Ordering */ - - // check if is allowed - if(!$this->app->erp->TableSearchAllowed($cmd)) - { - $this->app->erp->Protokoll("Nicht erlaubter Zugriff auf $cmd von Benutzer ".$this->app->User->GetName()); - $this->app->erp->ExitWawi(); - } - - - - //$findcolstmp = $this->app->YUI->TableSearch("",$cmd,"findcols","","",$frommodule, $fromclass); - $findcolstmp = $YUIs['findcols']; - //$moreinfo = $this->app->YUI->TableSearch("",$cmd,"moreinfo","","",$frommodule, $fromclass); - $moreinfo = $YUIs['moreinfo']; - - if (isset($iSortCol_0) || ($moreinfo && $iSortCol_0 < 1)) - { - if($moreinfo){ - if(!($iSortCol_0 < 1)){ - $iSortCol_0++; - } - }else{ - $iSortCol_0++; - - } - if($iSortCol_0 < 1){ - $iSortCol_0 = 1; - } - - if(trim($findcolstmp[$iSortCol_0 - 1]) == 'belegnr' || - strpos($findcolstmp[$iSortCol_0 - 1], '.belegnr') !== false){ - if(preg_match_all('/([a-zA-Z0-9]*)(\.*)belegnr/', $findcolstmp[$iSortCol_0 - 1], $ergebnis)){ - if(isset($ergebnis[1][0]) && !isset($ergebnis[1][1])){ - $findcolstmp[$iSortCol_0 - 1] = $this->app->erp->BelegnummerSortierung($ergebnis[1][0]); - } - } - } - - $sOrder = 'ORDER BY ' . $findcolstmp[$iSortCol_0 - 1] . " $sSortDir_0"; - } - else - { - //standard einstellung nach datum absteigend wenn datumsspalte vorhanden - //$defaultorder = $this->app->YUI->TableSearch("",$cmd,"defaultorder","","",$frommodule, $fromclass); - $defaultorder = $YUIs['defaultorder']; - //$defaultorderdesc = $this->app->YUI->TableSearch("",$cmd,"defaultorderdesc","","",$frommodule, $fromclass); - $defaultorderdesc = $YUIs['defaultorderdesc']; - if($defaultorder<=0) { - $defaultorder = count($findcolstmp); - $defaultorderdesc = 1; - } - - if($defaultorderdesc=='1') { - $defaultorderdesc = ' DESC'; - } else { - $defaultorderdesc=''; - } - - - if($defaultorder >=0 && is_numeric($defaultorder)) - { - $defaultorder++; - //$findcolstmp = $this->app->YUI->TableSearch("",$cmd,"findcols","","",$frommodule, $fromclass); - $findcolstmp = $YUIs['findcols']; - if($defaultorder < 2) - { - $defaultorder = 2; - } - $sOrder = 'ORDER BY '.$findcolstmp[$defaultorder-2]." $defaultorderdesc"; - }else - { - $sOrder = 'ORDER BY '.$findcolstmp[0]." $defaultorderdesc"; - } - } - - - /* Filtering - NOTE this does not match the built-in DataTables filtering which does it - * word by word on any field. It's possible to do here, but concerned about efficiency - * on very large tables, and MySQL's regex functionality is very limited - */ - - $sWhere = ''; - //$where = $this->app->YUI->TableSearch("",$cmd,"where","","",$frommodule, $fromclass); - $where = $YUIs['where']; - //echo $where; - - $matchesql = !empty($YUIs['matchesql'])?$YUIs['matchesql']:''; - - if ($sSearch != '' && !empty($matchesql) && !empty($matchesql['sqlpre'])) - { - while(strpos($sSearch,' ') !== false) - { - $sSearch = str_replace(' ',' ', $sSearch); - } - while(strpos($sSearch2,' ') !== false) - { - $sSearch2 = str_replace(' ',' ', $sSearch2); - } - $sSearch = str_replace('%','%',$sSearch); - $sSearch2 = str_replace('%','%',$sSearch2); - $sSearcha = explode(' ', $sSearch); - $sSearcha2 = explode(' ', $sSearch2); - $sSearch = str_replace(' ','%',$sSearch); - $sSearch2 = str_replace(' ','%',$sSearch2); - $YUIs['sql'] = $matchesql['sqlpre']; - $unions = []; - foreach($matchesql['elements'] as $keyEl => $SqlElement) - { - $SqlElementQuery = $SqlElement['sql'].' WHERE '; - $whereArr = []; - $firstsubwhere = true; - if(!empty($SqlElement['where'])) - { - foreach($SqlElement['where'] as $keyWhere => $valWhere) - { - if(!$firstsubwhere) - { - $SqlElementQuery .= ' OR '; - } - if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) - { - if(count($sSearcha) > 1) - { - $SqlElementQuery .= $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha, $sSearcha2); - }else{ - $SqlElementQuery .= "({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR - {$valWhere} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; - } - }else{ - if(count($sSearcha) > 1) - { - $SqlElementQuery .= $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha); - }else{ - $SqlElementQuery .= "({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; - } - } - if($sSearch2!='' && ($sSearch2 !== $sSearch)) - { - if($this->app->DB->real_escape_string( $sSearch2 ) !== $this->app->erp->ConvertForTableSearch( $sSearch2 )) - { - $SqlElementQuery .=" OR ({$valWhere} LIKE '%".$this->app->DB->real_escape_string( $sSearch2 )."%' OR {$valWhere} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch2 )."%' ) "; - }else{ - if(count($sSearcha) > 1) - { - $SqlElementQuery .= ' OR ('. $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha2).') '; - }else{ - $SqlElementQuery .= " OR ({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch2) . "%') "; - } - } - } - $firstsubwhere = false; - } - } - if(!empty($SqlElement['match'])) - { - if(!$firstsubwhere) - { - $SqlElementQuery .= ' OR '; - } - $sSearchArr = explode('%', str_replace(['+','-','*','~'],['%','','%','%'], $sSearch)); - foreach($sSearchArr as $keyS => $keyv) - { - if(strlen($keyv) === 0) - { - unset($sSearchArr[$keyS]); - } - } - - $sSearchMatch = ''; - foreach ($sSearchArr as $sSearchItem) { - // $sSearchItem enthält einzelne Wörter evtl. mit HTML-Entities - // Problem 1: Das Ampersand-Zeichen der HTML-Entities wird im BOOLEAN MODE als Worttrenner gesehen. - // Problem 2: Das Ampersand-Zeichen kann im BOOLEAN MODE nicht escaped werden. - // Die einzige Lösung ist das Suchwort mit doppelten Anführungszeichen zu umschließen, - // die Worttrenner-Eigenschaft des Ampersandzeichens wird damit aufgehoben. - // Der Nachteil bei dieser Lösung: Es werden nur noch ganze Wörter gefunden. - $sSearchMatch .= sprintf('+%s* ', $this->app->DB->real_escape_string($sSearchItem)); - } - $SqlElementQuery .= ' MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$sSearchMatch.'\' IN BOOLEAN MODE) '; - if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) - { - $SqlElementQuery .= ' OR MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$this->app->erp->ConvertForTableSearch($sSearchMatch).'\' IN BOOLEAN MODE) '; - } - elseif(!empty($sSearch2) && $sSearch2 !== $sSearch) { - $sSearchArr2 = explode('%', str_replace(['+','-','*','~'],['%','','%','%'], $sSearch2)); - foreach($sSearchArr2 as $keyS => $keyv) - { - if(strlen($keyv) === 0) { - unset($sSearchArr2[$keyS]); - } - } - $sSearchMatch2 = '+'.implode('* +', $sSearchArr2).'*'; - $SqlElementQuery .= ' OR MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$this->app->DB->real_escape_string($sSearchMatch2).'\' IN BOOLEAN MODE) '; - } - } - $SqlElementQuery .= implode(' OR ', $whereArr); - $unions[] = $SqlElementQuery; - } - $YUIs['sql'] .= implode(' - UNION - ', $unions); - $YUIs['sql'] .= $matchesql['sqlpost']; - - if($where!=''){ - $sWhere = " WHERE $where "; - } - } - elseif ( $sSearch != '' ) { - /* - $sWhere = "WHERE a.nummer LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%' OR ". - "p.abkuerzung LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%' OR ". - "a.name_de LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; - */ - //$searchsql = $this->app->YUI->TableSearch("",$cmd,"searchsql","","",$frommodule, $fromclass); - $searchsql = $YUIs['searchsql']; - $searchsql2 = null; - $datesearchcol2 = null; - $datesearchcol = $YUIs['datesearchsols']; - if(is_array($searchsql)) - { - foreach($searchsql as $k => $v) - { - if(is_array($v)) - { - foreach($v as $k2 => $v2) - { - $searchsql2[] = $v2; - if($datesearchcol && in_array($k, $datesearchcol)) { - $datesearchcol2[] = count($searchsql2)-1; - } - } - }else{ - $searchsql2[] = $v; - if($datesearchcol && in_array($k, $datesearchcol)) - { - $datesearchcol2[] = count($searchsql2)-1; - } - } - } - } - if($where==''){ - $sWhere = ' WHERE ('; - } - else - { - if(count($searchsql) > 0){ - $sWhere = " WHERE $where AND ("; - } - else{ - $sWhere = " WHERE $where "; - } - } - - // Prozent austauschen da dies mysql wildcat ist - - while(strpos($sSearch,' ') !== false) - { - $sSearch = str_replace(' ',' ', $sSearch); - } - while(strpos($sSearch2,' ') !== false) - { - $sSearch2 = str_replace(' ',' ', $sSearch2); - } - - $sSearch = str_replace('%','%',$sSearch); - $sSearch2 = str_replace('%','%',$sSearch2); - - //$sSearch3 = str_replace('%','%',$sSearch3); - //$sSearch3 = str_replace(' ','%',$sSearch3); - - $sSearcha = explode(' ', $sSearch); - $sSearcha2 = explode(' ', $sSearch2); - //$sSearcha = []; - //$sSearcha2 = []; - - $sSearch = str_replace(' ','%',$sSearch); - $sSearch2 = str_replace(' ','%',$sSearch2); - - - $csearchsql2 = $searchsql2?count($searchsql2):0; - for($i=0;$i<$csearchsql2;$i++) - { - if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) - { - if($datesearchcol2 && in_array($i, $datesearchcol2)) - { - $sWhere .= '('.$this->AjaxTableWhereBuilder($searchsql2[$i], $sSearch, true, false).' OR '.$this->AjaxTableWhereBuilder($searchsql2[$i], $this->app->erp->ConvertForTableSearch( $sSearch ), true, false).")"; - }else{ - if(count($sSearcha) > 1) - { - $sWhere .= $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha, $sSearcha2); - }else{ - $sWhere .= "({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR - {$searchsql2[$i]} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; - } - } - }else{ - if($datesearchcol2 && in_array($i, $datesearchcol2)) { - $sWhere .= $this->AjaxTableWhereBuilder($searchsql2[$i], $sSearch, true, false); - }else{ - if(count($sSearcha) > 1) - { - $sWhere .= $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha); - }else{ - $sWhere .= "({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; - } - } - } - - - if($sSearch2!='' && ($sSearch2 !== $sSearch)) - { - if($this->app->DB->real_escape_string( $sSearch2 ) !== $this->app->erp->ConvertForTableSearch( $sSearch2 )) - { - $sWhere .=" OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch2 )."%' OR {$searchsql2[$i]} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch2 )."%' ) "; - }else{ - if(count($sSearcha) > 1) - { - $sWhere .= ' OR ('. $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha2).') '; - }else{ - $sWhere .= " OR ({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch2) . "%') "; - } - } - } - - if($sSearch3!='' && ($sSearch3 !== $sSearch || $sSearch3 !== $sSearch2)) - { - if($this->app->DB->real_escape_string( $sSearch3 ) !== $this->app->erp->ConvertForTableSearch( $sSearch3 )) - { - $sWhere .= "OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch3 )."%' OR {$searchsql2[$i]} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch3 )."%' ) OR "; - }else{ - $sWhere .= "OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch3 )."%') OR "; - } - } - else { - $sWhere .= ' OR '; - } - } - - //$searchfulltext = $this->app->YUI->TableSearch("",$cmd,"searchfulltext","","",$frommodule, $fromclass); - $searchfulltext = $YUIs['searchfulltext']; - if($searchfulltext!='' && $sSearch!='') - { - $sSearch = str_replace('"','"',$sSearch); - $sSearch .= '*'; - $searchfulltext = ' MATCH(e.subject,e.sender,e.action,e.action_html) AGAINST (\''.$this->app->erp->ConvertForTableSearch($sSearch).'\' IN BOOLEAN MODE ) '; - } - if(count($searchsql2) > 0){ - if($searchfulltext == '') - { - $sWhere .= ' 0)'; - }else{ - $sWhere .= ' '.$searchfulltext.')'; - /*$i--; - if($searchfulltext != ''){ - $searchfulltext = ' OR ' . $searchfulltext; - } - if($this->app->DB->real_escape_string($sSearch) !== $this->app->erp->ConvertForTableSearch($sSearch)){ - $sWhere .= "( {$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR {$searchsql2[$i]} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%') $searchfulltext )"; - }else{ - $sWhere .= "( {$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') $searchfulltext )"; - }*/ - } - } else { - $sWhere .= " AND $searchfulltext"; - } - - } else { - if($where!=''){ - $sWhere = " WHERE $where "; - } - } - - - //$searchsql = $this->app->YUI->TableSearch("",$cmd,"searchsql","","",$frommodule, $fromclass); - $searchsql = $YUIs['searchsql']; - - //$moreinfo = $this->app->YUI->TableSearch("",$cmd,"moreinfo","","",$frommodule, $fromclass); - $moreinfo = $YUIs['moreinfo']; - if($moreinfo) { - $offset = 1; - } else { - $offset=0; - } - if(!$YUIs['columnfilter']) - { - $searchsql = $YUIs['findcols']; - $offset = 0; - } - $csearchsql = $searchsql?count($searchsql):0; - for($isearch=0;$isearch<$csearchsql;$isearch++) - { - $sSearch = $this->app->Secure->GetGET('sSearch_'.$isearch); - if($sSearch!='' && $sSearch!='A') - { - if(isset($searchsql[$isearch-$offset]) && is_array($searchsql[$isearch-$offset])) - { - $gef = false; - foreach($searchsql[$isearch-$offset] as $v) - { - if($v != '') - { - if($sWhere == '') - { - //$sWhere = "WHERE (".$v." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; - $sWhere = 'WHERE ('.$this->AjaxTableWhereBuilder($v, $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); - $gef = true; - }else{ - $sWhere = "$sWhere "; - if(!$gef) - { - $sWhere .= ' AND ('; - }else{ - $sWhere .= ' OR '; - } - //$sWhere .= " (".$v." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%')"; - $sWhere .= $this->AjaxTableWhereBuilder($v, $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); - $gef = true; - } - } - } - if($gef){ - $sWhere .= ' ) '; - } - }else{ - if($sWhere=='') - { - if($searchsql[$isearch-$offset]!='') - { - //$sWhere = "WHERE ".$searchsql[$isearch-$offset]." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; - $sWhere = 'WHERE '.$this->AjaxTableWhereBuilder($searchsql[$isearch-$offset], $sSearch ,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); - } - } - else - { - if($searchsql[$isearch-$offset]!='') - { - //$sWhere = "$sWhere AND (".$searchsql[$isearch-$offset]." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%')"; - $sWhere = "$sWhere AND (".$this->AjaxTableWhereBuilder($searchsql[$isearch-$offset], $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ).")"; - } - } - } - } - } - - - - //$tmp = $this->app->YUI->TableSearch("",$cmd,"sql","","",$frommodule, $fromclass); - $tmp = $YUIs['sql']; - //$groupby = $this->app->YUI->TableSearch("",$cmd,"groupby","","",$frommodule, $fromclass); - $groupby = $YUIs['groupby']; - //$orderby = $this->app->YUI->TableSearch("",$cmd,"orderby","","",$frommodule, $fromclass); - $orderby = $YUIs['orderby']; - - $fastcount = isset($YUIs['fastcount'])?$YUIs['fastcount']:''; - if($orderby){ - $sOrder = $orderby; - } - $uid = $this->app->Secure->GetGET('uid'); - $pid = $this->app->User->GetParameter('tablesearch_'.$uid); - if(!empty($pid)) { - $pid = explode('|',$pid); - $sEchoCheck = !empty($pid[1])?(int)$pid[1]:0; - $pid = reset($pid); - if($sEchoCheck < $sEcho && $pid != $this->app->DB->connection->thread_id){ - $this->app->DB->kill($pid); - } - $this->app->User->deleteParameter('tablesearch_'.$uid); - } - //$sQuery = $sWhere." ".$sOrder." ". $sLimit; - - //$rResult = $this->app->DB->Query( $sQuery); - $sQuery = " - $tmp - $sWhere - $groupby - $sOrder - $sLimit - "; - if($fastcount || $limiert){ - $sQuery = str_replace('SQL_CALC_FOUND_ROWS','',$sQuery); - } - - $jsarray = null; - if(isset($this->app->stringcleaner)) { - $jsarray = $this->app->stringcleaner->CheckSQLHtml($sQuery); - } - if($this->app->erp->Firmendaten('schnellsuchecount') && strpos($sQuery, 'SQL_CALC_FOUND_ROWS')){ - $YUIs['count'] = ''; - } - - if(isset($YUIs['onequeryperuser']) && $YUIs['onequeryperuser']) { - $killId = $this->app->User->GetParameter('tablesearch_'.$cmd.'_id2'); - $killId = explode('|',$killId); - $sEchoCheck = !empty($killId[1])?(int)$killId[1]:0; - $killId = reset($killId); - if(!empty($killId) && $sEchoCheck < $sEcho) { - $this->app->DB->kill($killId); - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); - } - $killId = $this->app->User->GetParameter('tablesearch_'.$cmd.'_id'); - $killId = explode('|',$killId); - $sEchoCheck = !empty($killId[1])?(int)$killId[1]:0; - $killId = reset($killId); - if(!empty($killId) && $sEchoCheck < $sEcho) { - $this->app->DB->kill($killId); - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); - } - //TODO Alte Prozesse killen - $_sql = substr($this->app->YUI->CodiereSQLForOneQuery($tmp, $cmd),0, 100); - $processlist = $this->app->DB->SelectArr('SHOW PROCESSLIST'); - if(count($processlist) > 1) { - foreach($processlist as $v) { - if($v['Time'] > 1 && $v['db'] == $this->app->Conf->WFdbname && $v['User'] == $this->app->Conf->WFdbuser && substr($v['Info'], 0, 100) == $_sql) { - $this->app->DB->kill($v['Id']); - } - } - } - $this->app->User->SetParameter('tablesearch_'.$cmd.'_id', $this->app->DB->connection->thread_id); - } - $maxExecutionTime = 300; - if($cmd === 'report_table') { - $maxExecutionTime = 30; - } - $useasync = function_exists('mysqli_poll'); - if($useasync) { - ignore_user_abort(true); - $db2 = $this->app->DB->getClone(); - $threadid = $db2->connection->thread_id; - $this->app->User->SetParameter('tablesearch_'.$uid, $threadid.'|'.$sEcho); - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); - } - - $startExecutionTime = microtime(true); - $rResult = $db2->Query($sQuery, true); - $all_links = array($db2->connection); - $processed = 0; - do { - echo ' '; - flush(); - ob_flush(); - if(connection_aborted() == 1 - || ($maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) - ) { - $this->app->DB->kill($threadid); - if((int)$this->app->User->GetParameter('tablesearch_'.$uid) == $threadid) { - $this->app->User->deleteParameter('tablesearch_'.$uid); - } - exit; - } - $links = $errors = $reject = array(); - foreach ($all_links as $link) { - $links[] = $errors[] = $reject[] = $link; - } - if (!mysqli_poll($links, $errors, $reject, 0,50000)) { - continue; - } - foreach ($links as $link) { - if ($rResult = $link->reap_async_query()) { - break 2; - }; - $processed++; - } - } while ($processed < count($all_links)); - } - else{ - $rResult = $this->app->DB->Query($sQuery); - } - if($cmd === 'adresse_brief' && $this->app->DB->error() && strpos($this->app->DB->error(), 'COLLATION \'utf8_general_ci\' is not valid for CHARACTER') !== false) - { - if((String)$this->app->erp->GetKonfiguration('adresse_crm_collateerror') === ''){ - $this->app->erp->SetKonfigurationValue('adresse_crm_collateerror', 1); - } - }elseif($cmd === 'adresse_brief' && $this->app->DB->error() && $this->app->erp->GetKonfiguration('adresse_crm_collateerror')) - { - $this->app->erp->SetKonfigurationValue('adresse_crm_collateerror', 0); - } - - $iTotal = 0; - if(!$limiert) { - if($fastcount) { - $sQuery = "$fastcount $sWhere"; - if($useasync) { - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); - } - $startExecutionTime = microtime(true); - $rResultFilterTotal = $db2->Query($sQuery, true); - $threadid = $db2->connection->thread_id; - $all_links = array($db2->connection); - $processed = 0; - do { - echo ' '; - flush(); - ob_flush(); - if(connection_aborted() == 1 || ( - $maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) - ){ - $this->app->DB->kill($threadid); - exit; - } - $links = $errors = $reject = array(); - foreach ($all_links as $link) { - $links[] = $errors[] = $reject[] = $link; - } - if(!mysqli_poll($links, $errors, $reject, 0, 50000)){ - continue; - } - foreach ($links as $link) { - if($rResultFilterTotal = $link->reap_async_query()){ - break 2; - }; - $processed++; - } - } while ($processed < count($all_links)); - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); - } - } - else { - $rResultFilterTotal = $this->app->DB->Query($sQuery); - } - $aResultFilterTotal = $this->app->DB->Fetch_Row($rResultFilterTotal); - $this->app->DB->free($rResultFilterTotal); - $iFilteredTotal = $aResultFilterTotal[0]; - } - else { - $sQuery = ' - SELECT FOUND_ROWS() - '; - if($useasync) { - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); - } - $startExecutionTime = microtime(true); - $rResultFilterTotal = $db2->Query($sQuery, true); - $threadid = $db2->connection->thread_id; - $all_links = array($db2->connection); - $processed = 0; - do { - echo ' '; - flush(); - ob_flush(); - if(connection_aborted() == 1 || ( - $maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) - ) { - $this->app->DB->kill($threadid); - exit; - } - $links = $errors = $reject = array(); - foreach ($all_links as $link) { - $links[] = $errors[] = $reject[] = $link; - } - if(!mysqli_poll($links, $errors, $reject, 0, 50000)){ - continue; - } - foreach ($links as $link) { - if($rResultFilterTotal = $link->reap_async_query()){ - break 2; - }; - $processed++; - } - } while ($processed < count($all_links)); - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); - } - } - else { - $rResultFilterTotal = $this->app->DB->Query($sQuery); - } - $aResultFilterTotal = $this->app->DB->Fetch_Row($rResultFilterTotal); - $this->app->DB->free($rResultFilterTotal); - $iFilteredTotal = $aResultFilterTotal[0]; - } - } - if($useasync) { - echo ' '; - flush(); - ob_flush(); - if(connection_aborted() == 1) { - if(!empty($db2)) { - $db2->Close(); - } - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); - } - $this->app->DB->Close(); - exit; - } - } - /* - $sQuery = " - SELECT COUNT(id) - FROM artikel - "; - */ - //$sQuery = $this->app->YUI->TableSearch("",$cmd,"count","","",$frommodule, $fromclass); - if(!$limiert){ - $sQuery = $YUIs['count']; - if((String)$sQuery !== '') { - $rResultTotal = $this->app->DB->Query( $sQuery); - - $aResultTotal = $this->app->DB->Fetch_Array($rResultTotal); - $this->app->DB->free($rResultTotal); - $iTotal = (int)$aResultTotal[0]; - } - else { - $iTotal = !empty($iFilteredTotal)?(int)$iFilteredTotal:0; - } - $this->app->erp->CheckBegrenzungLiveTabelle($cmd, $iTotal, microtime(true)-$starttime); - } - elseif(!empty($YUIs['cached_count'])) { - $aResultTotal = $this->app->DB->SelectArrCache($YUIs['cached_count'], 180, 'tablesearch_count'); - if(!empty($aResultTotal)) { - $iTotal = reset($aResultTotal); - $iTotal = reset($iTotal); - } - } - if(method_exists($this->app->erp,'CheckSchnellsuche')) { - $this->app->erp->CheckSchnellsuche($cmd, $iTotal, microtime(true) - $starttime); - } - //$heading = count($this->app->YUI->TableSearch("",$cmd,"heading","","",$frommodule, $fromclass)); - $heading = count($YUIs['heading']); - //$menu = $this->app->YUI->TableSearch("",$cmd,"menu","","",$frommodule, $fromclass); - $menu = $this->app->Tpl->ParseTranslation($YUIs['menu']); - $sOutput2 = ''; - $rowc = 0; - while ( $aRow = $this->app->DB->Fetch_Row( $rResult )) { - $rowc++; - if(!$limiert || ($rowc <= $iDisplayLength)) { - $sOutput2 .= '['; - for($i=1;$i<$heading;$i++) { - /*if(strpos($aRow[$i],'<') !== false) //30.07.2018 Bruno Entfernt wegen fehlerhaften Entfernen von Tags - { - if($jsarray && isset($jsarray[$i]) && !$jsarray[$i]) - { - $aRow[$i] = strip_tags($aRow[$i]); - }elseif(isset($jsarray[$i]) && 1 == $jsarray[$i]) - { - $aRow[$i] = $this->app->stringcleaner->xss_clean($aRow[$i], false); - } - }*/ - $aRow[$i] = $this->EntferneSteuerzeichen(trim(str_replace("'",''',$aRow[$i]))); - $aRow[$i] = str_replace("\r",'',$aRow[$i]); - $aRow[$i] = str_replace("\n",'',$aRow[$i]); - $sOutput2 .= '"'.addslashes($aRow[$i]).'",'; - } - - $sOutput2 .= '"'.addslashes(str_replace('%value%',$aRow[$i],$menu)).'"'; - - $sOutput2 .= '],'; - } - } - if($limiert) { - $sOutput = '{'; - $sOutput .= '"sEcho": '.(int)$sEcho.', '; - $sOutput .= '"iTotalRecords": '.(!empty($iTotal)?$iTotal:$rowc+(int)$iDisplayStart).', '; - $sOutput .= '"iTotalDisplayRecords": '.($rowc+(int)$iDisplayStart).', '; - $sOutput .= '"aaData": [ '; - } - else{ - $sOutput = '{'; - $sOutput .= '"sEcho": '.(int)$sEcho.', '; - $sOutput .= '"iTotalRecords": '.$iTotal.', '; - $sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', '; - $sOutput .= '"aaData": [ '; - } - $sOutput .= $sOutput2; - - $sOutput = substr_replace( $sOutput, "", -1 ); - $sOutput .= '] }'; - - $sOutput = str_replace("\t",'',$sOutput); - - // Eventuell deutsches Datumsformat in allen Tabellen und sortieren geht auch - //$repl = preg_replace('~\"([1-2]{1}\d{3})-(\d{2})-(\d{2})\"~', '" $3.$2.$1"', $sOutput); - //$repl = preg_replace('~\"([1-2]{1}\d{3})-(\d{2})-(\d{2})\s+~', '" $3.$2.$1 ', $repl); - //$repl = preg_replace('~\s+([1-2]{1}\d{3})-(\d{2})-(\d{2})\s+~', ' $3.$2.$1 ', $repl); - //$repl = preg_replace('~\"(\d{4})-(\d{2})-(\d{2})\"~', '"$3.$2.$1"', $sOutput); - $repl = $sOutput; - $repl = $this->app->erp->ClearDataBeforeOutput($repl); - $repl = json_encode(json_decode($repl)); - echo $repl; - if(!empty($YUIs['onequeryperuser'])) { - $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); - } - $this->app->erp->ExitWawi(); - } - - /** - * @return void - */ - public function AjaxLiveTable(): void - { - /** @var Request request */ - $request = $this->app->Container->get('Request'); - $tableName = $request->get->get('srctable', ''); - $module = $request->get->get('srcmodule', ''); - $className = $request->get->get('srcclass', ''); - $className = StringUtil::toTitleCase($className, '-'); - - $this->app->BuildNavigation=false; - - if (empty($tableName)) { - $this->app->Tpl->Set( - 'MESSAGE', - '
Fehler: Tabelle ist nicht spezifiziert.
' - ); - $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); - - return; - } - - if ((empty($module) xor empty($className))) { - $this->app->Tpl->Set( - 'MESSAGE', - '
Fehler: Tabelle kann nicht gefunden werden.
' - ); - $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); - - return; - } - - if (!empty($module) && !str_ends_with(strtolower($module), '.php')) { - $module .= '.php'; - } - - $this->app->YUI->TableSearch('LIVETABLE', $tableName, 'show', '', '', $module, $className); - $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); - } - - protected function EntferneSteuerzeichen($string) - { - $len = strlen($string); - $out = ''; - for($i = 0; $i < $len; $i++) { - $ord = ord($string[$i]); - if($ord != 127 && ($ord > 31 || $ord == 13 || $ord == 10 || $ord == 9)) { - $out .= $string[$i]; - } - } - return $out; - } - - protected function fnColumnToFieldPosition( $i ) - { - $cmd = $this->app->Secure->GetGET('cmd'); - $findcols = $this->app->YUI->TablePositionSearch('',$cmd,'findcols'); - - return !empty($findcols[$i])?$findcols[$i]:0; - } - - protected function fnColumnToField( $i ) - { - $cmd = $this->app->Secure->GetGET('cmd'); - $frommodule = $this->app->Secure->GetGET('frommodule'); - $fromclass = $this->app->Secure->GetGET('fromclass'); - $findcols = $this->app->YUI->TableSearch('',$cmd,'findcols','','',$frommodule, $fromclass); - - return $findcols[$i]; - } - -} - +app=$app; + if($intern) { + return; + } + $this->app->ActionHandlerInit($this); + + $this->app->ActionHandler("filter","AjaxFilter"); + $this->app->ActionHandler("table","AjaxTable"); + $this->app->ActionHandler("labels","AjaxLabels"); + $this->app->ActionHandler("validator","AjaxValidator"); + $this->app->ActionHandler("ansprechpartner","AjaxAnsprechpartner"); + $this->app->ActionHandler("lieferadresse","AjaxLieferadresse"); + $this->app->ActionHandler("verzolladresse","AjaxVerzolladresse"); + $this->app->ActionHandler("adressestammdaten","AjaxAdresseStammdaten"); + $this->app->ActionHandler("tooltipsuche","AjaxTooltipSuche"); + $this->app->ActionHandler("tableposition","AjaxTablePosition"); + $this->app->ActionHandler("tablefilter", "AjaxTableFilter"); + $this->app->ActionHandler("articlematrixselection", "AjaxArticleMatrixSelection"); + $this->app->ActionHandler("moduleunlock", "AjaxModuleUnlock"); + $this->app->ActionHandler("thumbnail", "AjaxThumbnail"); + $this->app->ActionHandler("autosavekonfiguration", "AjaxAutoSaveKonfiguration"); + $this->app->ActionHandler("autosaveuserparameter", "AjaxAutoSaveUserParameter"); + $this->app->ActionHandler("getuserparameter","AjaxGetUserParameter"); + $this->app->ActionHandler("getdateititel","AjaxGetDateiTitel"); + $this->app->ActionHandler("editdateititel","AjaxEditDateiTitel"); + $this->app->ActionHandler("profilbild","AjaxProfilbild"); + $this->app->ActionHandler("getgewicht","AjaxGetGewicht"); + $this->app->ActionHandler("upload","AjaxUpload"); + $this->app->ActionHandler("sidebar","AjaxSidebar"); + $this->app->ActionHandler("livetable","AjaxLiveTable"); + $this->app->ActionHandlerListen($app); + } + + /** + * @return JsonResponse + */ + public function AjaxSidebar(): JsonResponse + { + $userId = $this->app->User->GetID(); + $cmd = $this->app->Secure->GetGET('cmd'); + + switch ($cmd) { + case 'set_collapsed': + $state = $this->app->Secure->GetGET('value') === 'true'; + /** @var Xentral\Modules\User\Service\UserConfigService $userConfig */ + $userConfig = $this->app->Container->get('UserConfigService'); + $userConfig->set('sidebar_collapsed', $state,$userId); + $data = ['success' => true, 'collapsed' => $state]; + break; + + default: + $data = ['success' => false, 'error' => 'Incomplete request']; + break; + } + + return new JsonResponse( + $data, + $data['success'] === false ? JsonResponse::HTTP_BAD_REQUEST : JsonResponse::HTTP_OK + ); + } + + public function AjaxUpload() + { + $fromUrl = $this->app->Secure->GetGET('fromurl'); + $fromUrl = pathinfo($fromUrl); + $fromUrl = $fromUrl['basename']; + if(strpos($fromUrl, 'index.php?') === 0) { + $fromUrl = substr($fromUrl, 10); + } + $fromUrl = explode('&', $fromUrl); + $parts = []; + foreach($fromUrl as $urlpart) { + $urlpartA = explode('=', $urlpart); + $parts[$urlpartA[0]] = isset($urlpartA[1])?$urlpartA[1]:''; + } + if(!empty($_FILES)) { + $this->app->erp->RunHook('ajaxupload', 1, $parts); + } + + header('Content-Type: application/json'); + echo json_encode([]); + $this->app->ExitXentral(); + } + + public function AjaxGetGewicht() + { + $seriennummer = $this->app->Secure->GetPOST('seriennummer'); + ///$mindestgewicht = (float)$this->app->Secure->GetPOST('mindestgewicht'); + $gewicht = str_replace(',','.',$this->app->erp->GetAdapterboxAPIWaage($seriennummer)); + if(!is_numeric($gewicht)) { + $gewicht = 0; + } + //if($gewicht < $mindestgewicht)$gewicht = $mindestgewicht; + echo json_encode(array('gewicht'=>number_format($gewicht ,1,'.',''))); + $this->app->ExitXentral(); + } + + public function AjaxLabels() + { + /** @var \Xentral\Modules\Label\LabelModule $labelModule */ + $labelModule = $this->app->Container->get('LabelModule'); + + $cmd = $this->app->Secure->GetGET('cmd'); + switch ($cmd) { + + case 'collect': + // Aktive Labels für eine DataTable-Seite abrufen + $collection = $this->app->Secure->GetPOST('collection'); + + $data = $this->FindLabelsByCollection($collection); + header('Content-Type: application/json'); + echo json_encode(['success' => true, 'data' => $data]); + $this->app->erp->ExitWawi(); + break; + + case 'list': + // Label-Typen auflisten + Zugewiesene Typen markieren + $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); + $referenceTable = $this->app->Secure->GetPOST('reference_table'); + + $labelTypes = $this->FindLabelTypesByReference($referenceTable, $referenceId); + header('Content-Type: application/json'); + echo json_encode($labelTypes); + $this->app->erp->ExitWawi(); + break; + + case 'assign': + // Label-Zuweisung erstellen + $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); + $referenceTable = $this->app->Secure->GetPOST('reference_table'); + $labelType = $this->app->Secure->GetPOST('type'); + + try { + $labelModule->assignLabel($referenceTable, $referenceId, $labelType); + } catch (LabelExceptionInterface $exception) { + header('HTTP/1.1 404 Not Found'); + header('Content-Type: application/json'); + echo json_encode(['success' => false, 'error' => 'Zuweisung nicht möglich. Fehler: ' . $exception->getMessage()]); + $this->app->erp->ExitWawi(); + return; + } + + // Ausgabe + $data = $this->FindLabelsByReference($referenceTable, $referenceId); + header('Content-Type: application/json'); + echo json_encode(['success' => true, 'data' => $data]); + $this->app->erp->ExitWawi(); + break; + + case 'unassign': + // Label-Zuweisung löschen + $referenceId = (int)$this->app->Secure->GetPOST('reference_id'); + $referenceTable = $this->app->Secure->GetPOST('reference_table'); + $labelType = $this->app->Secure->GetPOST('type'); + + try { + $labelModule->unassignLabel($referenceTable, $referenceId, $labelType); + } catch (LabelExceptionInterface $exception) { + header('HTTP/1.1 404 Not Found'); + header('Content-Type: application/json'); + echo json_encode(['success' => false, 'error' => 'Zuweisung löschen nicht möglich. Fehler: ' . $exception->getMessage()]); + $this->app->erp->ExitWawi(); + return; + } + + // Ausgabe + $data = $this->FindLabelsByReference($referenceTable, $referenceId); + header('Content-Type: application/json'); + echo json_encode(['success' => true, 'data' => $data]); + $this->app->erp->ExitWawi(); + break; + } + } + + /** + * @param string $referenceTable + * @param int $referenceId + * + * @return array + */ + protected function FindLabelsByReference($referenceTable, $referenceId) + { + /** @var \Xentral\Modules\Label\LabelModule $labelModule */ + $labelModule = $this->app->Container->get('LabelModule'); + $labels = $labelModule->findLabelsByReference($referenceTable, $referenceId); + + $target = sprintf('labels-%s-%s', $referenceTable, $referenceId); + $result = [$target => []]; + + foreach ($labels as $item) { + $item['target'] = $target; + $item['title'] = htmlspecialchars($item['title']); + $item['bgcolor'] = $item['hexcolor']; + unset($item['hexcolor']); + unset($item['id']); + + $result[$target][] = $item; + } + + return $result; + } + + /** + * @param array $collection + * + * @return array + */ + protected function FindLabelsByCollection($collection) + { + /** @var \Xentral\Modules\Label\LabelModule $labelModule */ + $labelModule = $this->app->Container->get('LabelModule'); + + $result = []; + foreach ($collection as $referenceTable => $referenceIds) { + $referenceTable = (string)$referenceTable; + if (empty($referenceTable)) { + continue; + } + + // Für jede angefragte Referenz ein Ergebnis liefern; Leeres Ergebnis als Default + foreach ($referenceIds as $referenceId) { + $target = sprintf('labels-%s-%s', $referenceTable, $referenceId); + $result[$target] = []; + } + + // Label-Gruppen anlegen + $labelGroupId = $this->app->DB->Select( + "SELECT lg.id FROM label_group AS lg WHERE lg.group_table = '{$referenceTable}'" + ); + if (empty($labelGroupId)) { + $groupTitle = ucwords($referenceTable); + $this->app->DB->Insert( + "INSERT INTO label_group (id, group_table, title, created_at) + VALUES (NULL, '{$referenceTable}', '{$groupTitle}', CURRENT_TIMESTAMP)" + ); + } + + $labels = $labelModule->findLabelsByReferences($referenceTable, $referenceIds); + foreach ($labels as $item) { + $target = sprintf('labels-%s-%s', $item['reference_table'], $item['reference_id']); + if (!isset($result[$target])) { + $result[$target] = []; + } + $item['target'] = $target; + $item['title'] = htmlspecialchars($item['title']); + $item['bgcolor'] = $item['hexcolor']; + $item['referenceTable'] = $item['reference_table']; + $item['referenceId'] = $item['reference_id']; + unset($item['reference_table']); + unset($item['reference_id']); + unset($item['hexcolor']); + unset($item['id']); + + $result[$target][] = $item; + } + } + + return $result; + } + + /** + * @param string $referenceTable + * @param int $referenceId + * + * @return array + */ + protected function FindLabelTypesByReference($referenceTable, $referenceId) + { + /** @var \Xentral\Modules\Label\LabelModule $labelModule */ + $labelModule = $this->app->Container->get('LabelModule'); + $labelTypes = $labelModule->findLabelTypesByReference($referenceTable, $referenceId); + + foreach ($labelTypes as &$labelType) { + $labelType['id'] = (int)$labelType['id']; + $labelType['target'] = 'labels-' . $referenceTable . '-' . $referenceId; + $labelType['selected'] = !empty($labelType['label_id']); + if ((int)$labelType['label_id'] > 0) { + $labelType['key'] = 'label-' . (int)$labelType['label_id']; + } + $labelType['bgcolor'] = $labelType['hexcolor']; + $labelType['referenceTable'] = $referenceTable; + $labelType['referenceId'] = $referenceId; + unset($labelType['hexcolor']); + } + + return $labelTypes; + } + + public function AjaxValidator() + { + $rule = $this->app->Secure->GetPOST('rule'); + $value = $this->app->Secure->GetPOST('value'); + $mandatoryId = (int)$this->app->Secure->GetPOST('mandatoryid'); + + /** @var \Xentral\Modules\MandatoryFields\MandatoryFieldsModule $mandatoryFields */ + $mandatoryFields = $this->app->Container->get('MandatoryFieldsModule'); + + try{ + $data = $mandatoryFields->validate($rule,$value,$mandatoryId)->toArray(); + } catch(UnknownTypeException $e){ + $data = ['error' => true, 'message' => 'Validatorregel nicht gültig.']; + } catch(MandatoryFieldNotFoundException $e){ + $data = ['error' => true, 'message' => 'Die Validierungsregel konnte nicht gefunden werden.']; + } + header('Content-Type: application/json'); + echo json_encode($data); + $this->app->ExitXentral(); + } + + public function AjaxGetDateiTitel() + { + $status = 0; + $cmds = $this->CmdList(); + $cmd = $this->app->Secure->GetPOST('typ'); + $data = null; + if($this->app->erp->RechteVorhanden($cmd, 'dateien')) + { + $id = $this->app->Secure->GetPOST('id'); + $objekt = $this->app->Secure->GetPOST('typ'); + $parameter = $this->app->Secure->GetPOST('parameter'); + if($objekt === 'adresse'){ + $objekt = 'Adressen'; + } + + $data = $this->app->DB->SelectRow( + "SELECT d.*, s.subjekt + FROM datei AS d + LEFT JOIN datei_stichwoerter AS s ON d.id=s.datei + LEFT JOIN datei_version AS v ON v.datei=d.id + WHERE s.objekt LIKE '$objekt' AND s.parameter='$parameter' AND d.geloescht=0 AND d.id = '$id' + LIMIT 1" + ); + + + $module = strtolower($objekt); + if($module === 'adressen'){ + $module = 'adresse'; + } + + $typen = $this->app->erp->getDateiTypen($module); + $found = false; + foreach($typen as $typ) { + if($typ['wert'] === $data['subjekt']) { + $found = true; + break; + } + } + $subjekthtml = ''; + if(!$found) { + $subjekthtml = ''; + } + foreach($typen as $typ) { + $subjekthtml .= ''; + } + /* + $subjekthtml = ''; + if($module==='adresse') + { + $subjekthtml .= ''; + } + + if($module!='') + { + $tmp = $this->app->DB->SelectArr("SELECT * FROM datei_stichwortvorlagen WHERE modul='$module' ORDER by beschriftung"); + $ctmp = $tmp?count($tmp):0; + for($i=0;$i<$ctmp;$i++) { + $subjekthtml .= ''; + } + } + + $tmp = $this->app->DB->SelectArr("SELECT * FROM datei_stichwortvorlagen WHERE modul='' ORDER by beschriftung"); + $ctmp = $tmp?count($tmp):0; + for($i=0;$i<$ctmp;$i++) { + $subjekthtml .= ''; + } + */ + + if($data){ + $data['subjekthtml'] = $subjekthtml; + } + + } + + echo json_encode($data); + exit; + } + + public function AjaxEditDateiTitel() + { + $status = 0; + $cmds = $this->CmdList(); + $cmd = $this->app->Secure->GetPOST('typ'); + $data = null; + if($this->app->erp->RechteVorhanden($cmd, 'dateien')) + { + $id = $this->app->Secure->GetPOST('id'); + $objekt = $this->app->Secure->GetPOST('typ'); + $parameter = $this->app->Secure->GetPOST('parameter'); + $titel = $this->app->Secure->GetPOST('titel'); + $beschreibung = $this->app->Secure->GetPOST('beschreibung'); + $subjekt = $this->app->Secure->GetPOST('subjekt'); + if($objekt == 'adresse') + { + $objekt = 'Adressen'; + } + $ersteller = $this->app->DB->real_escape_string($this->app->User->GetName()); + $datei = $this->app->DB->SelectArr("SELECT d.id, s.id as sid FROM datei d LEFT JOIN datei_stichwoerter s ON d.id=s.datei LEFT JOIN datei_version v ON v.datei=d.id WHERE s.objekt LIKE '$objekt' AND s.parameter='$parameter' AND d.geloescht=0 AND d.id = '$id' LIMIT 1"); + if($datei) + { + $sid = $datei[0]['sid']; + if($subjekt && $sid) + { + $this->app->DB->Update("UPDATE datei_stichwoerter SET subjekt = '".$this->app->DB->real_escape_string($subjekt)."' WHERE id = '$sid' LIMIT 1"); + } + $this->app->DB->Update("UPDATE datei SET titel = '$titel', beschreibung = '$beschreibung' WHERE id = '$id' LIMIT 1"); + if(!empty($_FILES['datei']) && $_FILES['datei']['tmp_name']!='') + { + $dateiname = $_FILES['datei']['name']; + $this->app->erp->AddDateiVersion($id,$ersteller,$dateiname, $beschreibung,$_FILES['datei']['tmp_name']); + } + $status = 1; + } + } + + echo json_encode(array('status'=>$status)); + exit; + } + + protected function CmdList() + { + return array('artikel','adresse','angebot','auftrag','rechnung','gutschrift','lieferschein','bestellung','projekt','produktion','anfrage','reisekosten','kalkulation','serviceauftrag','verbindlichkeit','kasse','geschaeftsbrief_vorlagen','wiedervorlage','wiki'); + } + + /** + * @param int $userId + * @param string|null $alt + * @param string|null $imgClass + * @param int|null $widthHeight + * + * @return string + */ + public function getProfileHtml($userId, $alt = null, $imgClass=null, $widthHeight = null): string + { + $userId = (int)$userId; + $addressId = 0; + $shortUserName = ''; + $user = $userId <= 0?null:$this->app->DB->SelectRow( + sprintf( + "SELECT u.adresse, u.`username` + FROM `user` AS `u` + WHERE u.id=%d + LIMIT 1", + $userId + ) + ); + if(!empty($user)) { + $addressId = $user['adresse']; + $shortUserName = substr($user['username'],0,2); + } + + $fileId = $this->getFileVersionFromProfileImage($addressId); + if($this->getProfilePictureFromFileVersionId($fileId) !== null) { + $imgString = sprintf( + '%s'; + } + + return sprintf('%s', $shortUserName); + } + + /** + * @param int $addressId + * + * @return int|null + */ + public function getFileVersionFromProfileImage($addressId): ?int + { + $addressId = (int)$addressId; + if($addressId <= 0) { + return null; + } + $fileVersionId = (int)$this->app->DB->Select( + sprintf( + "SELECT dv.id + FROM `datei_stichwoerter` AS `ds` + INNER JOIN `datei` AS `d` ON ds.datei = d.id + INNER JOIN `datei_version` AS `dv` ON dv.datei = d.id + WHERE d.geloescht = 0 AND objekt LIKE 'Adressen' AND parameter = '%d' AND subjekt LIKE 'Profilbild' + ORDER BY dv.id DESC + LIMIT 1", + $addressId + ) + ); + if($fileVersionId <= 0) { + return null; + } + + return $fileVersionId; + } + + /** + * @param int $fileVersionId + * + * @return bool + */ + public function getProfilePictureFromFileVersionId($fileVersionId): ?array + { + $fileVersionId = (int)$fileVersionId; + if($fileVersionId <= 0) { + return null; + } + $userdata = isset($this->app->Conf->WFuserdata)?$this->app->Conf->WFuserdata:str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME'])."../userdata"; + $path = $userdata.'/dms/'.$this->app->Conf->WFdbname; + $cachefolder = $path.'/cache'; + $path = $this->app->erp->GetDMSPath($fileVersionId, $path); + $cachefolder = $this->app->erp->GetDMSPath($fileVersionId.'_100_100', $cachefolder, true); + if(!file_exists($cachefolder.'/'.$fileVersionId.'_100_100')) { + if(file_exists($path.'/'.$fileVersionId)) { + $type = mime_content_type($path.'/'.$fileVersionId); + switch($type) { + case 'image/jpg': + case 'image/jpeg': + $img = new image($this->app); + $str = $img->scaledPicByFileId($fileVersionId, 100, 100); + if((string)$str === '') { + return null; + } + return [ + 'header' => 'Content-type: image/jpg', + 'image' => $str, + ]; + break; + case 'image/png': + $img = new image($this->app); + $str = $img->scaledPicByFileId($fileVersionId, 100, 100); + if((string)$str === '') { + return null; + } + return [ + 'header' => 'Content-type: image/png', + 'image' => $str, + ]; + break; + case 'image/gif': + $img = new image($this->app); + $str = $img->scaledPicByFileId($fileVersionId, 100, 100); + if((string)$str === '') { + return null; + } + return [ + 'header' => 'Content-type: image/gif', + 'image' => $str, + ]; + break; + case 'application/pdf': + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); + if((string)$str === '') { + return null; + } + + return [ + 'header' => 'Content-type: image/svg', + 'picture' => $str, + ]; + break; + } + } + } + if(file_exists($cachefolder.'/'.$fileVersionId.'_100_100')){ + $type = mime_content_type($cachefolder . '/' . $fileVersionId . '_100_100'); + if(strpos($type, 'image') !== false){ + $str = file_get_contents($cachefolder . '/' . $fileVersionId . '_100_100'); + if((string)$str === '') { + return null; + } + + return [ + 'header' => 'Content-type: ' . $type, + 'picture' => $str, + ]; + } + } + + return null; + } + + public function AjaxProfilbild() + { + $userId = (int)$this->app->Secure->GetGET('id'); + $addressId = $userId === $this->app->User->GetID() + ?$this->app->User->GetAdresse(): + (int)$this->app->DB->Select(sprintf('SELECT `adresse` FROM `user` WHERE `id` = %d', $userId)); + $dateiversion = $this->getFileVersionFromProfileImage($addressId); + $picture = $this->getProfilePictureFromFileVersionId($dateiversion); + if($picture !== null) { + header($picture['header']); + echo $picture['picture']; + exit; + } + + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/profil.png'); + header('Content-type: image/png'); + echo $str; + exit; + } + + public function AjaxThumbnail() + { + $cmds = $this->CmdList(); + $cmd = trim($this->app->Secure->GetGET('cmd')); + $id = (int)$this->app->Secure->GetGET('id'); + + if(!empty($cmd) && $id + && (!in_array($cmd, $cmds) || (in_array($cmd, $cmds) && $this->app->erp->RechteVorhanden($cmd,'dateien')))) { + $datei = $this->app->DB->SelectRow( + sprintf( + "SELECT dv.id, ds.parameter, dv.dateiname + FROM datei_version AS dv + INNER JOIN datei_stichwoerter ds ON ds.datei = dv.datei + WHERE dv.datei = %d AND (ds.objekt like '%s'".($cmd === 'adresse'?" OR ds.objekt like 'Adressen' ":'').") + ORDER BY dv.datei DESC, dv.version DESC + LIMIT 1", + $id, $cmd + ) + ); + if(empty($datei)) { + if ($this->app->erp->Firmendaten('iconset_dunkel')) { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); + } else { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); + } + header('Content-type: image/png'); + echo $str; + exit; + } + if(!empty($datei['parameter'])) { + if($cmd === 'projekt') { + if(!$this->app->erp->UserProjektRecht($datei['parameter'])) { + if ($this->app->erp->Firmendaten('iconset_dunkel')) { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); + } else { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); + } + header('Content-type: image/png'); + echo $str; + exit; + } + } + else{ + $projekt = $this->app->DB->Select( + sprintf( + 'SELECT `projekt` FROM `%s` WHERE `id` = %d LIMIT 1', + $cmd, $datei[0]['parameter'] + ) + ); + if(!$this->app->erp->UserProjektRecht($projekt)) { + if ($this->app->erp->Firmendaten('iconset_dunkel')) { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); + } + else { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); + } + header('Content-type: image/png'); + echo $str; + exit; + } + } + } + //Rechte prüfen + + $userdata = isset($this->app->Conf->WFuserdata) + ?$this->app->Conf->WFuserdata + :(str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']).'../userdata'); + $path = $userdata.'/dms/'.$this->app->Conf->WFdbname; + $cachefolder = $path.'/cache'; + $_cachefolder = $cachefolder; + $cachefolder = $this->app->erp->GetDMSPath($datei['id'].'_100_100', $cachefolder, true); + if(!file_exists($cachefolder.'/'.$datei['id'].'_100_100')) { + $cachefolder = $this->app->erp->CreateDMSPath($_cachefolder, $datei['id']); + $datei_orig = $this->app->erp->GetDateiPfadVersion($datei['id']); + if(file_exists($datei_orig)) { + $type = mime_content_type($datei_orig); + switch($type) + { + case 'image/jpg': + case 'image/jpeg': + $img = new image($this->app); + $str = $img->scaledPicByFileId($datei['id'], 100, 100); + header('Content-type: image/jpg'); + echo $str; + exit; + break; + case 'image/png': + $img = new image($this->app); + $str = $img->scaledPicByFileId($datei['id'], 100, 100); + header('Content-type: image/png'); + echo $str; + exit; + break; + case 'image/gif': + $img = new image($this->app); + $str = $img->scaledPicByFileId($datei['id'], 100, 100); + header('Content-type: image/gif'); + echo $str; + exit; + break; + case 'application/pdf': + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); + header('Content-type: image/png'); + echo $str; + exit; + break; + default: + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/pdf.svg'); + if(substr(strtolower($datei['dateiname']),-4) === '.gif'){ + header('Content-type: image/gif'); + echo $str; + exit; + } + if(substr(strtolower($datei['dateiname']),-4) === '.png'){ + header('Content-type: image/png'); + echo $str; + exit; + } + if(substr(strtolower($datei['dateiname']),-4) === '.jpg' + || substr(strtolower($datei['dateiname']),-4) === 'jpeg'){ + header('Content-type: image/jpg'); + echo $str; + exit; + } + break; + } + } + } + + if(file_exists($cachefolder.'/'.$datei['id'].'_100_100')) { + $type = is_file($path.'/'.$datei['id'])? false : mime_content_type($path.'/'.$datei['id']); + if($type === false) { + $type = mime_content_type($cachefolder.'/'.$datei['id'].'_100_100'); + } + if(strpos($type,'image') !== false) { + header('Content-type: '.$type); + $str = file_get_contents($cachefolder.'/'.$datei['id'].'_100_100'); + echo $str; + exit; + } + $str = file_get_contents($cachefolder.'/'.$datei['id'].'_100_100'); + if(substr(strtolower($datei['dateiname']),-4) === '.gif') { + header('Content-type: image/gif'); + echo $str; + exit; + } + if(substr(strtolower($datei['dateiname']),-4) === '.png') { + header('Content-type: image/png'); + echo $str; + exit; + } + if(substr(strtolower($datei['dateiname']),-4) === '.jpg' + || substr(strtolower($datei['dateiname']),-5) === '.jpeg') { + header('Content-type: image/jpg'); + echo $str; + exit; + } + } + else{ + if ($this->app->erp->Firmendaten('iconset_dunkel')) { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); + } else { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); + } + header('Content-type: image/png'); + echo $str; + exit; + } + } + else{ + if ($this->app->erp->Firmendaten('iconset_dunkel')) { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_dunkel.png'); + } else { + $str = file_get_contents(dirname(__DIR__) . '/themes/new/images/keinbild_hell.png'); + } + header('Content-type: image/png'); + echo $str; + } + exit; + } + + public function AjaxModuleUnlock() { + if($this->app->erp->RechteVorhanden('welcome','unlock') && + ($salt = $this->app->Secure->GetGET('salt'))) + { + $this->app->DB->Delete("DELETE from module_lock where salt = '".$salt."'"); + } + $this->app->erp->ExitWawi(); + } + + public function AjaxTableFilter() { + + /*header("Content-Type: text/html; charset=utf-8");*/ + + $do = $this->app->Secure->GetGET('do'); + $filter = $this->app->Secure->GetGET('filter'); + + switch ($do) { + case 'getParameters': + $params = $this->app->User->GetParameter('table_filter_' . $filter); + echo base64_decode($params); + break; + case 'setParameters': + $params = base64_encode(json_encode($_GET)); + $this->app->User->SetParameter('table_filter_' . $filter, $params); + break; + case 'clearParameters': + $this->app->User->SetParameter('table_filter_' . $filter,''); + break; + default: + return false; + break; + } + + $this->app->erp->ExitWawi(); + } + + public function AjaxArticleMatrixSelection() + { + $menge = $this->app->Secure->GetPOST('menge'); + $auswahl = $this->app->Secure->GetPOST('auswahl'); + $cmd = $this->app->Secure->GetGET('cmd'); + $vorgangsId = (int)$this->app->Secure->GetGET('id'); + $vorgangsTyp = $this->app->Secure->GetGET('typ'); + if ($vorgangsId === 0) { + $this->app->erp->ExitWawi(); + } + + if ($cmd === 'get') { + $articleMatrixSelection = $this->GetArticleMatrixSelection($vorgangsTyp, $vorgangsId); + header('Content-Type: application/json'); + echo json_encode($articleMatrixSelection); + $this->app->erp->ExitWawi(); + } + + if ($cmd === 'set') { + // Vorhandene Auswahl laden und aktuelle Auswahl hinzufügen + // Notwendig, da sich der Auswahlprozess über mehrere Seiten erstrecken kann. + $articleMatrix = $this->GetArticleMatrixSelection($vorgangsTyp, $vorgangsId); + + foreach ($menge as $artikelId => $artikelAnzahl) { + // Nur Mengen größer Null merken + if (!empty($artikelAnzahl)) { + $articleMatrix['menge'][(int)$artikelId] = (int)$artikelAnzahl; + } + // Auswahl wurde entfernt > Menge ebenfalls leeren + if (isset($menge[$artikelId]) && !isset($auswahl[$artikelId])) { + unset($articleMatrix['auswahl'][(int)$artikelId],$articleMatrix['menge'][(int)$artikelId]); + } + } + // Nur aktive Checkboxen merken + foreach ($auswahl as $artikelId => $artikelAuswahl) { + if ($artikelAuswahl === 'on') { + $articleMatrix['auswahl'][(int)$artikelId] = true; + } + } + + $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, $articleMatrix); + $this->app->erp->ExitWawi(); + } + + // Artikelmatrix-Auswahl zurücksetzen + if ($cmd === "reset") { + $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, []); + $this->app->erp->ExitWawi(); + } + } + + protected function GetArticleMatrixSelection($vorgangsTyp, $vorgangsId) + { + if (empty($vorgangsTyp) || (int)$vorgangsId === 0) { + return [ + 'auswahl' => [], + 'menge' => [], + ]; + } + + $selection = $this->app->User->GetParameter("article_matrix_selection_{$vorgangsTyp}_{$vorgangsId}"); + $matrix = json_decode($selection, true); + if (empty($matrix)) { + $matrix = []; + } + + // Alter des Eintrags kontrollieren; nach 24 Stunden ohne Änderung > Eintrag verwerfen + $yesterday = time() - (60 * 60 * 24); + if (empty($matrix['time']) || (int)$matrix['time'] < $yesterday) { + $this->SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, []); + $matrix = []; + } + + if (empty($matrix['auswahl'])) { + $matrix['auswahl'] = []; + } + if (empty($matrix['menge'])) { + $matrix['menge'] = []; + } + + return $matrix; + } + + protected function SaveArticleMatrixSelection($vorgangsTyp, $vorgangsId, $data = []) + { + if ((int)$vorgangsId === 0) { + return; + } + if (empty($vorgangsTyp)) { + return; + } + if (!is_array($data)) { + $data = []; + } + + // Aktuellen Timestamp hinzufügen/überschreiben + $data['time'] = time(); + + // Auswahl pro User und Vorgang merken + $this->app->User->SetParameter("article_matrix_selection_{$vorgangsTyp}_{$vorgangsId}", json_encode($data)); + } + + public function AjaxTooltipSuche() + { + $term = $this->app->Secure->GetGET('term'); + + if(is_numeric($term)) + { + $rechnung = $this->app->DB->SelectArr("SELECT id,belegnr,soll,ist FROM rechnung WHERE belegnr='$term'"); + $gutschrift = $this->app->DB->SelectArr("SELECT id,belegnr,soll,ist FROM gutschrift WHERE belegnr='$term'"); + $auftrag = $this->app->DB->SelectArr("SELECT id,belegnr FROM auftrag WHERE belegnr='$term'"); + $internet = $this->app->DB->SelectArr("SELECT id,belegnr FROM auftrag WHERE internet='$term'"); + $kunde = $this->app->DB->SelectArr("SELECT id,name FROM adresse WHERE kundennummer='$term'"); + } + if(!empty($rechnung) && is_array($rechnung)) + { + foreach($rechnung as $value){ + echo '
Rechnung '.$value['belegnr'].' SOLL:'.$value['soll'].' IST:'.$value['ist'].'
'; + } + } + + if(!empty($auftrag) && is_array($auftrag)) + { + foreach($auftrag as $value){ + echo 'Auftrag '.$value['belegnr']; + } + } + + + + if(!empty($internet) && is_array($internet)) + { + foreach($internet as $value){ + echo 'Internet Auftrag '.$value['belegnr']; + } + } + + + /*if($internetnummer) + echo "Internetnummer";*/ + + + if(!empty($kunde) && is_array($kunde)) + { + foreach($kunde as $value){ + echo 'Kunde '.$value['name']; + } + } + + + echo 'ENDE '; + + $this->app->erp->ExitWawi(); + + } + + public function AjaxAdresseStammdaten() + { + $id = $this->app->Secure->GetGET('id'); + if($id <= 0) + { + $this->app->erp->ExitWawi(); + } + + //name abteilung unterabteilung land strasse ort plz + + $values = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$id' LIMIT 1"); + if(!empty($values)){ + foreach ($values[0] as $key => $value) { + $values[0][$key] = $this->app->erp->ReadyForPDF($value); + } + + echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['titel'] . '#*#' . $values[0]['id'] . + '#*#' . $values[0]['email'] . + '#*#' . $values[0]['telefon'] . + '#*#' . $values[0]['telfax'] . + '#*#' . $values[0]['anschreiben'] . + '#*#' . $values[0]['gln'] + ); + } + $this->app->erp->ExitWawi(); + + } + + public function AjaxVerzolladresse() + { + $id = $this->app->Secure->GetGET('id'); + if($id <= 0) + { + $this->app->erp->ExitWawi(); + } + + //name abteilung unterabteilung land strasse ort plz + + $values = $this->app->DB->SelectArr("SELECT * FROM adresse WHERE id='$id' LIMIT 1"); + if(!empty($values)){ + foreach ($values[0] as $key => $value) { + if($key !== 'zollinformationen') { + $values[0][$key] = $this->app->erp->ReadyForPDF($value); + } + } + echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['titel'] . '#*#' . base64_encode($values[0]['zollinformationen']) . '#*#'); + } + $this->app->erp->ExitWawi(); + } + + public function AjaxLieferadresse() + { + $id = $this->app->Secure->GetGET('id'); + if($id <= 0) + { + $this->app->erp->ExitWawi(); + } + + //name abteilung unterabteilung land strasse ort plz + + $values = $this->app->DB->SelectArr("SELECT * FROM lieferadressen WHERE id='$id' LIMIT 1"); + if(!empty($values)){ + foreach ($values[0] as $key => $value) { + $values[0][$key] = $this->app->erp->ReadyForPDF($value); + } + echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['ansprechpartner'] . '#*#' . $values[0]['id'] . '#*#' . $values[0]['gln'] . '#*#' . $values[0]['ustid'] . '#*#' . $values[0]['ust_befreit'] . '#*#' . $values[0]['lieferbedingung']. '#*#' . $values[0]['email']); + } + $this->app->erp->ExitWawi(); + + } + + + + public function AjaxAnsprechpartner() + { + $id = $this->app->Secure->GetGET('id'); + if($id <= 0) + { + $this->app->erp->ExitWawi(); + } + $values = $this->app->DB->SelectArr("SELECT * FROM ansprechpartner WHERE id='$id' LIMIT 1"); + if(!empty($values[0])){ + foreach ($values[0] as $key => $value) { + $values[0][$key] = $this->app->erp->ReadyForPDF($value); + } + echo $this->app->erp->ClearDataBeforeOutput($values[0]['name'] . '#*#' . $values[0]['email'] . '#*#' . $values[0]['telefon'] . '#*#' . $values[0]['telefax'] . '#*#' . $values[0]['abteilung'] . '#*#' . $values[0]['unterabteilung'] . + '#*#' . $values[0]['land'] . '#*#' . $values[0]['strasse'] . '#*#' . $values[0]['plz'] . '#*#' . $values[0]['ort'] . '#*#' . $values[0]['adresszusatz'] . '#*#' . $values[0]['typ'] . '#*#' . $values[0]['anschreiben'] . '#*#' . $values[0]['titel'] . '#*#' . $values[0]['id']); + } + $this->app->erp->ExitWawi(); + } + + public function AjaxAutoSaveKonfiguration() + { + $name = $this->app->Secure->GetPOST('name'); + $value = $this->app->Secure->GetPOST('value'); + $this->app->erp->SetKonfigurationValue($name,base64_decode($value)); + $this->app->erp->ExitWawi(); + } + + public function AjaxAutoSaveUserParameter() + { + $name = $this->app->Secure->GetPOST('name'); + $value = $this->app->Secure->GetPOST('value'); + $this->app->User->SetParameter($name,base64_decode($value)); + $this->app->erp->ExitWawi(); + } + + + public function AjaxGetUserParameter() + { + $name = $this->app->Secure->GetPOST('name'); + $names = $this->app->Secure->GetPOST('names'); + if(!empty($names)) + { + $names = explode(',', $names); + $elems = explode(',',$this->app->Secure->GetPOST('elems')); + + $values = $this->app->User->GetParameter($names); + if(!empty($values)) + { + foreach($values as $k => $v) + { + $values[$k]['elem'] = $elems[$k]; + } + } + echo json_encode($values); + }else{ + echo json_encode(array('name'=>$name,'elem'=>$this->app->Secure->GetPOST('elem'),'value'=>$this->app->User->GetParameter($name))); + } + $this->app->erp->ExitWawi(); + } + + public function AjaxFilterWhere($term, $fields) + { + if(empty($fields)) + { + return '1'; + } + while(strpos($term,' ') !== false) + { + $term = str_replace(' ',' ', $term); + } + $term = trim($term); + $term2 = $term; + $term3 = $term; + $term2 = $this->app->erp->ConvertForDBUTF8($term); + $term3 = $this->app->erp->ConvertForDB($term); + $terma = explode( ' ', $term); + $term2a = explode( ' ', $term2); + $term3a = explode( ' ', $term3); + if(count($terma) === 1) + { + $wherea = []; + foreach($fields as $v) { + $wherea[] = $v . " LIKE '%" . $term . "%'"; + if($term2 !== $term && $term2 !== ''){ + $wherea[] = $v . " LIKE '%" . $term2 . "%'"; + } + if($term3 !== $term && $term3 !== $term2 && $term3!==''){ + $wherea[] = $v . " LIKE '%" . $term3 . "%'"; + } + } + return ' ('.implode(' OR ', $wherea).') '; + } + $wherea = []; + foreach($fields as $v) { + if(!empty($term2) && $term2 !== $term){ + $tmp = []; + //foreach ($terma as $v2) { + $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma, $term2a); + //} + $wherea[] = implode(' AND ', $tmp); + } + elseif(!empty($term3) && $term3 !== $term){ + $tmp = []; + //foreach ($terma as $v2) { + $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma, $term3a); + //} + $wherea[] = implode(' AND ', $tmp); + } + else{ + $tmp = []; + //foreach ($terma as $v2) { + $tmp[] = $this->AjaxTableWhereBuilderArray($v, $terma); + //} + $wherea[] = implode(' AND ', $tmp); + } + } + + return ' ('.implode(' OR ', $wherea).') '; + } + + public function AjaxFilter() + { + //$term = $this->app->Secure->GetGET("term"); + $term = $this->app->Secure->GetGET('term'); + $termorig = $term; + $rmodule = $this->app->Secure->GetGET('rmodule'); + $raction = $this->app->Secure->GetGET('raction'); + $rid = (int)$this->app->Secure->GetGET('rid'); + $pruefemodule = array('artikel','auftrag','angebot','rechnung','lieferschein','gutschrift','bestellung','produktion'); + $filter_projekt = 0; + if($raction === 'edit' && $rid && in_array($rmodule, $pruefemodule)) + { + $projekt = $this->app->DB->Select("SELECT projekt FROM $rmodule WHERE id = '$rid' LIMIT 1"); + if($projekt) + { + $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id = '$projekt' LIMIT 1"); + //if($eigenernummernkreis) + $filter_projekt = $projekt; + } + } + $term2 = $term; + $term3 = $term; + $term = $this->app->erp->ConvertForDBUTF8($term); + $term2 = $this->app->erp->ConvertForDB($term2); + if($term2=='') { + $term2 = $term; + } + $term = str_replace(' ','%',$term); + $term2 = str_replace(' ','%',$term2); + $term3 = str_replace(' ','%',$term3); + //$term = $this->app->erp->ConvertForDBUTF8($term); + //$term = str_replace(' ','%',$term); + $filtername = $this->app->Secure->GetGET('filtername'); + + $term = trim($term); + $term2 = trim($term2); + + switch($filtername) + { + case "adressenamegruppe": + $gruppe = $this->app->Secure->GetGET('gruppe'); + $gruppea = explode(',',$gruppe); + $gruppenwhere = ' 0 '; + foreach($gruppea as $v) + { + if($v){ + $gruppenw[] = " ar.parameter = '$v' "; + } + } + if(!empty($gruppenw)) + { + $gruppenwhere = ' ('.implode(' OR ', $gruppenw).') '; + } + + $felder = array('a.email','a.name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT concat(a.id, ' ',a.name) as name2 FROM adresse a + INNER JOIN adresse_rolle ar ON a.id = ar.adresse AND $gruppenwhere AND ar.objekt LIKE 'Gruppe' AND (bis = '0000-00-00' OR bis >= curdate()) + WHERE ($subwhere) AND a.geloescht <> 1 ".$this->app->erp->ProjektRechte('a.projekt')." + ORDER BY a.name LIMIT 20 + "); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name2']}"; + } + break; + + case "adressename": + $arr = $this->app->DB->SelectArr("SELECT a.email, (SELECT name FROM adresse a2 WHERE a2.kundennummer = a.kundennummer ".$this->app->erp->ProjektRechte('a2.projekt')." order by ".($filter_projekt?" a2.projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1) as name2 FROM adresse a WHERE (a.email LIKE '%$term%' OR a.name LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte('a.projekt')." GROUP by email ORDER BY a.email, name2 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name2']}"; + } + break; +/* + +select a.kundennummer, (SELECT name FROM adresse a2 WHERE a2.kundennummer = a.kundennummer order by a2.projekt = 13 DESC, a2.projekt = 0 DESC, projekt LIMIT 1) as name FROM adresse a WHERE a.kundennummer like '10500' group by a.kundennummer +*/ + case "arbeitspaket": + if(trim($this->app->Secure->GetGET('projekt')) != ''){ + $checkprojekt = trim($this->app->Secure->GetGET('projekt')); + }else{ + $checkprojekt = $this->app->User->GetParameter("teilprojekt_filter"); + } + + if(is_numeric($checkprojekt) && $checkprojekt > 0){ + $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE id='" . $checkprojekt . "' LIMIT 1"); + } + + $limit = ''; + if($projektid <=0) + { + $checkprojekt = explode(' ',$checkprojekt); + $projektid = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung='".$checkprojekt[0]."' AND abkuerzung!='' LIMIT 1"); + if($projektid <=0){ + $limit = ' LIMIT 20 '; + } + } + + if($projektid > 0){ + $subwhere = " AND p.id='".$projektid."'"; + } else { + $subwhere=''; + } + + $felder = array('p.abkuerzung', 'ap.aufgabe'); + $subwhere2 = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(ap.id,' ',p.abkuerzung,' ',ap.aufgabe) as name2 FROM arbeitspaket ap LEFT JOIN projekt p ON p.id=ap.projekt WHERE ($subwhere2) AND ap.status!='abgeschlossen' AND ap.aufgabe!='' AND p.id > 0 $subwhere ".$limit); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name2']}"; + } + break; + case "artikeleigenschaften": + $subwhere = $this->app->erp->ProjektRechte('e.projekt'); + $felder = array('name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT name FROM artikeleigenschaften e WHERE ($subwhere) AND geloescht <> 1 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name']}"; + } + break; + case "artikeleigenschaftenwerte": + //$arr = $this->app->DB->SelectArr("SELECT DISTINCT wert FROM artikeleigenschaftenwerte WHERE wert LIKE '%$term%' OR wert LIKE '%$term2%' OR wert LIKE '%$term3%' LIMIT 20"); + //$arr2 = $this->app->DB->SelectArr("SELECT DISTINCT property_value_from FROM article_property_translation WHERE (property_value_from LIKE '%$term%' OR property_value_from LIKE '%$term2%' OR property_value_from LIKE '%$term3') AND language_from = 'DE' LIMIT 20"); + + + $arr = $this->app->DB->SelectArr("(SELECT DISTINCT wert FROM artikeleigenschaftenwerte WHERE wert LIKE '%$term%' OR wert LIKE '%$term2%' OR wert LIKE '%$term3%' LIMIT 20) UNION + (SELECT DISTINCT property_value_from as wert FROM article_property_translation WHERE (property_value_from LIKE '%$term%' OR property_value_from LIKE '%$term2%' OR property_value_from LIKE '%$term3') AND language_from = 'DE' LIMIT 20) ORDER BY wert"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = "{$arr[$i]['wert']}"; + } + break; + case "matrixprodukt_uebersetzungen": + $arr = $this->app->DB->SelectArr("(SELECT DISTINCT name_from AS name FROM matrix_article_translation WHERE name_from LIKE '%$term%' OR name_from LIKE '%$term2%' OR name_from LIKE '%$term3%' LIMIT 20) + UNION (SELECT DISTINCT name_to AS name FROM matrix_article_translation WHERE name_to LIKE '%$term%' OR name_to LIKE '%$term2%' OR name_to LIKE '%$term3%' LIMIT 20) + UNION (SELECT DISTINCT name FROM matrixprodukt_eigenschaftengruppen WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20)"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = "{$arr[$i]['name']}"; + } + break; + case "matrixprodukt_optionen_uebersetzungen": + $arr = $this->app->DB->SelectArr("(SELECT DISTINCT name_from AS name FROM matrix_article_options_translation WHERE name_from LIKE '%$term%' OR name_from LIKE '%$term2%' OR name_from LIKE '%$term3%' LIMIT 10) + UNION (SELECT DISTINCT name_to AS name FROM matrix_article_options_translation WHERE name_to LIKE '%$term%' OR name_to LIKE '%$term2%' OR name_to LIKE '%$term3%' LIMIT 20) + UNION (SELECT DISTINCT name FROM matrixprodukt_eigenschaftenoptionen WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20)"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = "{$arr[$i]['name']}"; + } + break; + case "drucker": + $felder = array('name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT name FROM drucker WHERE $subwhere LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name']}"; + } + break; + case "wiedervorlage_stages": + $felder = array('ws.name','ws.kurzbezeichnung'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr( + "SELECT CONCAT(ws.id, ' ', ws.kurzbezeichnung, ' (', IFNULL(wv.shortname, 'Standard'), ' - ', ws.name, ')') AS `name2` + FROM `wiedervorlage_stages` AS `ws` + LEFT JOIN `wiedervorlage_view` AS `wv` ON ws.view = wv.id + WHERE $subwhere + ORDER BY ws.view, ws.kurzbezeichnung LIMIT 20" + ); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name2']}"; + } + break; + case "wiedervorlage_view": + $felder = array('name', 'shortname'); + $subwhere = $this->AjaxFilterWhere($termorig, $felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', shortname, ' (',name,')') AS name2 FROM wiedervorlage_view WHERE $subwhere ORDER BY shortname LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = "{$arr[$i]['name2']}"; + } + break; + case "etiketten": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',name) as name2 FROM etiketten WHERE name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = "{$arr[$i]['name2']}"; + break; + + + case "laender": + $laender = $this->app->erp->GetSelectLaenderliste(); + $_term = explode(',',$term); + $_term = $_term[count($_term)-1]; + if($laender){ + foreach($laender as $key => $value) + { + if(stripos($key, $_term) !== false || stripos($value, $_term) !== false) + { + $newarr[] = $key.' '.$value; + } + } + } + break; + case "artikelname": + $felder = array('CONCAT(nummer,\' \',name_de)','nummer','name_de'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT name_de FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND ($artikel_freitext1_suche) AND geloescht=0 ORDER by name_de LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name_de']; + } + break; + + case "artikelgruppe": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['typ']; + } + break; + + case "artikelkategorienfull": + $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); + $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); + if($anz) + { + + $artikelbaum = array(); + $allekategorien = $this->app->DB->SelectArr("SELECT id, bezeichnung, parent FROM artikelkategorien WHERE geloescht = 0"); + foreach($allekategorien as $key=>$value){ + if($value['parent'] == 0){ + $artikelbaum[$value['id']] = $value['bezeichnung']; + foreach($allekategorien as $key2=>$value2){ + if(array_key_exists($value2['parent'], $artikelbaum)){ + $artikelbaum[$value2['id']] = $artikelbaum[$value2['parent']]." / ".$value2['bezeichnung']; + } + } + } + } + + $arr = array(); + $i = 0; + + if($term == "" || $term == "%"){ + foreach($artikelbaum as $key=>$value){ + $arr[$i] = $key." ".$value; + $i++; + } + }else{ + foreach($artikelbaum as $key=>$value){ + if(strpos(strtolower($value), strtolower($term)) !== false){ + $arr[$i] = $key.' '.$value; + $i++; + } + } + } + + } + + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + if($i<20){ + $newarr[] = $arr[$i]; + }else{ + break; + } + } + + + break; + + case "artikelkategorien": + + $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); + $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); + if($anz) + { + $arr = $this->app->DB->SelectArr("SELECT a.typ,ar.bezeichnung FROM artikel a LEFT JOIN artikelkategorien ar ON a.typ = concat(ar.id,'_kat') WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ar.bezeichnung LIKE '%$term%' ".$subwhere." GROUP BY a.typ ORDER by ar.bezeichnung "); + if($arr) + { + $typen = false; + foreach($arr as $k => $a) + { + if($a['bezeichnung'])$arr[$k]['typ'] = $a['bezeichnung']; + $typen = $arr[$k]['typ']; + } + array_multisort($typen, $arr); + $last = false; + foreach($arr as $k => $a) + { + if($last == $a['typ']) + { + unset($arr[$k]); + } else { + $last = $a['typ']; + } + } + } + + + } else { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = $arr[$i]['typ']; + } + break; + + case 'alleartikelkategorien': + $anz = $this->app->DB->Select("SELECT count(*) FROM artikelkategorien"); + $subwhere = $this->app->erp->ProjektRechte('ar.projekt'); + if($anz) + { + $arr = $this->app->DB->SelectArr("SELECT ar.bezeichnung as typ FROM artikelkategorien ar WHERE ar.bezeichnung LIKE '%$term%' ".$subwhere." AND ar.geloescht <> 1 ORDER by ar.bezeichnung "); + } else { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT typ FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND typ LIKE '%$term%' ORDER by typ"); + } + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['typ']; + } + break; + case 'xcs_tables': + $felder = array('name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT name FROM xcs_table ORDER BY name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + case "artikeleanbeleg": + $doctype = $this->app->Secure->GetGET('doctype'); + $doctypeid = (int)$this->app->Secure->GetGET('doctypeid'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(if(art.ean <> '', art.ean, art.nummer),' ',art.name_de) as name FROM artikel art + INNER JOIN $doctype"."_position ap ON ap.artikel = art.id AND $doctype = '$doctypeid' + WHERE art.geloescht=0 AND ($subwhere) AND art.geloescht=0 AND art.intern_gesperrt!=1 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "artikelnummerbeleg": + $doctype = $this->app->Secure->GetGET('doctype'); + $doctypeid = (int)$this->app->Secure->GetGET('doctypeid'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(art.nummer,' ',art.name_de) as name FROM artikel art + INNER JOIN $doctype"."_position ap ON ap.artikel = art.id AND $doctype = '$doctypeid' + WHERE art.geloescht=0 AND ($artikel_freitext1_suche) AND art.geloescht=0 AND art.intern_gesperrt!=1 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "spracheniso": + $arr = $this->app->DB->SelectArr('SELECT iso FROM sprachen'); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = $arr[$i]['iso']; + } + break; + case "geschaeftsbrief_vorlagen": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',subjekt,' (',sprache,')') as name FROM geschaeftsbrief_vorlagen"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = $arr[$i]['name']; + } + break; + + case "artikeleinheit": + //$arr = $this->app->DB->SelectArr("SELECT DISTINCT einheit_de FROM artikeleinheit WHERE firma='".$this->app->User->GetFirma()."' AND einheit_de LIKE '%$term%' ORDER by einheit_de"); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT einheit_de FROM artikeleinheit WHERE einheit_de LIKE '%$term%' ORDER by einheit_de"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['einheit_de']; + break; + + + + case "ihrebestellnummer": + $adresse = $this->app->Secure->GetGET('adresse'); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT ihrebestellnummer FROM auftrag WHERE ihrebestellnummer LIKE '%$term%' AND adresse='$adresse' ORDER by ihrebestellnummer "); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['ihrebestellnummer']; + } + break; + + + case "accountart": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT art FROM adresse_accounts WHERE art LIKE '%$term%' ORDER by art"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['art']; + } + break; + + + case "ansprechpartneradresse": + $adressId = $this->app->Secure->GetGET('adresse'); + + if(is_numeric($adressId) && $adressId > 0){ + $adressId = $this->app->DB->Select("SELECT id FROM adresse WHERE id = '$adressId' LIMIT 1"); + } + + $limit = ''; + if($adressId <= 0){ + $adresse = explode(' ', $adressId); + $adressId = $this->app->DB->Select("SELECT id FROM adresse WHERE name = '".$adresse[0]."' AND name != '' LIMIT 1"); + if($adressId <= 0){ + $limit = ' LIMIT 20 '; + } + } + + if($adressId > 0){ + $subwhere = " AND a.id = '$adressId'"; + }else{ + $subwhere = ''; + } + + $felder = array('an.name'); + $subwhere2 = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(an.id, ' ', an.name, ' ', IF(a.lieferantennummer,CONCAT('(', a.name, ', Kdr: ', a.kundennummer, ' Liefr: ', a.lieferantennummer, ')'), CONCAT('(', a.name, ', Kdr: ', a.kundennummer, ')'))) AS name + FROM ansprechpartner an + LEFT JOIN adresse a ON an.adresse = a.id + WHERE ($subwhere2) AND a.id > 0 AND a.geloescht = 0 $subwhere ".$this->app->erp->ProjektRechte('a.projekt').$limit); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = "{$arr[$i]['name']}"; + } + break; + + case "ansprechpartner": + $adresse = $this->app->Secure->GetGET('adresse'); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT name FROM ansprechpartner WHERE adresse='$adresse' AND name LIKE '%$term%' AND geloescht <> 1 ORDER by name"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "hersteller": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT hersteller FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND hersteller LIKE '%$term%' ORDER by hersteller"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['hersteller']; + break; + case "rmakategorien": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM rma_vorlagen_kategorien WHERE bezeichnung LIKE '%$term%' ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "spedition_einstellungen_feld": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT feld FROM spedition_einstellungen WHERE aktiv=1 AND feld LIKE '%$term%' ORDER by feld"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['feld']; + } + break; + + case "zeiterfassung_beschreibung": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT beschreibung FROM zeiterfassung_kosten WHERE beschreibung LIKE '%$term%' ORDER by beschreibung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['beschreibung']; + } + break; + + case "eigenschaften_vorlagen": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM eigenschaften_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "ticketnummer": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(t.schluessel, ' Name: ', t.kunde, ' Betr: ', t.betreff) as schluessel FROM ticket t WHERE t.schluessel LIKE '%$term%' OR t.kunde LIKE '%$term%' OR t.betreff LIKE '%$term%' ORDER BY t.schluessel"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['schluessel']; + } + break; + + case "abosammelrechnungen": + $id = $this->app->Secure->GetGET('adresse'); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', bezeichnung) as bezeichnung FROM adresse_abosammelrechnungen WHERE bezeichnung LIKE '%$term%' AND adresse = '$id' ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + + case "arbeitsplatzgruppe": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ',bezeichnung) as bezeichnung FROM arbeitsplatzgruppen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + case "artikelarbeitsanweisung_vorlagen": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM artikelarbeitsanweisung_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + case "artikelfunktionsprotokoll_vorlagen": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM artikelfunktionsprotokoll_vorlagen WHERE bezeichnung LIKE '%$term%' AND aktiv = 1 ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + case "fahrtenbuch_kennzeichen": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT kennzeichen FROM fahrtenbuch_fahrzeuge WHERE kennzeichen LIKE '%$term%' AND aktiv = 1 ORDER BY kennzeichen"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['kennzeichen']; + break; + + case "fahrtenbuch_strecke": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT strecke FROM fahrtenbuch_vorlagen WHERE (strecke LIKE '%$term%' OR strecke LIKE '%$term2%' OR strecke LIKE '%$term3%') AND aktiv = 1 ORDER BY strecke"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['strecke']; + break; + + case "verpackungsgruppe": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT verpackungsgruppe FROM verpackungen_details WHERE verpackungsgruppe LIKE '%$term%' ORDER by verpackungsgruppe"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['verpackungsgruppe']; + break; + + case "dropshipping_gruppe": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM dropshipping_gruppe WHERE bezeichnung LIKE '%$term%' ORDER BY bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + + + case "layoutvorlage": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id, ' ', name) AS name FROM layoutvorlagen WHERE name LIKE '%$term%' ORDER BY name"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "uservorlage": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT bezeichnung FROM uservorlage WHERE bezeichnung LIKE '%$term%' ORDER by bezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + + case "lagergrund": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT TRIM(REPLACE(REPLACE(referenz,'Umlagern fü :',''),'Differenz:','')) as ergebnis FROM lager_bewegung WHERE REPLACE(referenz,'Differenz:','') LIKE '%$term%' AND referenz NOT LIKE '%Inventur%' AND referenz NOT LIKE '%Charge%' AND referenz NOT LIKE '%Lieferschein%' + AND referenz NOT LIKE '%Manuell%' AND referenz NOT LIKE '%Wareneingang%' AND referenz NOT LIKE '%Lieferungen%' LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['ergebnis']; + break; + + + + case "auftrag_zahlungseingang": + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' ',REPLACE(a.name,',',''),' ',r.internet,' GESAMT: ',r.gesamtsumme,' (Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status) as name + FROM auftrag r LEFT JOIN adresse a ON a.id=r.adresse WHERE r.belegnr!='' + AND (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%' OR IFNULL(r.internet,'') LIKE '%$term%' ) ORDER by r.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "rechnung_zahlungseingang": + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' Soll:',r.soll,' Ist:',r.ist,' ',' Diff:',(r.soll-r.ist)*-1,' ', + if(r.zahlungszielskonto > 0,if(isnull(r.skontobetrag),CONCAT('SK:',r.zahlungszielskonto,'%(',FORMAT((r.soll/100)*r.zahlungszielskonto,2),') '),concat('SK:',FORMAT(100*r.skontobetrag / r.soll,2),'%(',FORMAT(r.skontobetrag,2),')')),''),REPLACE(a.name,',',''),'(Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status + ,IF(IFNULL(ab.internet,'')!='',CONCAT(' Intenet: ',ab.internet),'') + ) as name + FROM rechnung r + LEFT JOIN auftrag ab ON r.auftragid = ab.id + LEFT JOIN adresse a ON a.id=r.adresse + WHERE r.belegnr!='' AND + (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' + OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%' + OR IFNULL(ab.internet,'') LIKE '%$term%' + ) + AND r.zahlungsstatus!='bezahlt' + ORDER by r.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "gutschrift_zahlungseingang": + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' SOLL: ',r.soll,' IST:',r.ist,' ',REPLACE(a.name,',',''),' (Kunde ',a.kundennummer,') vom ',DATE_FORMAT(r.datum,'%d.%m.%Y'),' Status: ',r.status) as name + FROM gutschrift r LEFT JOIN adresse a ON a.id=r.adresse WHERE r.belegnr!='' AND (a.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR a.kundennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') AND (r.manuell_vorabbezahlt IS NULL OR r.manuell_vorabbezahlt='0000-00-00') ORDER by r.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + + case "gutschrift": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) AS name + FROM gutschrift WHERE belegnr != '' AND belegnr != '0' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." ORDER BY belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "angebot": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM angebot WHERE belegnr!='' AND belegnr!='0' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "bestellung": + $status = $this->app->Secure->GetGET('status'); + switch($status) { + case 'freigegeben': + case 'abgeschlossen': + case 'versendet': + case 'strorniert': + break; + default: + $status = ''; + break; + } + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM bestellung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".($status != ''?" AND status = '".$status."' ":'').$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "preisanfrage": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM preisanfrage WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte("projekt")." ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "bestellunggesamtsumme": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',".$this->app->erp->FormatPreis("gesamtsumme",2).",' ',waehrung,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM bestellung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + + case "auftrag_position_dienstleistung": + $arr = $this->app->DB->SelectArr("SELECT ap.menge, ap.id as auftragspositionid,CONCAT(a.belegnr,'-',ap.sort,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y'),' ',ap.bezeichnung) as name + FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag LEFT JOIN artikel art ON art.id=ap.artikel WHERE art.dienstleistung=1 AND a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR ap.bezeichnung LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ORDER by a.belegnr DESC LIMIT 20"); + foreach($arr as $value){ + $sollzeit = number_format($value['menge'],2); + $istzeit = $this->app->DB->Select("SELECT SUM(Time_to_sec(Timediff(z.von,z.bis))/3600) FROM zeiterfassung z WHERE z.auftragpositionid = '{$value['auftragspositionid']}'"); + $newarr[] = $value['name'] . " ( " . number_format(($istzeit*-1),2) . " von " . $sollzeit . ")"; + } + break; + + case "alle_auftrag_positionen": + $arr = $this->app->DB->SelectArr("SELECT ap.menge, ap.id as auftragspositionid,CONCAT(a.belegnr,'-',ap.sort,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y'),' ',ap.bezeichnung) as name + FROM auftrag_position ap LEFT JOIN auftrag a ON a.id=ap.auftrag WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR ap.bezeichnung LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ORDER by a.belegnr DESC LIMIT 20"); + foreach($arr as $value){ + $sollzeit = number_format($value['menge'],2); + $istzeit = $this->app->DB->Select("SELECT SUM(Time_to_sec(Timediff(z.von,z.bis))/3600) FROM zeiterfassung z WHERE z.auftragpositionid = '{$value['auftragspositionid']}'"); + $newarr[] = $value['name'] . " ( " . number_format(($istzeit*-1),2) . " von " . $sollzeit . ")"; + } + break; + + case "auftragihrebestellnummer": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y'), + if(ihrebestellnummer!='',CONCAT(' ',ihrebestellnummer),''),if(internebezeichnung!='',CONCAT(' ',internebezeichnung),'')) as name + FROM auftrag WHERE belegnr!='0' AND belegnr!='' AND status!='angelegt' AND + (name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' OR ihrebestellnummer LIKE '%$term%' OR internebezeichnung LIKE '%$term%' + OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "auftrag": + $status = $this->app->Secure->GetGET('status'); + switch($status) { + case 'freigegeben': + case 'abgeschlossen': + case 'strorniert': + break; + default: + $status = ''; + break; + } + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.belegnr,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y')) as name + FROM auftrag a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." ".($status != ''?" AND a.status = '".$status."' ":'')." ORDER by a.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "auftragmitrechnung": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.belegnr,' ',a.name,' ',DATE_FORMAT(a.datum,'%d.%m.%Y')) as name + FROM auftrag a + INNER JOIN rechnung r ON a.id = r.auftragid AND r.belegnr <> '' + WHERE a.belegnr!='0' AND a.belegnr!='' AND (a.name LIKE '%$term%' OR a.belegnr LIKE '%$term%' OR DATE_FORMAT(a.datum,'%Y-%m-%d') LIKE '%$term%') GROUP BY a.id ORDER by a.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "auftrag_freigegeben": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM auftrag WHERE belegnr!='0' AND belegnr!='' AND status='freigegeben' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "rechnung_freigegeben": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM rechnung WHERE belegnr!='0' AND belegnr!='' AND status='freigegeben' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "produktion": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM produktion WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + + case "arbeitsnachweis": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM arbeitsnachweis WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "lieferschein": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM lieferschein WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case 'rechnung': + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM rechnung WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + case 'retoure': + $arr = $this->app->DB->SelectArr("SELECT CONCAT(belegnr,' ',name,' ',DATE_FORMAT(datum,'%d.%m.%Y')) as name + FROM retoure WHERE belegnr!='0' AND belegnr!='' AND (name LIKE '%$term%' OR belegnr LIKE '%$term%' OR DATE_FORMAT(datum,'%Y-%m-%d') LIKE '%$term%') ORDER by belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "rechnungmitauftrag": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(r.belegnr,' ',r.name,' ',DATE_FORMAT(r.datum,'%d.%m.%Y')) as name + FROM rechnung r + INNER JOIN auftrag a ON r.auftragid = a.id + LEFT JOIN projekt p ON p.id=r.projekt + WHERE r.belegnr!='0' AND r.belegnr!='' AND (r.name LIKE '%$term%' OR r.belegnr LIKE '%$term%' OR DATE_FORMAT(r.datum,'%Y-%m-%d') LIKE '%$term%') ".$this->app->erp->ProjektRechte()." GROUP BY r.id ORDER by r.belegnr DESC LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "vpeartikel": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT vpe FROM verkaufspreise WHERE geloescht=0 AND vpe LIKE '%$term%' ORDER by vpe"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['vpe']; + break; + + case "herstellerlink": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT herstellerlink FROM artikel WHERE geloescht=0 AND intern_gesperrt!=1 AND herstellerlink LIKE '%$term%' ORDER by herstellerlink"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['herstellerlink']; + break; + + + case 'lagerplatz': + case 'lagerplatzstandardlager': + $onlyStdLager = $filtername === 'lagerplatzstandardlager'; + $stdLager = 0; + if($rmodule === 'produktionszentrum' || $rmodule==='produktion') { + if($onlyStdLager > 0 && $rid > 0) { + $stdLager = (int)$this->app->DB->Select( + sprintf( + 'SELECT standardlager FROM produktion WHERE id = %d', + $rid + ) + ); + } + } + $withzwischenlager = $this->app->Secure->GetGET('zwischenlager'); + $withstadardlager = $this->app->Secure->GetGET('withstandardlager'); + $sql = "SELECT lp.kurzbezeichnung + FROM lager_platz AS lp + LEFT JOIN lager AS l ON l.id=lp.lager + WHERE lp.geloescht=0 AND ('$stdLager' = '0' OR l.id = '$stdLager') + AND lp.kurzbezeichnung LIKE '%$term%' ". + $this->app->erp->ProjektRechte('l.projekt').' + ORDER BY lp.kurzbezeichnung'; + $arr = $this->app->DB->SelectArr($sql); + if(empty($arr)) { + $arr = []; + } + if($withzwischenlager) { + $arr2 = $this->app->DB->SelectArr( + "SELECT 'Zwischenlager' AS kurzbezeichnung FROM (SELECT 1) a WHERE 'Zwischenlager' LIKE '%$term%' " + ); + if(!empty($arr2)) { + $arr = array_merge($arr, $arr2); + } + } + if($withstadardlager) { + $arr2 = $this->app->DB->SelectArr( + "SELECT 'Standardlager' AS kurzbezeichnung FROM (SELECT 1) a WHERE 'Standardlager' LIKE '%$term%'" + ); + if(!empty($arr2)) { + $arr = array_merge($arr, $arr2); + } + } + if(!empty($arr)) { + sort($arr); + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['kurzbezeichnung']; + } + break; + case 'artikelfremdnummern': + $article = explode(' ', $this->app->Secure->GetGET('artikel')); + $article = reset($article); + $articleId = (int)$this->app->Secure->GetGET('artikelid'); + $bezeichnung = $this->app->Secure->GetGET('bezeichnung'); + $shopid = (int)$this->app->Secure->GetGET('shopid'); + if(empty($articleId) && !empty($article)) { + $articleId = $this->app->DB->Select( + sprintf( + "SELECT id + FROM artikel + WHERE nummer = '%s' AND nummer <> '' AND geloescht <> 1 + ORDER BY intern_gesperrt + LIMIT 1", + $article + ) + ); + } + if(!empty($articleId)) { + $newarr = $this->app->DB->SelectFirstCols( + sprintf( + "SELECT DISTINCT af.nummer + FROM artikelnummer_fremdnummern AS af + WHERE af.artikel = %d AND af.aktiv = 1 AND (af.bezeichnung = '%s' OR '%s' = '') + AND af.nummer LIKE '%%%s%%' AND af.shopid = %d", + $articleId, $bezeichnung, $bezeichnung, $term, $shopid + ) + ); + } + + break; + case "bezeichnungfremdnr": + $arr = $this->app->DB->SelectArr('SELECT DISTINCT af.bezeichnung FROM artikelnummer_fremdnummern af'); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + if(!in_array('ID', $newarr)){ + $newarr[] = 'ID'; + } + if(!in_array('SKU', $newarr)){ + $newarr[] = 'SKU'; + } + + break; + case "lagerplatzprojekt": + $arr = $this->app->DB->SelectArr('SELECT lp.kurzbezeichnung + FROM lager_platz AS lp + INNER JOIN lager l ON lp.lager = l.id AND (l.projekt = 0 OR (1 '.$this->app->erp->ProjektRechte('l.projekt').")) + WHERE lp.geloescht=0 AND lp.kurzbezeichnung LIKE '%$term%' + ORDER BY lp.kurzbezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['kurzbezeichnung']; + } + break; + case "sperrlagerplatz": + $arr = $this->app->DB->SelectArr("SELECT kurzbezeichnung FROM lager_platz WHERE geloescht=0 AND sperrlager = 1 AND kurzbezeichnung LIKE '%$term%' ORDER by kurzbezeichnung"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['kurzbezeichnung']; + break; + case 'lagerplatzartikel': + $artikel = (int)$this->app->Secure->GetGET('artikel'); + $pos = (int)$this->app->Secure->GetGET('pos'); + $doctype = strtolower($this->app->Secure->GetGET('doctype')); + $join = ''; + if($pos > 0 && $doctype === 'lieferschein' && $artikel > 0) { + $seriennummern = $this->app->DB->Select( + sprintf( + 'SELECT `seriennummern` FROM artikel WHERE id = %d LIMIT 1', + $artikel + ) + ); + if($seriennummern !== 'keine' && !empty($seriennummern)) { + $cSn = $this->app->DB->SelectArr( + sprintf( + 'SELECT IFNULL(COUNT(id), 0) + FROM `beleg_chargesnmhd` + WHERE doctype = \'%s\' AND pos = %d AND type = \'sn\' AND wert <> \'\' + ', + $doctype, $pos + ) + ); + $position = $this->app->DB->SelectRow( + sprintf('SELECT menge, geliefert FROM lieferschein_position WHERE id = %d', + $pos + ) + ); + if($cSn == $position['menge']) { + $join = sprintf(' INNER JOIN + ( + SELECT lagerplatz + FROM `beleg_chargesnmhd` + WHERE doctype = \'%s\' AND parameter = %d + GROUP BY lagerplatz + ) AS bc ON lp.id = bc.lagerplatz ', + $doctype, $pos + ); + } + } + } + $arr = $this->app->DB->SelectArr( + sprintf('SELECT lp.kurzbezeichnung + FROM lager_platz AS lp + INNER JOIN lager_platz_inhalt AS lpi on lp.id = lpi.lager_platz + %s + WHERE lpi.artikel=%d AND lp.geloescht=0 AND lp.kurzbezeichnung LIKE \'%%%s%%\' + GROUP BY lp.kurzbezeichnung + ORDER by lp.kurzbezeichnung', + $join, $artikel, $term + ) + ); + if(empty($arr)) { + break; + } + foreach($arr as $row) { + $newarr[] = $row['kurzbezeichnung']; + } + break; + + case "lager": + $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." ORDER by 1"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + case 'lager_produktion': + $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l JOIN lager_platz lp ON l.id = lp.lager WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." AND lp.allowproduction = 1 ORDER BY 1"); + + if(empty($arr)){ + $arr = $this->app->DB->SelectArr("SELECT l.bezeichnung FROM lager l WHERE l.geloescht=0 AND l.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("l.projekt")." ORDER by 1"); + } + + $carr = !empty($arr)?count($arr):0; + for($i=0; $i < $carr; $i++) + $newarr[] = $arr[$i]['bezeichnung']; + break; + + case "aktionscode": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(code,' ',beschriftung) as name FROM aktionscode_liste + WHERE (beschriftung LIKE '%$term%' OR code LIKE '%$term%' OR code LIKE '%$term2%' OR code LIKE '%$term3%') AND ausblenden!=1 ORDER by code"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "waehrung": + if($this->app->DB->Select("SELECT id FROM waehrung_umrechnung LIMIT 1")) { + + + $arr = $this->app->DB->SelectArr(" + ( + SELECT DISTINCT waehrung_nach as name FROM waehrung_umrechnung + WHERE (waehrung_nach LIKE '%$term%') ORDER by waehrung_nach + ) + UNION + ( + SELECT DISTINCT waehrung_von as name FROM waehrung_umrechnung + WHERE (waehrung_von LIKE '%$term%') + + ORDER by waehrung_von + ) + ORDER by name"); + }else{ + + $waehrungen = $this->app->erp->GetWaehrung(); + if($waehrungen) + { + foreach($waehrungen as $v) + { + if($v) { + $sqla[] = " (SELECT '$v' as name FROM (SELECT 1) AS X WHERE + '$v' LIKE '%$term%' + ) "; + } + } + $arr = $this->app->DB->SelectArr("SELECT t.name FROM ( ".implode(' UNION ', $sqla)." ) t ORDER BY name "); + } + } + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + + + break; + + case "sachkonto": + $cmd = $this->app->Secure->GetGET("cmd"); + + if($cmd!="") $projekt = $this->app->DB->Select("SELECT id FROM projekt WHERE abkuerzung='".$this->app->DB->real_escape_string($cmd)."' LIMIT 1"); + + $checkprojekt = ($projekt > 0?$this->app->DB->Select("SELECT COUNT(id) FROM kontorahmen WHERE projekt='$projekt'"):0); + $checkprojektnull = $this->app->DB->Select("SELECT COUNT(id) FROM kontorahmen WHERE projekt=0 OR projekt IS NULL"); + + if($checkprojekt > 0) + { + $andprojekt = "AND (projekt='$projekt' OR projekt = 0 OR projekt IS NULL)"; + } else { + if($checkprojektnull>0) + { + $andprojekt = " AND (projekt=0 OR projekt IS NULL) "; + } else { + $andprojekt = ""; + } + } + + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(sachkonto,' ',beschriftung) as name FROM kontorahmen + WHERE (beschriftung LIKE '%$term%' OR sachkonto LIKE '%$term%' OR sachkonto LIKE '%$term2%' OR sachkonto LIKE '%$term3%' OR beschriftung LIKE '%$term2%' OR beschriftung LIKE '%$term3%') AND ausblenden!=1 $andprojekt ORDER by sachkonto"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "lieferbedingungen": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(lieferbedingungen) as name FROM lieferbedingungen + WHERE (lieferbedingungen LIKE '%$term%' OR lieferbedingungen LIKE '%$term2%' OR lieferbedingungen LIKE '%$term3%') ORDER by lieferbedingungen"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "zeiterfassungvorlage": + $arr = $this->app->DB->SelectArr("SELECT vorlage as name FROM zeiterfassungvorlage + WHERE (vorlage LIKE '%$term%' OR vorlage LIKE '%$term2%' OR vorlage LIKE '%$term3%') AND ausblenden!=1 ORDER by vorlage"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + case "zeiterfassungvorlagedetail": + $vorlage = $this->app->Secure->GetPOST('vorlage'); + $arr = $this->app->DB->SelectRow("SELECT vorlagedetail as name, art, projekt, teilprojekt, kunde, abrechnen FROM zeiterfassungvorlage WHERE vorlage = '$vorlage' LIMIT 1"); + + if($arr['projekt'] > 0){ + $arr['projekt'] = $this->app->DB->Select("SELECT CONCAT(abkuerzung, ' ', name) FROM projekt WHERE id = '".$arr['projekt']."' LIMIT 1"); + }else{ + $arr['projekt'] = ''; + } + + if($arr['teilprojekt'] > 0){ + $projektid = $this->app->DB->Select("SELECT projekt FROM arbeitspaket WHERE id = '".$arr['teilprojekt']."' LIMIT 1"); + if($projektid > 0){ + $projektabk = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id = '$projektid' LIMIT 1"); + if($projektabk != ""){ + $arr['teilprojekt'] = $this->app->DB->Select("SELECT CONCAT('".$arr['teilprojekt']."', ' ', '$projektabk', ' ', aufgabe) FROM arbeitspaket WHERE id = '".$arr['teilprojekt']."' LIMIT 1"); + }else{ + $arr['teilprojekt'] = ''; + } + }else{ + $arr['teilprojekt'] = ''; + } + }else{ + $arr['teilprojekt'] = ''; + } + + if($arr['kunde'] > 0){ + $arr['kunde'] = $this->app->DB->Select("SELECT CONCAT(kundennummer, ' ', name) FROM adresse WHERE id = '".$arr['kunde']."' LIMIT 1"); + } + + if($arr['art'] == ''){ + $arr['art'] = 'Arbeit'; + } + + + $newarr[] = $arr['name']; + $newarr[] = $arr['art']; + $newarr[] = $arr['projekt']; + $newarr[] = $arr['teilprojekt']; + $newarr[] = $arr['kunde']; + $newarr[] = $arr['abrechnen']; + break; + case "zeiterfassungprojektdetail": + $projekt = explode(' ',$this->app->Secure->GetPOST('projekt')); + $projektkennung = $projekt[0]; + + $kunde = $this->app->DB->Select("SELECT CONCAT(a.kundennummer,' ',a.name,' (',a.ort,')') AS kunde FROM projekt p JOIN adresse a ON p.kunde=a.id WHERE a.geloescht=0 AND p.abkuerzung='$projektkennung' LIMIT 1"); + $newarr[] = $kunde; + break; + + case "zolltarifnummer": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM zolltarifnummer WHERE beschreibung LIKE '%$term%' OR nummer LIKE '%$term%' ORDER by nummer"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + + case "kostenstelle": + $felder = array('CONCAT(nummer,\' \',beschreibung)','nummer','beschreibung'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM kostenstellen WHERE $subwhere ORDER by nummer"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "verrechnungsart": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',beschreibung) as name FROM verrechnungsart WHERE beschreibung LIKE '%$term%' OR nummer LIKE '%$term%' ORDER by nummer"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + case "kundenrechnung": + case "kundenauftrag": + case "kundenlieferschein": + case "kundenangebot": + case "kundenproformarechnung": + $adresse = (int)$this->app->Secure->GetGET('adresse'); + if(!$adresse) + { + $kunde = explode(' ',$this->app->Secure->GetGET('kunde')); + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer = '".$kunde[0]."' AND kundennummer <> '' LIMIT 1"); + } + $beleg = str_replace('kunden','',$filtername); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',if(belegnr <> '',belegnr,'ENTWURF'),' ',kundennummer,' ',name) as name FROM $beleg WHERE (belegnr LIKE '%$term%' OR name LIKE '%$term%' OR kundennummer LIKE '$%term%') AND (status = 'angelegt' OR status = 'freigegeben') + ".($adresse?" AND adresse = '$adresse' ":'')." ".$this->app->erp->ProjektRechte('projekt')." + ORDER by belegnr LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + case "lieferantenpreisanfrage": + case "lieferantenbestellung": + $adresse = (int)$this->app->Secure->GetGET('adresse'); + if(!$adresse) + { + $lieferant = explode(' ',$this->app->Secure->GetGET('lieferant')); + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE lieferantennummer = '".$lieferant[0]."' AND lieferantennummer <> '' LIMIT 1"); + } + $beleg = str_replace('lieferanten','',$filtername); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',if(belegnr <> '',belegnr,'ENTWURF'),' ',lieferantennummer,' ',name) as name FROM $beleg WHERE (belegnr LIKE '%$term%' OR name LIKE '%$term%' OR lieferantennummer LIKE '$%term%') AND (status = 'angelegt' OR status = 'freigegeben') + ".($adresse?" AND adresse = '$adresse' ":'')." ".$this->app->erp->ProjektRechte('projekt')." + ORDER by belegnr LIMIT 20" ); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['name']; + break; + + // Suche nach einzelner Artikelnummer + case 'artikelnummer': + case 'artikelnummerseriennummer': + $isSeriennummer = $filtername === 'artikelnummerseriennummer'; + $tmp_where = ''; + if($isSeriennummer) { + $tmp_where = " AND seriennummern <> '' AND seriennummern <> 'keine' "; + } + $projekt = $this->app->Secure->GetGET('projekt'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + //$checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); + //$eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); + + //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = " AND projekt='$checkprojekt' "; + //else $tmp_where = ""; + + + $arr = $this->app->DB->SelectArr( + "SELECT CONCAT(nummer,' ',name_de) as `name` + FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where ". + $this->app->erp->ProjektRechte('art.projekt'). ' LIMIT 20' + ); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "artikelnummerstueckliste": + $tmp_where = ''; + $projekt = $this->app->Secure->GetGET('projekt'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + + $artikel_artikelnummer_suche = $this->app->erp->Firmendaten('artikel_artikelnummer_suche'); + + if($artikel_artikelnummer_suche){ + $felder[] = 'e.bestellnummer'; + $felder[] = 'v.kundenartikelnummer'; + } + + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + if($artikel_artikelnummer_suche){ + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(nummer,' ',name_de) as name + FROM artikel AS art + LEFT JOIN einkaufspreise e ON art.id = e.artikel AND e.bestellnummer != '' AND e.geloescht = 0 AND e.bestellnummer IS NOT NULL AND + (IFNULL(e.gueltig_bis,'0000-00-00') > NOW() OR IFNULL(e.gueltig_bis,'0000-00-00')='0000-00-00') + LEFT JOIN verkaufspreise v ON art.id = v.artikel AND v.kundenartikelnummer != '' AND v.geloescht = 0 AND v.kundenartikelnummer IS NOT NULL AND + (IFNULL(v.gueltig_bis,'0000-00-00') > NOW() OR IFNULL(v.gueltig_bis,'0000-00-00')='0000-00-00') + WHERE art.geloescht=0 AND ($subwhere) AND art.intern_gesperrt!=1 $tmp_where ". + $this->app->erp->ProjektRechte('art.projekt'). "LIMIT 20"); + }else{ + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where ". + $this->app->erp->ProjektRechte('art.projekt'). "LIMIT 20"); + } + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + + case "artikelnummermitseriennummern": + $tmp_where = ''; + $projekt = $this->app->Secure->GetGET('projekt'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND seriennummern<>'keine' $tmp_where ". + $this->app->erp->ProjektRechte('art.projekt'). 'LIMIT 20'); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "artikelmengeinbeleg": + $beleg = $this->app->Secure->GetGet('beleg'); + $belegid = $this->app->Secure->GetGet('id'); + $artikel = explode(' ',$this->app->Secure->GetPost('vorlage')); + $artikelnummer = $artikel[0]; + $artikelid = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer='$artikelnummer' AND geloescht=0 LIMIT 1"); + if($artikelid){ + $menge = $this->app->DB->Select('SELECT '.$this->app->erp->FormatMenge('SUM(menge)').' FROM '.$beleg."_position WHERE artikel='$artikelid' AND $beleg='$belegid'"); + } + if(!$menge){ + $menge='0'; + } + + $newarr[] = $menge; + break; + // Suche nach mehreren Artikelnummern (kommagetrennt) + case "artikelnummer_multi": + $tmp_where = ''; + if(strpos($term,',')!==false) { + $term = substr($term, (strripos($term,',')+1)); + } + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "portoartikel": + $tmp_where = ''; + //$projekt = $this->app->Secure->GetGET('projekt'); + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + //$checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); + //$eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); + + //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = " AND projekt='$checkprojekt' "; + //else $tmp_where = ""; + + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND porto = 1 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "juststuecklistenartikel": + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND stueckliste = 1 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "stuecklistenartikel": + $projekt = $this->app->Secure->GetGET('projekt'); + $tmp_where = ''; + if($projekt != '') + { + if(is_numeric($projekt)) + { + $tmp_where = " AND projekt = '$projekt' "; + }else{ + $projekt = $this->app->DB->Select("SELECT id FROM projekt WHERE ifnull(geloescht,0) = 0 AND abkuerzung = '$projekt' LIMIT 1"); + if($projekt){ + $tmp_where = " AND projekt = '$projekt' "; + } + } + } + $juststueckliste = $this->app->Secure->GetGET('juststueckliste'); + if($juststueckliste) + { + $swhere = ''; + }else{ + $swhere = ' AND juststueckliste = 0 '; + } + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel AS art WHERE geloescht=0 AND ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 AND stueckliste = 1 $swhere $tmp_where LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++) { + $newarr[] = $arr[$i]['name']; + } + break; + break; + + case "artikelstueckliste": + $stuecklistenartikel = $this->app->Secure->GetGET('stuecklistenartikel'); + $artikelID = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer = '$stuecklistenartikel'"); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer,' ',a.name_de) AS name FROM artikel a LEFT JOIN stueckliste s ON a.id=s.artikel WHERE s.stuecklistevonartikel='$artikelID' AND a.geloescht=0 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++){ + $newarr[] = $arr[$i]['name']; + } + break; + + case "artikelinstueckliste": + $stuecklistenartikel = trim($this->app->Secure->GetGET('art')); + if($stuecklistenartikel != ''){ + $stuecklistenartikel = explode(' ', $stuecklistenartikel); + $stuecklistenartikelnr = $stuecklistenartikel[0]; + $stuecklistenartikelid = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer = '$stuecklistenartikelnr' LIMIT 1"); + if($stuecklistenartikelid != "" && $stuecklistenartikelid > 0){ + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer, ' ', a.name_de) as name FROM artikel a LEFT JOIN stueckliste s ON a.id = s.artikel WHERE a.geloescht = 0 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR a.herstellernummer LIKE '%$term%' OR a.ean LIKE '%$term%') AND a.intern_gesperrt != 1 AND s.stuecklistevonartikel = '$stuecklistenartikelid'"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + } + } + break; + + case "partlistfrom": + $article_id = $this->app->Secure->GetGET('article_id'); + $arr = $this->app->DB->SelectArr(" + SELECT concat(art.nummer,' ',art.name_de) as name + FROM artikel art + INNER JOIN (SELECT DISTINCT stuecklistevonartikel FROM stueckliste WHERE artikel = '$article_id') s + ON art.id = s.stuecklistevonartikel + WHERE (concat(art.nummer,' ',art.name_de) LIKE '%$term%' OR concat(art.nummer,' ',art.name_de) LIKE '%$term2%' OR concat(art.nummer,' ',art.name_de) LIKE '%$term3%') + "); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = $arr[$i]['name']; + } + break; + + break; + + case "artikelnummertagespreise": + $projekt = $this->app->Secure->GetGET('projekt'); + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + $checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); + $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); + + if($checkprojekt > 0 && $eigenernummernkreis=='1') + { + $tmp_where = " AND projekt='$checkprojekt' "; + } + else { + $tmp_where = ''; + } + + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name FROM artikel WHERE geloescht=0 AND tagespreise = 1 AND (nummer LIKE '%$term%' OR name_de LIKE '%$term%' OR nummer LIKE '%$term2%' OR name_de LIKE '%$term2%' OR nummer LIKE '%$term3%' OR name_de LIKE '%$term3%' OR herstellernummer LIKE '%$term%' OR ean LIKE '%$term%' ".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") AND geloescht=0 AND intern_gesperrt!=1 $tmp_where LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "keinelagerartikelnummer": + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name + FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 + AND (lagerartikel!='1' OR dienstleistung=1) AND porto!=1 AND stueckliste!=1 LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "lagerartikelnummer": + + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name + FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 + AND lagerartikel='1' LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "lagerartikelnummerohnechargemhdseriennummer": + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name + FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 + AND lagerartikel='1' AND chargenverwaltung = 0 AND mindesthaltbarkeitsdatum <> 1 AND (seriennummern = '' OR seriennummern = 'keine') ".$this->app->erp->ProjektRechte('projekt')." LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "lagerartikelkategorie": + $felder = array('bezeichnung'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT bezeichnung FROM artikelkategorien WHERE ($subwhere) AND geloescht=0"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "chargenartikel": + $felder = array('art.nummer','art.name_de','art.herstellernummer','art.ean','CONCAT(art.nummer,\' \',art.name_de)'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(nummer,' ',name_de) as name + FROM artikel AS art WHERE ($subwhere) AND geloescht=0 AND intern_gesperrt!=1 + AND chargenverwaltung > 0 ".$this->app->erp->ProjektRechte('projekt')." LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "artikelnummerlager": + $lager_platz = (int)$this->app->Secure->GetGET('lager_platz'); + $lwhere = ''; + if($lager_platz){ + $lwhere = " and lpi.lager_platz = '$lager_platz' "; + } + $felder = array('ar.nummer','ar.name_de','ar.herstellernummer','ar.ean','CONCAT(ar.nummer,\' \',ar.name_de)'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'ar.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + // heute 13.07. das INNER zu einem LEFT gemacht + $arr = $this->app->DB->SelectArr("SELECT CONCAT(ar.nummer,' ',ar.name_de) as name + FROM artikel ar LEFT JOIN lager_platz_inhalt lpi ON ar.id=lpi.artikel WHERE ($subwhere) AND ar.geloescht=0 AND ar.intern_gesperrt!=1 + AND ar.lagerartikel='1' $lwhere GROUP BY CONCAT(ar.nummer,' ',ar.name_de) ".$this->app->erp->ProjektRechte('ar.projekt')." LIMIT 20"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + + case "artikelnummerprojektpos": + $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); + + if($this->app->erp->Firmendaten('artikel_freitext1_suche')) + { + $felder[] = 'a.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $projekt = $this->app->User->GetParameter('pos_list_projekt'); + $projekArr = $this->app->DB->SelectRow( + sprintf( + 'SELECT id, pos_artikelnurausprojekt,eanherstellerscan + FROM projekt WHERE id = %d + LIMIT 1', + (int)$projekt + ) + ); + $checkprojekt = 0; + $eigenernummernkreis = 0; + $eanherstellerscan = 0; + if(!empty($projekArr)){ + $checkprojekt = $projekArr['id']; + $eigenernummernkreis = $projekArr['pos_artikelnurausprojekt']; + $eanherstellerscan = $projekArr['eanherstellerscan']; + } + if($checkprojekt > 0 && $eigenernummernkreis=='1') { + $tmp_where = " AND a.projekt='$checkprojekt' "; + } + else { + $tmp_where = ''; + } + + // besser ist wenn man die immer scannt da es oberflächen gibt wo das projekt nicht angegeben werden kann + if(0)//$eanherstellerscan) + { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name, a.id FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term2%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term3%' OR a.herstellernummer LIKE '%$term%' OR a.ean LIKE '%$term%'".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") $tmp_where ORDER by a.id DESC LIMIT 20"); + } + else { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name, a.id FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ($subwhere) $tmp_where ORDER by a.id DESC LIMIT 20"); + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + { + $check_lagerartikel = $this->app->DB->Select("SELECT lagerartikel FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + if($check_lagerartikel) + { + $summe_im_lager = (float)$this->app->DB->Select("SELECT ifnull(SUM(li.menge),0) FROM lager_platz_inhalt li LEFT JOIN lager_platz lp ON lp.id=li.lager_platz WHERE li.artikel='".$arr[$i]['id']."'"); + if($summe_im_lager > 0) + { + $artikel_reserviert = (float)$this->app->DB->Select("SELECT ifnull(SUM(menge),0) FROM lager_reserviert WHERE artikel='".$arr[$i]['id']."' AND (datum>=NOW() OR datum='0000-00-00')"); + }else $artikel_reserviert = 0; + } + if($check_lagerartikel && ($summe_im_lager - $artikel_reserviert) <= 0) { + $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; + } else { + $lager=''; + } + $newarr[] = $arr[$i]['name'].$lager; + + } + break; + + + + case "artikelnummerprojekt": + $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $projekt = $this->app->Secure->GetGET('projekt'); + $checkprojekt = $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); + $eigenernummernkreis = $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); + $eanherstellerscan = $this->app->DB->Select("SELECT eanherstellerscan FROM projekt WHERE id='$projekt'"); + + if($checkprojekt > 0 && $eigenernummernkreis=='1') { + $tmp_where = " AND a.projekt='$checkprojekt' "; + } + else { + $tmp_where = ''; + } + + // besser ist wenn man die immer scannt da es oberflächen gibt wo das projekt nicht angegeben werden kann + if(0)//$eanherstellerscan) + { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND (a.nummer LIKE '%$term%' OR a.name_de LIKE '%$term%' OR a.herstellernummer LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term2%' OR CONCAT(a.nummer,' ',a.name_de) LIKE '%$term3%' OR a.ean LIKE '%$term%'".($artikel_freitext1_suche?" OR freifeld1 LIKE '%$term%' ":"").") $tmp_where ORDER by a.id DESC LIMIT 20"); + } + else { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.nummer,' ',a.name_de,if(a.herstellernummer IS NULL OR a.herstellernummer='','',CONCAT(' PN: ',a.herstellernummer))) as name FROM artikel a WHERE a.geloescht=0 AND a.intern_gesperrt!=1 AND ($subwhere) $tmp_where ORDER by a.id DESC LIMIT 20"); + + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + + case "lagerartikelnummerprojekt": + $felder = array('a.nummer','a.name_de','a.herstellernummer','a.ean','CONCAT(a.nummer,\' \',a.name_de)','a.herstellernummer'); + + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + if($artikel_freitext1_suche) + { + $felder[] = 'art.freifeld1'; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.nummer,' ',a.name_de,' (',p.abkuerzung,')') as name FROM artikel a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.porto=0 AND a.intern_gesperrt!=1 + AND ( + $subwhere + ) LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + + case "verkaufartikelnummerprojekt": + $letzte_menge = null; + $artikel_freitext1_suche = $this->app->erp->Firmendaten('artikel_freitext1_suche'); + $projekt = $this->app->Secure->GetGET('projekt'); + $projectRow = empty($projekt)?null: $this->app->DB->SelectRow( + sprintf( + 'SELECT `id`, `eigenernummernkreis`, `projektlager` FROM `projekt` WHERE `id` = %d', $projekt + ) + ); + $checkprojekt = empty($projectRow)?null:$projectRow['id'];// $this->app->DB->Select("SELECT id FROM projekt WHERE id='$projekt' LIMIT 1"); + $eigenernummernkreis = empty($projectRow)?null:$projectRow['eigenernummernkreis'];//$this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id='$projekt' LIMIT 1"); + $projectStorage = !empty($projectRow['projektlager'])?$checkprojekt:0; + $smodule = $this->app->Secure->GetGET('smodule'); + $sid = $this->app->Secure->GetGET('sid'); + $document = $this->app->DB->SelectRow(sprintf('SELECT * FROM `%s` WHERE `id` = %d', $smodule, $sid)); + + $adresse = $document['adresse'];// $this->app->DB->Select("SELECT adresse FROM $smodule WHERE id='$sid' LIMIT 1"); + $waehrung = $document['waehrung'];//$this->app->DB->Select("SELECT waehrung FROM $smodule WHERE id='$sid' LIMIT 1"); + $posanz = (int)$this->app->DB->Select("SELECT count(id) FROM $smodule"."_position WHERE $smodule = '$sid'"); + + if($posanz == 0) + { + $waehrung = ''; + } + + $anzeigebrutto = false; + if($smodule == 'auftrag' || $smodule == 'rechnung' || $smodule == 'gutschrift' || $smodule == 'angebot' || $smodule == 'proformarechnung') + { + $_anrede = $this->app->DB->Select("SELECT typ FROM $smodule WHERE id = '$sid' LIMIT 1"); + $_projekt = $this->app->DB->Select("SELECT projekt FROM $smodule WHERE id = '$sid' LIMIT 1"); + $funktion = ucfirst($smodule).'MitUmsatzeuer'; + if($this->app->erp->AnzeigePositionenBrutto($_anrede, $smodule, $_projekt, $adresse,$sid) && $this->app->erp->$funktion($sid)) + { + $anzeigebrutto = true; + } + } + + $tmp_where = $this->app->erp->ProjektRechte('p.id', true, '', array(0, $projekt)); + //if($checkprojekt > 0 && $eigenernummernkreis=="1") $tmp_where = $this->app->erp->ProjektRechte(); + //else $tmp_where = ""; + $felder = array('a.nummer','a.name_de','a.ean','a.herstellernummer','a.name_de','CONCAT(a.nummer,\' \',a.name_de)'); + if($artikel_freitext1_suche) + { + $felder[] = 'a.freifeld1'; + } + + $artikel_artikelnummer_suche = $this->app->erp->Firmendaten('artikel_artikelnummer_suche'); + + if($artikel_artikelnummer_suche){ + $felder[] = 'v.kundenartikelnummer'; + $felder[] = 'e.bestellnummer'; + + $artikelnummer_suche_join = " + LEFT JOIN `einkaufspreise` AS `e` ON e.artikel=a.id AND e.geloescht = 0 + AND e.bestellnummer IS NOT NULL AND (e.gueltig_bis IS NULL OR e.gueltig_bis = '0000-00-00' OR e.gueltig_bis >= CURDATE()) + AND (e.gueltig_bis > NOW() OR e.gueltig_bis='0000-00-00' OR e.gueltig_bis IS NULL) "; + if($waehrung === 'EUR') { + $artikelnummer_suche_join .= " AND (e.waehrung='EUR' OR e.waehrung = '') "; + } + elseif($waehrung != ''){ + $artikelnummer_suche_join .= " AND e.waehrung='{$waehrung}' "; + } + $artikelnummer_suche_join .= "LEFT JOIN `verkaufspreise` AS `v` ON v.artikel=a.id AND v.geloescht = 0 + AND v.kundenartikelnummer IS NOT NULL + AND (v.gueltig_bis > NOW() OR v.gueltig_bis='0000-00-00' OR v.gueltig_bis IS NULL) "; + if($waehrung === 'EUR') { + $artikelnummer_suche_join .= " AND (v.waehrung='EUR' OR v.waehrung = '') "; + } + elseif($waehrung != ''){ + $artikelnummer_suche_join .= " AND v.waehrung = '{$waehrung}' "; + } + + $artikelnummer_suche_where = ''; + }else{ + $artikelnummer_suche_join = ""; + $artikelnummer_suche_where = ""; + } + + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr( + "SELECT DISTINCT a.id as id, + CONCAT( + a.nummer,' ',a.name_de,' (',p.abkuerzung,if(a.lagerartikel=1,'',''),')', + if(a.herstellernummer!='',CONCAT(' (PN: ',a.herstellernummer,')'),'') + ) as `name` , a.lagerartikel, a.porto, a.keinrabatterlaubt, a.juststueckliste, a.stueckliste + FROM `artikel` AS `a` + LEFT JOIN `projekt` AS `p` ON p.id=a.projekt + ".$artikelnummer_suche_join." + WHERE a.geloescht=0 AND a.intern_gesperrt!=1 + ".$artikelnummer_suche_where." + AND ($subwhere) $tmp_where LIMIT 20"); + + if ($module != "") { + if ($this->app->DB->Select("SHOW COLUMNS FROM `$module` LIKE 'realrabatt'")) { + $rabatt = $this->app->DB->Select("SELECT realrabatt FROM $smodule WHERE id='$sid' LIMIT 1"); + } + } + $sql_erweiterung = ''; + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++) { + + $arr[$i]['name'] = $this->app->DB->Select("SELECT CONCAT(nummer,' ',name_de,if(herstellernummer!='',CONCAT(' (PN: ',herstellernummer,')'),'') ) FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $keinrabatterlaubt = $arr[$i]['keinrabatterlaubt'];//$this->app->DB->Select("SELECT keinrabatterlaubt FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $checkporto = $arr[$i]['porto'];//$this->app->DB->Select("SELECT porto FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $gruppenarray = $this->app->erp->GetGruppen($adresse); + $cgruppenarray = !empty($gruppenarray)?count($gruppenarray):0; + if($cgruppenarray >0) + { + $sql_erweiterung = ' OR '; + } + for($gi=0;$gi<$cgruppenarray;$gi++) + { + $sql_erweiterung .= " gruppe='".$gruppenarray[$gi]."' "; + + if($gi<$cgruppenarray-1){ + $sql_erweiterung .= ' OR '; + } + } + + $vkarr = $this->app->erp->GeneratePreisliste($arr[$i]['id'],$adresse,$rabatt, $waehrung); + + $check_lagerartikel = $arr[$i]['lagerartikel'];//$this->app->DB->Select("SELECT lagerartikel FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $isJit = $arr[$i]['juststueckliste']; + //$newarr[]=$arr[$i]['name']." ($label Inkl. Rabatt ".$rabatt."%: ".$this->app->erp->Rabatt($arr[$i]['preis'],$rabatt).")"; + if($isJit) { + $preproducedpartlist = $this->app->erp->getPreproducedPartlistFromArticle($arr[$i]['id']); + if(!empty($preproducedpartlist) + && ($partlistsellable = $this->app->erp->ArtikelAnzahlVerkaufbar($preproducedpartlist, $projektlager)) + ) { + $lager = ' (Verfügbar: '.round($partlistsellable,4); + } + else { + $lager = (float)$this->app->erp->ArtikelAnzahlLagerStueckliste($arr[$i]['id'], $projectStorage); + if($lager == 0) { + $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; + } + else { + $lager = ' (Verfügbar: '.round($lager,4); + } + } + } + elseif($this->app->erp->LagerFreieMenge($arr[$i]['id']) <= 0 && $check_lagerartikel){ + $lager=' (Aktuell kein Lagerbestand bzw. durch Aufträge reserviert) '; + } + else{ + if($this->app->erp->Firmendaten('lagerbestand_in_auftragspositionen_anzeigen')){ + $artikel_reserviert = $this->app->DB->Select('SELECT '.$this->app->erp->FormatMenge('SUM(menge)')." FROM lager_reserviert WHERE artikel='".$arr[$i]['id']."' AND (datum>=NOW() OR datum='0000-00-00')"); + + $lager=' (Verfügbar: '.$this->app->erp->LagerFreieMenge($arr[$i]['id']); + if($artikel_reserviert) + { + $lager .= ' Reserviert: '.$artikel_reserviert; + } + else { + $lager .= ' Reserviert: 0'; + } + $lager .= ') '; + }else{ + $lager=''; + } + } + $cvkarr = !empty($vkarr)?count($vkarr):0; + $letzte_menge = null; + for($vi=0;$vi<$cvkarr;$vi++) + { + if(isset($vkarr[$vi]['ab_menge'])) + { + $vkarr[$vi]['ab_menge'] = round($vkarr[$vi]['ab_menge'], 8); + } + $tmprabatt = $rabatt; + if($vkarr[$vi]['art']=='Kunde' && ($vkarr[$vi]['adresse']<=0 || $vkarr[$vi]['adresse']=='')){ + $vkarr[$vi]['art'] = 'Standardpreis'; + } + + $preis = 0; + if($letzte_menge !=$vkarr[$vi]['ab_menge']) + { + if($keinrabatterlaubt=='1' || $checkporto=='1') + { + $preis = $vkarr[$vi]['preis']; //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); + + $newarr[]=$arr[$i]['name']." $lager ab Menge ".$vkarr[$vi]['ab_menge'].' | Preis: '.$preis. + ' ('.$vkarr[$vi]['art'].' - Kein Rabatt erlaubt) '; + + } else { + if($this->app->erp->IsSpezialVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse)) + { + $tmprabatt=0; + $rabatt_string = ' - Kein Rabatt auf Spezialpreis'; + $uvp_string = '(UVP: '.$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse).") "; + } else { + if($tmprabatt > 0) { + $rabatt_string = ' Inkl. Rabatt '.$tmprabatt.'%'; + $uvp_string = '(UVP: '.$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi]['ab_menge'],$adresse).") "; + } else { + $rabatt_string = ''; + $uvp_string = ''; + } + } + + if($anzeigebrutto) + { + $umsatzsteuer = $this->app->DB->Select("SELECT umsatzsteuer FROM artikel WHERE id = '".$arr[$i]['id']."' LIMIT 1"); + if($umsatzsteuer == 'ermaessigt') + { + $vkarr[$vi]['preis'] = round($vkarr[$vi]['preis']* (1+ (float)$this->app->DB->Select("SELECT steuersatz_ermaessigt FROM $smodule WHERE id = '$sid' LIMIT 1")/100),8); + }elseif($umsatzsteuer != 'befreit') + { + $vkarr[$vi]['preis'] = round($vkarr[$vi]['preis'] * (1+ (float)$this->app->DB->Select("SELECT steuersatz_normal FROM $smodule WHERE id = '$sid' LIMIT 1")/100),8); + } + } + + if($this->app->erp->Firmendaten('viernachkommastellen_belege')){ + $preis = number_format(rtrim($vkarr[$vi]['preis'], 0), 4, ',', '.'); //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); + } + else{ + $preis = number_format(rtrim($vkarr[$vi]['preis'], 0), 2, ',', '.'); //$this->app->erp->GetVerkaufspreis($arr[$i]['id'],$vkarr[$vi][ab_menge],$adresse); + } + + $newarr[]=$arr[$i]['name'].($vkarr[$vi]['vpe']!=''?' (Menge in VPE: '.$vkarr[$vi]['vpe'].")":"")." $lager ab Menge ".$vkarr[$vi]['ab_menge']." | Preis: ".$preis. + " $uvp_string(".$vkarr[$vi]['art'].$rabatt_string.') '; + } + } + } + + if($vi==0) + { + $rabattartikel = $this->app->DB->Select("SELECT rabatt FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $rabattartikel_prozent = $this->app->DB->Select("SELECT rabatt_prozent FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + $arr[$i]['name'] = $this->app->DB->Select("SELECT CONCAT(nummer,' ',name_de,if(herstellernummer!='',CONCAT(' (PN: ',herstellernummer,')'),'')) FROM artikel WHERE id='".$arr[$i]['id']."' LIMIT 1"); + + if($rabattartikel=='1'){ + $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: $rabattartikel_prozent% Rabatt auf Gesamtsumme ohne Porto"; + } + else { + $preis = $this->app->erp->GetVerkaufspreis($arr[$i]['id'],1,$adresse,$waehrung); + if($preis > 0){ + $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: $preis"; + } + else{ + $newarr[] = $arr[$i]['name'] . " $lager ab Menge 1 | Preis: nicht vorhanden"; + } + } + } + } + break; + + case "einkaufartikelnummerprojekt": + + $smodule = $this->app->Secure->GetGET('smodule'); + $sid = $this->app->Secure->GetGET('sid'); + + $waehrung = $this->app->DB->Select("SELECT `waehrung` FROM `{$smodule}` WHERE `id`='{$sid}' LIMIT 1"); + + $felder = [ + 'a.nummer', + 'a.name_de', + 'e.bezeichnunglieferant', + 'e.bestellnummer', + ]; + + $artikel_artikelnummer_suche = (int)$this->app->erp->Firmendaten('artikel_artikelnummer_suche'); + + if($artikel_artikelnummer_suche > 0){ + $felder[] = 'v.kundenartikelnummer'; + + $artikelnummer_suche_join = 'LEFT JOIN `verkaufspreise` `v` ON v.artikel=a.id' + .' AND v.geloescht = 0 AND v.kundenartikelnummer IS NOT NULL ' + . " AND (v.gueltig_bis > NOW() OR v.gueltig_bis='0000-00-00' OR v.gueltig_bis IS NULL) "; + if($waehrung === 'EUR') { + $artikelnummer_suche_join .= "AND (v.waehrung='EUR' OR v.waehrung = '')"; + } + elseif($waehrung != ''){ + $artikelnummer_suche_join .= "AND v.waehrung='{$waehrung}'"; + } + $artikelnummer_suche_where = ''; + }else{ + $artikelnummer_suche_join = ""; + $artikelnummer_suche_where = ""; + } + + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $adresse = (int)$this->app->Secure->GetGET('adresse'); + + $sql = "SELECT + CONCAT( + a.nummer, + ' ', + a.name_de, + ' | Bezeichnung bei Lieferant ', + IFNULL(e.bestellnummer,'nicht vorhanden'), + ' ', + LEFT(IFNULL(e.bezeichnunglieferant,'nicht vorhanden'),50), + ' | ', + ' ab Menge ', + ".$this->app->erp->FormatMenge("IFNULL(e.ab_menge,1)").", + ' | Preis ', + ".$this->app->erp->FormatPreis("IFNULL(e.preis,0)").", + ' | VPE ', + ".$this->app->erp->FormatMenge("IF(IFNULL(e.vpe,1)='',1,IFNULL(e.vpe,1))")." + ) as `name` + FROM `artikel` AS `a` + LEFT JOIN `projekt` AS `p` ON p.id=a.projekt + LEFT JOIN `einkaufspreise` AS `e` ON e.artikel=a.id " + .($waehrung!=""?"AND IFNULL(e.waehrung,'$waehrung')='$waehrung'":""). + $artikelnummer_suche_join." + WHERE a.tagespreise = 0 AND a.geloescht=0 AND a.intern_gesperrt!=1 + AND (e.gueltig_bis > NOW() OR e.gueltig_bis='0000-00-00' OR e.gueltig_bis IS NULL)". + $artikelnummer_suche_where." + AND (IFNULL(e.adresse,0)='$adresse' OR a.allelieferanten=1) + AND $subwhere " + .$this->app->erp->ProjektRechte("a.projekt")." + GROUP BY a.nummer,a.name_de,e.bezeichnunglieferant,e.bestellnummer, e.preis, e.ab_menge, e.vpe LIMIT 20"; + + $arr = $this->app->DB->SelectArr($sql); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "lieferantname": + $felder = array('a.nummer','a.name_de','e.bezeichnunglieferant','e.bestellnummer'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT name FROM adresse + WHERE geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ( + name LIKE '%$term%' OR name LIKE '%$term2%' OR name LIKE '%$term3%' + ) order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "lieferant": + //$arr = $this->app->DB->SelectArr("SELECT CONCAT(a.lieferantennummer,' ',a.name) as name FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.lieferantennummer!='' AND lieferantennummer!='0' AND (a.name LIKE '%$term%' OR a.lieferantennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte()." order by a.name LIMIT 20"); + /* + $arr = $this->app->DB->SelectArr("SELECT a.lieferantennummer, + + (SELECT + CONCAT(a2.lieferantennummer, ' ',a2.name) + FROM adresse a2 WHERE a2.lieferantennummer = a.lieferantennummer ".$this->app->erp->ProjektRechte("a2.projekt")." ORDER BY + ".($filter_projekt?" a2.projekt = '$filter_projekt' DESC, ":"")." a2.projekt LIMIT 1 + )as name2 + FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.lieferantennummer!='' AND lieferantennummer!='0' AND (a.name LIKE '%$term%' OR a.lieferantennummer LIKE '%$term%' OR a.name LIKE '%$term2%' OR a.name LIKE '%$term3%') ".$this->app->erp->ProjektRechte()." group by a.lieferantennummer order by name2 LIMIT 20"); + */ + $felder = array("concat(a.lieferantennummer,' ',a.name, if(a.ort!='', CONCAT(' ',a.ort),''))"); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + + $arr = $this->app->DB->SelectArr("SELECT concat(a.lieferantennummer,' ',a.name, if(a.ort!='', CONCAT(' (',a.ort,')'),'')) as name2 + FROM adresse a INNER JOIN (SELECT a2.lieferantennummer, ".($filter_projekt?" min( if(a2.projekt = ".$filter_projekt.", -1,a2.projekt))":" min(a2.projekt) ")." as mprojekt FROM adresse a2 + LEFT JOIN adresse_rolle ar2 ON a2.id = ar2.adresse AND ar2.projekt > 0 ".$this->app->erp->ProjektRechte("ar2.projekt")." + WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.lieferantennummer!='' AND a2.lieferantennummer!='0' AND (1 ".$this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb')." OR not isnull(ar2.id) ) + group by a2.lieferantennummer) adr + ON a.lieferantennummer = adr.lieferantennummer AND ".($filter_projekt?"(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)":"a.projekt = adr.mprojekt")." + LEFT JOIN adresse_rolle ar ON a.id = ar.adresse AND ar.projekt > 0 + WHERE a.geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ($subwhere) + group by a.lieferantennummer order by name2 LIMIT 20 + + "); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name2']; + } + break; + + case "lieferantartikel": + $felder = array("concat(a.lieferantennummer,' ',a.name)"); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $artikel = (int)$this->app->Secure->GetGET('artikel'); + $arr = $this->app->DB->SelectArr("SELECT concat(a.lieferantennummer,' ',a.name) as name2 + FROM adresse a INNER JOIN (SELECT a2.lieferantennummer, ".($filter_projekt?" min( if(a2.projekt = ".$filter_projekt.", -1,a2.projekt))":" min(a2.projekt) ")." as mprojekt FROM adresse a2 + WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.lieferantennummer!='' AND a2.lieferantennummer!='0' ".$this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb')." + group by a2.lieferantennummer) adr + ON a.lieferantennummer = adr.lieferantennummer AND ".($filter_projekt?"(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)":"a.projekt = adr.mprojekt")." + INNER JOIN einkaufspreise ep ON ep.adresse = a.id AND ep.artikel = '$artikel' + WHERE a.geloescht=0 AND a.lieferantennummer!='' AND a.lieferantennummer!='0' AND ($subwhere) ".$this->app->erp->ProjektRechte("a.projekt")." group by a.lieferantennummer order by name2 LIMIT 20 + + "); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name2']; + } + break; + + case "adressegruppevertriebbearbeiter": + + $typ = $this->app->Secure->GetGET('typ'); + if($typ === 'vertrieb'){ + $gruppe = $this->app->erp->Firmendaten('group_sales'); + }elseif($typ === 'bearbeiter'){ + $gruppe = $this->app->erp->Firmendaten('group_employee'); + }else{ + $gruppe = ''; + } + + $gruppeJoin = ''; + $gruppeWhere = ''; + + if($gruppe !== ''){ + $gruppeKennziffer = explode(' ', $gruppe); + $gruppeKennziffer = $gruppeKennziffer[0]; + $gruppeId = $this->app->DB->Select("SELECT id FROM gruppen WHERE kennziffer = '$gruppeKennziffer' LIMIT 1"); + if($gruppeId > 0){ + $gruppeJoin = + ' LEFT JOIN `adresse_rolle` AS `ar` ON a.id = ar.adresse'; + + $gruppeWhere = + ' AND ar.subjekt = \'Mitglied\' AND ar.objekt = \'Gruppe\' AND ar.parameter = \''.$gruppeId.'\' + AND ar.von <= CURDATE() AND (ar.bis = \'0000-00-00\' OR ar.bis >= CURDATE())'; + } + } + + $felder = + array( + '(CASE + WHEN a.lieferantennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\' Liefr: \',a.lieferantennummer,\')\') + WHEN a.kundennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\')\') + WHEN a.mitarbeiternummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Mitr: \',a.mitarbeiternummer,\')\') + END)' + ); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $sql = + 'SELECT + (CASE + WHEN a.lieferantennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\' Liefr: \',a.lieferantennummer,\')\') + WHEN a.kundennummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Kdr: \',a.kundennummer,\')\') + WHEN a.mitarbeiternummer != \'\' THEN CONCAT(a.id,\' \',a.name,\' (Mitr: \',a.mitarbeiternummer,\')\') + END) AS `name` + FROM `adresse` AS `a` '.$gruppeJoin.' + WHERE a.geloescht=0 + AND ('.$subwhere.') '.$gruppeWhere.$this->app->erp->ProjektRechte('a.projekt').' + ORDER BY a.name LIMIT 20'; + + $arr = $this->app->DB->SelectArr($sql); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + + break; + + case "adresse": + $felder = array("if(a.lieferantennummer,CONCAT(a.name,' ',a.kundennummer,' ',a.lieferantennummer,')'),CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,')'))"); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $sql = "SELECT if(a.lieferantennummer,CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,' Liefr: ',a.lieferantennummer,')'),CONCAT(a.id,' ',a.name,' (Kdr: ',a.kundennummer,')')) as `name` + FROM adresse a WHERE a.geloescht=0 AND ($subwhere) ".$this->app->erp->ProjektRechte('a.projekt')." + order by a.name LIMIT 20"; + $arr = $this->app->DB->SelectArr($sql); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "adressemitvertrieb": + $felder = array("concat(a.name, + if(a.kundennummer <> '' OR a.lieferantennummer <> '' OR a.mitarbeiternummer <> '', + concat(if(a.kundennummer <> '',concat(' ',a.kundennummer),''), if(a.kundennummer <> '' AND a.lieferantennummer <> '',' ',''),if(a.lieferantennummer <> '',concat(' ',a.lieferantennummer),'') + ,if((a.kundennummer <> '' OR a.lieferantennummer <> '') AND a.mitarbeiternummer <> '',' ',''), + if(a.mitarbeiternummer <> '',concat(' ',a.mitarbeiternummer),'') + ) + ,'') + )"); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT concat(a.id, ' ',a.name, + if(a.kundennummer <> '' OR a.lieferantennummer <> '' OR a.mitarbeiternummer <> '', + concat(' (',if(a.kundennummer <> '',concat('Kdr: ',a.kundennummer),''), if(a.kundennummer <> '' AND a.lieferantennummer <> '',' ',''),if(a.lieferantennummer <> '',concat('Liefr: ',a.lieferantennummer),'') + ,if((a.kundennummer <> '' OR a.lieferantennummer <> '') AND a.mitarbeiternummer <> '',' ',''), + if(a.mitarbeiternummer <> '',concat('Mitr: ',a.mitarbeiternummer),'') + ,')') + ,'') + ) + as name + + FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND ($subwhere) AND ((1 ".$this->app->erp->ProjektRechte().") OR a.id = '".$this->app->User->GetAdresse()."') order by a.name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case 'kundepos': + $aktprojekt = $this->app->User->GetParameter('pos_list_projekt'); + $felder = array("CONCAT(ifnull(a.kundennummer,''),' ',a.name,if(a.projekt > 0,CONCAT(' (',p.abkuerzung,')'),''),if(ifnull(a.freifeld1,'')!='',CONCAT(' (',a.freifeld1,')'),''))"); + + $swhere = ''; + if($aktprojekt && !$this->app->DB->Select("SELECT pos_kundenalleprojekte FROM projekt WHERE id = '$aktprojekt' LIMIT 1") && $this->app->DB->Select("SELECT eigenernummernkreis FROM projekt WHERE id = '$aktprojekt' LIMIT 1")){ + $swhere = " AND p.id = '$aktprojekt' "; + } + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(a.kundennummer,' ',a.name,if(a.projekt > 0,CONCAT(' (',p.abkuerzung,')'),''),if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name FROM adresse a LEFT JOIN projekt p ON p.id=a.projekt WHERE a.geloescht=0 AND a.kundennummer!='' AND a.kundennummer!='0' AND ($subwhere) $swhere order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case 'kunde': + + $felder = array("CONCAT(a.kundennummer, ' ',a.name,if(ifnull(a.freifeld1,'')!='',CONCAT(' (',ifnull(a.freifeld1,''),')'),''),' ',a.plz,' ',a.ort)"); + if($term2 === $term){ + $term2 = ''; + } + if($term3 === $term){ + $term3 = ''; + } + $terma = explode('%', trim(str_replace('%%','%',$term),'%')); + $terma2 = explode('%', trim(str_replace('%%','%',$term2),'%')); + $terma3 = explode('%', trim(str_replace('%%','%',$term3),'%')); + foreach($felder as $v) + { + $subwherea[] = " $v LIKE '%$term%' "; + if($term2 !== '') + { + $subwherea[] = " $v LIKE '%$term2%' "; + } + if($term3 !== '') + { + $subwherea[] = " $v LIKE '%$term3%' "; + } + } + $terma21 = ''; + $terma22 = ''; + $terma31 = ''; + $terma32 = ''; + if(count($terma2) > 1) + { + $terma22 = $terma2[count($terma2)-1]; + unset($terma2[count($terma2)-1]); + $terma21 = implode('%', $terma2); + } + if(count($terma3) > 1) + { + $terma32 = $terma3[count($terma3)-1]; + unset($terma3[count($terma3)-1]); + $terma31 = implode('%', $terma3); + } + + if(count($terma) > 1) { + $terma12 = $terma[count($terma)-1]; + unset($terma[count($terma)-1]); + $terma11 = implode('%', $terma); + $subwheretmpa1 = null; + $subwheretmpa2 = null; + foreach($felder as $v) { + if($v !== 'a.ort') + { + $subwheretmpa1[] = " $v LIKE '%$terma11%' "; + $subwheretmpa2[] = " $v LIKE '%$terma12%' "; + if($terma21 !== '') + { + $subwheretmpa1[] = " $v LIKE '%$terma21%' "; + $subwheretmpa2[] = " $v LIKE '%$terma22%' "; + } + if($terma31 !== '') + { + $subwheretmpa1[] = " $v LIKE '%$terma31%' "; + $subwheretmpa2[] = " $v LIKE '%$terma32%' "; + } + } + } + $subwheretmpa3[] = " a.ort LIKE '%$terma12%' "; + $subwheretmpa4[] = " a.ort LIKE '%$terma11%' "; + if($terma21 !== '') + { + $subwheretmpa3[] = " a.ort LIKE '%$terma22%' "; + $subwheretmpa4[] = " a.ort LIKE '%$terma21%' "; + } + if($terma31 !== '') + { + $subwheretmpa3[] = " a.ort LIKE '%$terma32%' "; + $subwheretmpa4[] = " a.ort LIKE '%$terma31%' "; + } + + $subwherea[] = " ((".implode(' OR ', $subwheretmpa3).") AND (".implode(" OR ", $subwheretmpa1).") ) "; + $subwherea[] = " ((".implode(' OR ', $subwheretmpa4).") AND (".implode(" OR ", $subwheretmpa2).") ) "; + } + + //$subwhere = implode(' OR ', $subwherea); + + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + if($this->app->DB->Select('SELECT id FROM projekt WHERE geloescht <> 1 AND eigenernummernkreis = 1 LIMIT 1')){ + $sql = "SELECT CONCAT(a.kundennummer, ' ',a.name,if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name, a.ort + FROM adresse AS a + INNER JOIN + ( + SELECT a2.kundennummer, " . ($filter_projekt ? " min( if(a2.projekt = " . $filter_projekt . ", -1,a2.projekt))" : " min(a2.projekt) ") . " as mprojekt + FROM adresse a2 + WHERE (a2.geloescht = 0 or isnull(a2.geloescht)) AND a2.kundennummer!='' AND a2.kundennummer!='0' " . $this->app->erp->ProjektRechte("a2.projekt", true, 'a2.vertrieb') . " + group by a2.kundennummer + ) AS adr + ON a.kundennummer = adr.kundennummer AND " . ($filter_projekt ? "(a.projekt = adr.mprojekt OR a.projekt = $filter_projekt AND adr.mprojekt = -1)" : "a.projekt = adr.mprojekt") . " + WHERE ($subwhere) + " . $this->app->erp->ProjektRechte('a.projekt', true, 'a.vertrieb') . ' + GROUP BY a.kundennummer, a.name, a.ort + ORDER BY `name` LIMIT 20 + '; + } + else { + $sql = " + SELECT CONCAT(a.kundennummer, ' ',a.name,if(a.freifeld1!='',CONCAT(' (',a.freifeld1,')'),'')) as name, a.ort + FROM adresse AS a + WHERE ($subwhere) AND kundennummer <> '' AND kundennummer <> '0' AND a.geloescht <> 1 + " . $this->app->erp->ProjektRechte('a.projekt', true, 'a.vertrieb') . ' + GROUP BY a.kundennummer, a.name, a.ort + ORDER BY `name` LIMIT 20 + '; + } + $arr = $this->app->DB->SelectArr($sql); + + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + { + if($arr[$i]['ort']!=''){ + $newarr[] = $arr[$i]['name'] . ' (' . $arr[$i]['ort'] . ')'; + } + else{ + $newarr[] = $arr[$i]['name']; + } + } + break; + case "mitarbeiter": + $felder = array('mitarbeiternummer','name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(mitarbeiternummer,' ',name) as name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "mitarbeiterid": + $felder = array('mitarbeiternummer','name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',name) as name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "mitarbeiteraktuell": + $felder = array('mitarbeiternummer','name'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT CONCAT(a.mitarbeiternummer,' ',a.name) as name FROM adresse a LEFT JOIN adresse_rolle ar ON a.id = ar.adresse WHERE a.geloescht=0 AND a.mitarbeiternummer!='' AND a.mitarbeiternummer!='0' AND ($subwhere) AND ar.subjekt = 'Mitarbeiter' AND (ar.bis = '0000-00-00' OR ar.bis >= CURDATE()) ORDER BY name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "mitarbeitername": + $felder = array('name','mitarbeiternummer'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT name FROM adresse WHERE geloescht=0 AND mitarbeiternummer!='' AND mitarbeiternummer!='0' AND ($subwhere) order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "emailadresse": + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + $subwhere1 = ''; + $subwhere2 = ''; + if($this->app->Secure->GetGET('kundennummer')!="") + { + //$adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer like '".$this->app->Secure->GetGET('kundennummer')."' ".($filter_projekt?" AND (projekt = '$filter_projekt' or projekt = 0) ":"")." LIMIT 1"); + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE kundennummer like '".$this->app->Secure->GetGET('kundennummer')."' AND geloescht <> 1 ORDER BY ".($filter_projekt?" projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); + if($adresse) + { + $subwhere1 .= " AND adresse = '$adresse' "; + $subwhere2 .= " AND id = '$adresse' "; + } + } + + if($this->app->Secure->GetGET('kd_lf_ma_nummer')!="") + { + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE (kundennummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."' OR lieferantennummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."' OR mitarbeiternummer like '".$this->app->Secure->GetGET('kd_lf_ma_nummer')."') AND geloescht <> 1 ORDER BY ".($filter_projekt?" projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); + if($adresse) + { + $subwhere1 .= " AND adresse = '$adresse' "; + $subwhere2 .= " AND id = '$adresse' "; + } + } + + if($this->app->Secure->GetGET('kd_id')){ + $adresse = $this->app->DB->Select("SELECT id FROM adresse WHERE id = '".$this->app->Secure->GetGET('kd_id')."' AND geloescht != 1 ORDER BY ".($filter_projekt?"projekt = '$filter_projekt' DESC, ":"")." projekt LIMIT 1"); + if($adresse){ + $subwhere1 .= " AND adresse = '$adresse' "; + $subwhere2 .= " AND id = '$adresse' "; + } + } + + $limit = "LIMIT 20"; + if ($this->app->Secure->GetGET('limit')) { + $limit = "LIMIT 1"; + } + + if($limit=="LIMIT 1") + { + $arr = $this->app->DB->SelectArr("SELECT email FROM ansprechpartner WHERE email <> '' $subwhere1 AND geloescht <> 1 order by name $limit"); + } else { + $arr = $this->app->DB->SelectArr("SELECT email FROM ansprechpartner WHERE (name LIKE '%$term%' OR email LIKE '%$term%') and email <> '' $subwhere1 AND geloescht <> 1 order by name $limit"); + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['email']; + } + if($limit=="LIMIT 1") + { + $arr = $this->app->DB->SelectArr("SELECT email FROM adresse WHERE geloescht!='1' $subwhere2 order by name $limit"); + } + else + { + $arr = $this->app->DB->SelectArr("SELECT email FROM adresse WHERE (name LIKE '%$term%' OR email LIKE '%$term%') and email <> '' AND geloescht!='1' $subwhere2 order by name $limit"); + } + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['email']; + } + + $newarr = array_unique($newarr); + sort($newarr); + break; + case "emailbackup": + $arr = $this->app->DB->SelectArr("SELECT email FROM emailbackup"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['email']; + } + + $newarr = array_unique($newarr); + sort($newarr); + break; + case "emailname": + + $felder = array("CONCAT(name,' -ltrep-',email,'-gtrep-')",'name','email'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' -ltrep-',email,'-gtrep-') as name FROM ansprechpartner WHERE ($subwhere) AND geloescht <> 1 order by name LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + + $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' -ltrep-',email,'-gtrep-') as name FROM adresse WHERE ($subwhere) AND geloescht!='1' order by name LIMIT 20"); + + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++){ + $newarr[] = $arr[$i]['name']; + } + + $newarr = array_unique($newarr); + sort($newarr); + $isChangeLtGt = true; + break; + + case "shopname": + $arr = $this->app->DB->SelectArr("SELECT s.bezeichnung FROM shopexport s LEFT JOIN projekt p ON p.id=s.projekt WHERE s.bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("s.projekt")); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "shopnameid": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(id,' ',bezeichnung) as bezeichnung FROM shopexport WHERE bezeichnung LIKE '%$term%' ".$this->app->erp->ProjektRechte("projekt").""); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "gruppekennziffer": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g LEFT JOIN projekt p ON p.id=g.projekt + WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "preisgruppekennziffer": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g LEFT JOIN projekt p ON p.id=g.projekt + WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.art = 'preisgruppe' AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "gruppe": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.name,' ',g.kennziffer) as bezeichnung FROM gruppen g + LEFT JOIN projekt p ON p.id=g.projekt WHERE (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "verband": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(name,' ',kennziffer) as bezeichnung FROM gruppen WHERE (name LIKE '%$term%' OR kennziffer LIKE '%$term%') AND aktiv=1 AND art='verband'"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "verbindlichkeit": + $felder = array("CONCAT(v.belegnr, v.betrag, a.name, v.rechnung, a.lieferantennummer, a.lieferantennummer_buchhaltung, ".$this->app->erp->FormatPreis('v.betrag',2).")", + 'v.id','IFNULL(v.belegnr, \'\')','v.betrag','a.name','v.rechnung','a.lieferantennummer','a.lieferantennummer_buchhaltung',$this->app->erp->FormatPreis('v.betrag',2)); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + if(strpos($term,',')!==false) + { + $term = substr($term,strripos($term,',')); + $term = str_replace(',','',$term); + } + + $sql = + "SELECT CONCAT(v.id, + IF(IFNULL(v.belegnr, '') <> '' AND v.belegnr!=v.id, + CONCAT(' Nr. ',v.belegnr),''), + ' Betrag: ',".$this->app->erp->FormatPreis('v.betrag',2).", + if(v.skonto <> 0,CONCAT(' mit Skonto ',v.skonto,'% ', + ".$this->app->erp->FormatPreis("v.betrag-((v.betrag/100.0)*v.skonto)",2)."),''),' ', + ' Ist: ',".$this->app->erp->FormatPreis('v.betragbezahlt',2).", + ' Offen: ',".$this->app->erp->FormatPreis( + 'IF(v.betrag - v.betragbezahlt > ((v.betrag/100.0)*v.skonto), + v.betrag - v.betragbezahlt,0)',2 + ).", + + a.name,' (Lieferant ',a.lieferantennummer,if(a.lieferantennummer_buchhaltung!='' AND a.lieferantennummer <> a.lieferantennummer_buchhaltung,CONCAT(' ',a.lieferantennummer_buchhaltung),''),') RE ',v.rechnung,' Rechnungsdatum ',DATE_FORMAT(v.rechnungsdatum,'%d.%m.%Y')) as bezeichnung + FROM verbindlichkeit AS v + LEFT JOIN adresse AS a ON a.id=v.adresse + WHERE ($subwhere) AND bezahlt!=1 AND status!='storniert' + ORDER by v.id DESC"; //AND v.status!='bezahlt' // heute wieder raus + + $arr = $this->app->DB->SelectArr($sql); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + + case "projektname": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(p.abkuerzung,' ',p.name) as name FROM projekt p WHERE p.geloescht=0 AND status <> 'abgeschlossen' AND (p.name LIKE '%$term%' OR p.name LIKE '%$term2%' OR p.name LIKE '%$term3%' OR p.abkuerzung LIKE '%$term%' OR p.abkuerzung LIKE '%$term2%' OR p.abkuerzung LIKE '%$term3%') ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + + case "uebertragung_account": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(u.id,' ',u.bezeichnung) as name FROM uebertragungen_account u WHERE (u.bezeichnung LIKE '%$term%') ".$this->app->erp->ProjektRechte('u.projekt')); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + break; + case "api_account": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(u.id,' ',u.bezeichnung) as name FROM api_account u WHERE (u.bezeichnung LIKE '%$term%') ".$this->app->erp->ProjektRechte('u.projekt')); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + break; + case "gruppen_kategorien": + $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.id,' ',g.bezeichnung) as name FROM gruppen_kategorien g + LEFT JOIN projekt p ON p.id=g.projekt WHERE (g.bezeichnung LIKE '%$term%' ) ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + case "gruppenkategoriegruppen": + $kategorie = (int)$this->app->Secure->GetGET('gkid'); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(g.kennziffer,' ',g.name) as bezeichnung FROM gruppen g + LEFT JOIN projekt p ON p.id=g.projekt WHERE kategorie = '$kategorie' AND (g.name LIKE '%$term%' OR g.kennziffer LIKE '%$term%') AND g.aktiv=1 ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + + break; + case 'steuersatz': + $newarr[] = $this->app->erp->Firmendaten('steuersatz_normal').' normal'; + $newarr[] = $this->app->erp->Firmendaten('steuersatz_ermaessigt').' ermaessigt'; + $newarr = array_merge($newarr, $this->app->DB->SelectFirstCols( + "SELECT concat( + `satz`,' ',`bezeichnung`, ' ',`country_code`, + IF(`type` != '', CONCAT(' ',`type`),''), + IF( + `valid_from` = '0000-00-00' OR `valid_from` IS NULL, + '', + CONCAT(' gültig ab: ',DATE_FORMAT(valid_from,'%d.%m.%Y')) + ), + IF( + `valid_to` = '0000-00-00' OR `valid_to` IS NULL, + '', + CONCAT(' gültig bis: ',DATE_FORMAT(valid_to,'%d.%m.%Y')) + ) + ) as `name` + FROM `steuersaetze` WHERE `aktiv` = 1 + AND concat( + `satz`,' ',`bezeichnung`,' ',`country_code`, + IF(`type` != '', CONCAT(' ',`type`),''), + IF( + `valid_from` = '0000-00-00' OR `valid_from` IS NULL, + '', + CONCAT(' gültig ab: ',DATE_FORMAT(valid_from,'%d.%m.%Y')) + ), + IF( + `valid_to` = '0000-00-00' OR `valid_to` IS NULL, + '', + CONCAT(' gültig bis: ',DATE_FORMAT(valid_to,'%d.%m.%Y')) + ) + ) LIKE '%$term%'" + )); + break; + case "eigenschaftname": + $arr = $this->app->DB->SelectArr("SELECT name FROM artikeleigenschaften WHERE geloescht != 1 AND name like '%$term%' ORDER BY name "); + if($arr) + { + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['name']; + } + break; + } + break; + case "eigenschaftwert": + $eigenschaftname = $this->app->DB->real_escape_string(urldecode($this->app->Secure->GetGET('eigenschaftname'))); + if($eigenschaftname !== '') + { + $arr = $this->app->DB->SelectArr("SELECT DISTINCT aw.wert FROM artikeleigenschaftenwerte aw + INNER JOIN artikeleigenschaften ae ON aw.artikeleigenschaften = ae.id AND ae.geloescht <> 1 + WHERE aw.wert like '%$term%' AND ae.name = '$eigenschaftname' ORDER BY aw.wert "); + }else{ + $arr = $this->app->DB->SelectArr("SELECT DISTINCT aw.wert FROM artikeleigenschaftenwerte aw + INNER JOIN artikeleigenschaften ae ON aw.artikeleigenschaften = ae.id AND ae.geloescht <> 1 + WHERE aw.wert like '%$term%' ORDER BY aw.wert"); + } + if($arr) + { + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) + $newarr[] = $arr[$i]['wert']; + break; + } + + + break; + case "angebot_position": + $angebot = $this->app->Secure->GetGET('angebot'); + $angebotposition = $this->app->Secure->GetGET('angebotposition'); + $arr = $this->app->DB->SelectArr("SELECT CONCAT(ap.sort,' ',ap.nummer) as bezeichnung FROM angebot_position ap INNER JOIN angebot a ON ap.angebot = a.id AND a.id = '$angebot' + LEFT JOIN projekt p ON p.id=a.projekt + WHERE (ap.sort LIKE '%$term%' OR ap.nummer LIKE '%$term%') AND ap.explodiert_parent = 0 AND ap.id <> '$angebotposition' ".$this->app->erp->ProjektRechte()); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + break; + case "supportapp_gruppen": + $suchbegriff = $this->app->DB->real_escape_string($this->app->Secure->GetGET('term')); + $suchbegriff = trim($suchbegriff); + $arr = $this->app->DB->SelectArr("SELECT bezeichnung FROM supportapp_gruppen WHERE aktiv = '1' AND bezeichnung LIKE '%$suchbegriff%'"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['bezeichnung']; + } + break; + break; + case "datevkonto": + $arr = $this->app->DB->SelectArr("SELECT DISTINCT t.gegenkonto FROM + ( (SELECT concat(datevkonto, ' ',bezeichnung) as gegenkonto FROM konten WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1) + UNION ALL (SELECT concat(sachkonto, ' ',beschriftung) as gegenkonto FROM kontorahmen WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1) + + ) t WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' ORDER BY t.gegenkonto"); + $carr = !empty($arr)?count($arr):0; + for($i=0;$i<$carr;$i++) { + $newarr[] = $arr[$i]['gegenkonto']; + } + break; + case 'gegenkonto': + + $kontorahmenArr = $this->app->DB->SelectPairs( + "SELECT concat(kr.sachkonto, ' ',kr.beschriftung) as a, kr.sachkonto + FROM kontorahmen as kr + WHERE kr.ausblenden <> 1" + ); + $subwhere = ' '; + if(!empty($kontorahmenArr)) { + $kontorahmenArr = array_unique(array_merge(array_keys($kontorahmenArr), array_values($kontorahmenArr))); + $subwhere = sprintf(" AND ka.gegenkonto NOT IN ('%s') ", implode("','", $kontorahmenArr)); + } + + $arr = $this->app->DB->SelectArr( + "SELECT DISTINCT t.gegenkonto + FROM + ( + ( + SELECT concat(ka.gegenkonto,' ',ka.name) as gegenkonto + FROM (SELECT ka2.gegenkonto,a.name + FROM kontoauszuege ka2 + INNER JOIN adresse a ON ka2.gegenkonto = a.kundennummer OR ka2.gegenkonto = a.lieferantennummer + WHERE ka2.gegenkonto <> '' + GROUP BY ka2.gegenkonto, a.name + ) AS ka + WHERE ka.gegenkonto <> '' $subwhere + ) + UNION ALL ( + SELECT concat(datevkonto, ' ',bezeichnung) + FROM konten + WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1 + AND concat(datevkonto, ' ',bezeichnung) LIKE '%$term%' + ) + UNION ALL ( + SELECT concat(sachkonto, ' ',beschriftung) + FROM kontorahmen + WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1 + AND concat(sachkonto, ' ',beschriftung) LIKE '%$term%' + ) + + ) t + WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' + ORDER BY t.gegenkonto" + ); + + + if($this->app->DB->error()){ + $arr = $this->app->DB->SelectArr( + "SELECT DISTINCT t.gegenkonto + FROM + ( + ( + SELECT concat(ka.gegenkonto,' ',( + SELECT a.name + FROM adresse a + WHERE (a.kundennummer=ka.gegenkonto OR a.lieferantennummer=ka.gegenkonto) AND ka.gegenkonto!='') + ) as gegenkonto + FROM kontoauszuege ka + LEFT JOIN kontorahmen kr + ON (ka.gegenkonto = kr.sachkonto OR ka.gegenkonto = concat(kr.sachkonto, ' ',kr.beschriftung)) + AND kr.ausblenden <> 1 + WHERE isnull(kr.id) AND ka.gegenkonto <> '' + GROUP BY ka.gegenkonto + ) + UNION ALL ( + SELECT concat(datevkonto, ' ',bezeichnung) + FROM konten + WHERE datevkonto <> 0 AND datevkonto <> '' AND aktiv = 1 + AND concat(datevkonto, ' ',bezeichnung) LIKE '%$term%' + ) + UNION ALL ( + SELECT concat(sachkonto, ' ',beschriftung) + FROM kontorahmen + WHERE sachkonto <> 0 AND sachkonto <> '' AND ausblenden <> 1 + AND concat(sachkonto, ' ',beschriftung) LIKE '%$term%' + ) + + ) t + WHERE t.gegenkonto <> '' AND t.gegenkonto LIKE '%$term%' + ORDER BY t.gegenkonto" + ); + } + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['gegenkonto']; + } + break; + + break; + case 'versand_klaergrund': + $arr = $this->app->DB->SelectArr("SELECT DISTINCT problemcase FROM + delivery_problemcase WHERE problemcase LIKE '%$term%' ORDER BY sort, problemcase"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['problemcase']; + } + break; + case 'label_type': + $felder = array('type'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr("SELECT DISTINCT lt.type FROM label_type AS lt WHERE ($subwhere) ORDER BY type LIMIT 20"); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['type']; + } + break; + case 'versandartentype': + $felder = array('va.type'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr( + "SELECT DISTINCT va.type + FROM versandarten AS va + WHERE ($subwhere) AND va.geloescht <> 1 AND va.aktiv = 1 + ORDER BY va.type + LIMIT 20" + ); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['type']; + } + break; + case 'zahlungsweisetype': + $felder = array('va.type'); + $subwhere = $this->AjaxFilterWhere($termorig,$felder); + $arr = $this->app->DB->SelectArr( + "SELECT DISTINCT va.type + FROM zahlungsweisen AS va + WHERE ($subwhere) AND va.geloescht <> 1 AND va.aktiv = 1 + ORDER BY va.type + LIMIT 20" + ); + $carr = !empty($arr)?count($arr):0; + for($i = 0; $i < $carr; $i++) { + $newarr[] = $arr[$i]['type']; + } + break; + case 'ticketcategory': + $newarr = $this->app->DB->SelectFirstCols( + sprintf( + "SELECT CONCAT(`id`,' ',`name`) FROM `ticket_category` WHERE (`name` LIKE '%%%s%%' OR `name` LIKE '%%%s%%') %s", + $term, $term2, $this->app->erp->ProjektRechte('project_id') + ) + ); + break; + case 'shopimport_auftraege': + $shopId = $this->app->Secure->GetGET('id'); + $newarr = $this->app->DB->SelectFirstCols( + sprintf( + "SELECT CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) + FROM `shopimport_auftraege` AS `sa` + WHERE ( + CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) LIKE '%%%s%%' + OR CONCAT(sa.`extid`,' ',IFNULL(sa.`bestellnummer`,'')) LIKE '%%%s%%' + ) AND (%d = 0 OR %d = sa.shopid) %s", + $term, $term2, $shopId, $shopId, $this->app->erp->ProjektRechte('sa.projekt') + ) + ); + + break; + default: + $newarr = null; + $this->app->erp->RunHook('ajax_filter_hook1', 5,$filtername,$newarr, $term, $term2, $term3); + } + + $tmp = null; + //if(isset($this->app->stringcleaner) && false) + if(false) + { + $cnewarr = $newarr?count($newarr):0; + for($i=0;$i<$cnewarr;$i++){ + $tmp[] = $this->app->erp->ClearDataBeforeOutput($this->app->stringcleaner->CleanString(html_entity_decode( $this->app->stringcleaner->CleanString($newarr[$i], 'nojs'), ENT_QUOTES, 'UTF-8'), 'nojs')); + } + }else{ + $cnewarr = !empty($newarr)?count($newarr):0; + for($i=0;$i<$cnewarr;$i++) { + $tmp[] = $this->app->erp->ClearDataBeforeOutput(html_entity_decode($newarr[$i], ENT_QUOTES, 'UTF-8')); + } + } + + if(!empty($isChangeLtGt)){ + $ctmp = !empty($tmp)?count($tmp):0; + for($i=0;$i<$ctmp;$i++){ + $tmp[$i] = str_replace('-gtrep-','>',str_replace('-ltrep-','<',$tmp[$i])); + } + } + + echo json_encode($tmp); + $this->app->erp->ExitWawi(); + } + + public function AjaxTablePosition() + { + + $iDisplayStart = $this->app->Secure->GetGET('iDisplayStart'); + $iDisplayLength = $this->app->Secure->GetGET('iDisplayLength'); + $iSortCol_0 = $this->app->Secure->GetGET('iSortCol_0'); + $iSortingCols = $this->app->Secure->GetGET('iSortingCols'); + $sSearch = $this->app->Secure->GetGET('sSearch'); + $sEcho = $this->app->Secure->GetGET('sEcho'); + $cmd = $this->app->Secure->GetGET('cmd'); + + + $sLimit = ''; + if ( isset($iDisplayStart) ) + { + + $sLimit = 'LIMIT '. (int)$iDisplayStart .', '. + (int)$iDisplayLength ; + } + + /* Ordering */ + if ( isset( $iSortCol_0 ) ) + { + $sOrder = 'ORDER BY '; + $ciSortingCols = (int)$iSortingCols; + for ( $i=0 ; $i<$ciSortingCols ; $i++ ) + { + $iSortingCols_tmp = $this->app->Secure->GetGET('iSortCol_'.$i); + $sSortDir_tmp = $this->app->Secure->GetGET('sSortDir_'.$i); + + $sOrder .= $this->fnColumnToFieldPosition($iSortingCols_tmp ).' + '. $sSortDir_tmp .', '; + } + $sOrder = substr_replace( $sOrder, '', -2 ); + } + + /* Filtering - NOTE this does not match the built-in DataTables filtering which does it + * word by word on any field. It's possible to do here, but concerned about efficiency + * on very large tables, and MySQL's regex functionality is very limited + */ + + + $sWhere = ''; + $where = $this->app->YUI->TablePositionSearch('',$cmd,'where'); + if ( $sSearch != '' ) + { + $searchsql = $this->app->YUI->TablePositionSearch('',$cmd,'searchsql'); + + if($where==''){ + $sWhere = ' WHERE ('; + } + else + { + if(!empty($searchsql) && count($searchsql) >0){ + $sWhere = " WHERE $where AND ("; + } + else{ + $sWhere = " WHERE $where "; + } + } + + + for($i=0;$iapp->DB->real_escape_string($sSearch )."%' OR "; + } + $sWhere .= $searchsql[$i]." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%')"; + + + } else { + if($where!=''){ + $sWhere = " WHERE $where "; + } + } + + + $searchfulltext = $this->app->YUI->TablePositionSearch('',$cmd,'searchfulltext'); + if($searchfulltext!='' && $sSearch!='') + { + $searchfulltext = ' MATCH('.$searchfulltext.") AGAINST ('$sSearch') "; + if($sWhere==''){ + $sWhere = " WHERE $searchfulltext "; + } + else{ + $sWhere .= "AND $searchfulltext "; + } + } + $tmp = $this->app->YUI->TablePositionSearch('',$cmd,'sql'); + + + $sQuery = " + $tmp + $sWhere + $sOrder + $sLimit + "; + + + $rResult = $this->app->DB->Query($sQuery); + + + + $sQuery = ' + SELECT FOUND_ROWS() + '; + $rResultFilterTotal = $this->app->DB->Query($sQuery); + if(!empty($rResultFilterTotal)){ + $aResultFilterTotal = $this->app->DB->Fetch_Array($rResultFilterTotal); + $this->app->DB->free($rResultFilterTotal); + $iFilteredTotal = $aResultFilterTotal[0]; + }else{ + $aResultFilterTotal = 0; + $iFilteredTotal = 0; + } + + /* + $sQuery = " + SELECT COUNT(id) + FROM artikel + "; + */ + $sQuery = $this->app->YUI->TablePositionSearch('',$cmd,'count'); + $rResultTotal = $this->app->DB->Query($sQuery); + $aResultTotal = $this->app->DB->Fetch_Array($rResultTotal); + $this->app->DB->free($rResultTotal); + $iTotal = $aResultTotal[0]; + + + $heading = count($this->app->YUI->TablePositionSearch('',$cmd,'heading')); + $menu = $this->app->YUI->TablePositionSearch('',$cmd,'menu'); + + $sOutput = '{'; + $sOutput .= '"sEcho": '.(int)$sEcho.', '; + $sOutput .= '"iTotalRecords": '.$iTotal.', '; + $sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', '; + $sOutput .= '"aaData": [ '; + if($rResult){ + while ($aRow = $this->app->DB->Fetch_Row($rResult)) { + $sOutput .= '['; + for ($i = 1; $i < $heading; $i++) { + $sOutput .= '"' . addslashes($aRow[$i]) . '",'; + } + + $sOutput .= '"' . addslashes(str_replace('%value%', $aRow[$i], $menu)) . '"'; + + $sOutput .= '],'; + + } + $this->app->DB->free($rResult); + } + $sOutput = substr_replace( $sOutput, '', -1 ); + $sOutput .= '] }'; + + $sOutput = str_replace("\t",'',$sOutput); + + echo json_encode(json_decode($this->app->erp->ClearDataBeforeOutput($sOutput))); + $this->app->erp->ExitWawi(); + } + + protected function AjaxTableWhereBuilder($spalte, $sSearch, $datecol = false, $numbercol = false) + { + $sSearch = str_replace('%','%',$sSearch); + $sSearcha = explode(' ', $sSearch); + $sSearch = str_replace(' ','%',$sSearch); + + + if($spalte == 'datum' || $datecol) + { + return ' ( DATE_FORMAT('.$spalte.",'%d.%m.%Y %H:%i:%s') LIKE '%".$this->app->DB->real_escape_string($sSearch )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; + } + if(strpos($spalte, 'datum')) { + $spaltea = explode('.', $spalte); + if(count($spaltea) === 2){ + return ' ( DATE_FORMAT('.$spalte.",'%d.%m.%Y %H:%i:%s') LIKE '%".$this->app->DB->real_escape_string($sSearch )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; + } + }elseif(($numbercol || $spalte === 'soll' || $spalte === 'gesamtsumme') && strpos($sSearch,',')) + { + return ' ( '.$spalte." LIKE '%".$this->app->DB->real_escape_string(str_replace(',','.',$sSearch) )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; + }elseif((strpos($spalte, 'soll') || strpos($spalte, 'gesamtsumme')) && strpos($sSearch,',')) + { + $spaltea = explode('.', $spalte); + if(count($spaltea) === 2){ + return ' ( '.$spalte." LIKE '%".$this->app->DB->real_escape_string(str_replace(',','.',$sSearch) )."%' OR ".$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%') "; + } + } + if(count($sSearcha) > 1) + { + return ' ('.$this->AjaxTableWhereBuilderArray($spalte, $sSearcha).')'; + } + return ' ('.$spalte." LIKE '%".$this->app->DB->real_escape_string($sSearch )."%')"; + } + + protected function AjaxTableWhereBuilderArray($column, $sSearcha, $sSearcha2 = null) + { + if(empty($column) || empty($sSearcha)) + { + return ''; + } + $csSearcha = count($sSearcha); + $tmp = []; + foreach($sSearcha as $v) + { + $tmp[strtolower($v)] = 1+(!empty($tmp[strtolower($v)])?$tmp[strtolower($v)]:0); + } + if(count($tmp) === 1) + { + $sSearch = implode('%', $sSearcha); + + $sSearch2 = $this->app->erp->ConvertForTableSearch($sSearch); + if($sSearch2 === '') + { + $sWhere = "({$column} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; + }else{ + $sWhere = "({$column} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR + {$column} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; + } + return $sWhere; + } + + if(!empty($sSearcha2)) + { + $wherea = []; + foreach($tmp as $v => $c) { + if($c > 1) + { + $vold = $v; + for($i = 1; $i < $c; $i++) + { + $v .= '%'.$vold; + } + } + $vt = $this->app->erp->ConvertForTableSearch($v); + if($vt === '' || $vt === $v) + { + $vt = $this->app->erp->ConvertForDBUTF8($v); + } + if($v === '') + { + $v = $vt; + } + if($v !== $vt && $vt !== ''){ + $wherea[] = ' (' . $column . " LIKE '%" . $v . "%' OR " . $column . " LIKE '%" . $vt . "%') "; + }else{ + + $wherea[] = ' (' . $column . " LIKE '%" . $v . "%') "; + } + } + return '('.implode(' AND ',$wherea).')'; + }else{ + $wherea = []; + foreach($tmp as $v => $c) { + if($c > 1) + { + $vold = $v; + for($i = 1; $i < $c; $i++) + { + $v .= '%'.$vold; + } + } + $wherea[] = $column." LIKE '%".$v."%'"; + } + return '('.implode(' AND ',$wherea).')'; + } + } + + + + public function AjaxTable() + { + $iDisplayStart = $this->app->Secure->GetGET('iDisplayStart'); + $iDisplayLength = $this->app->Secure->GetGET('iDisplayLength'); + $iSortCol_0 = $this->app->Secure->GetGET('iSortCol_0'); + $sSortDir_0 = $this->app->Secure->GetGET('sSortDir_0'); + $iSortingCols = $this->app->Secure->GetGET('iSortingCols'); + $sSearch = $this->app->Secure->GetGET('sSearch'); + $sEcho = $this->app->Secure->GetGET('sEcho'); + $cmd = $this->app->Secure->GetGET('cmd'); + $frommodule = $this->app->Secure->GetGET('frommodule'); + $fromclass = $this->app->Secure->GetGET('fromclass'); + $sSearch = trim($sSearch); + $sSearch = str_replace('%','\%',$sSearch); + + $sSearch2 = $sSearch; + $sSearch3 = $this->app->erp->ConvertForDB($sSearch); + $sSearch = $this->app->erp->ConvertForDBUTF8($sSearch); + if($this->app->Secure->GetGet('deferLoading')){ + echo '{"sEcho":'.(int)$sEcho.',"iTotalRecords":0,"iTotalDisplayRecords":0,"aaData":[]}'; + $this->app->ExitXentral(); + } + + + $YUIs = $this->app->YUI->TableSearch('',$cmd,'ALL','','',$frommodule, $fromclass); + $starttime = microtime(true); + $limiert = false; + if(method_exists($this->app->erp, 'BegrenzungLivetabelle')) + { + $limiert = 2*$this->app->erp->BegrenzungLivetabelle($cmd, $this->app->DB->real_escape_string( $iDisplayLength )); + } + $maxrows = 0; + if(isset($YUIs['maxrows']) && $YUIs['maxrows'] > 0) + { + $maxrows = $YUIs['maxrows']; + } + $sLimit = ''; + if($limiert) + { + $limiert += (int) $iDisplayStart ; + $iDisplayLength = $iDisplayLength ; + if(($maxrows > 0) && $iDisplayLength > $maxrows){ + $iDisplayLength = $maxrows; + } + $sLimit = 'LIMIT '. $iDisplayStart .', '. ( $limiert ); + }else{ + if ( isset($iDisplayStart) ) + { + $iDisplayLength = $iDisplayLength ; + if(($maxrows > 0) && $iDisplayLength > $maxrows) + { + $iDisplayLength = $maxrows; + } + $sLimit = 'LIMIT '. $iDisplayStart .', '. $iDisplayLength ; + } + } + /* Ordering */ + + // check if is allowed + if(!$this->app->erp->TableSearchAllowed($cmd)) + { + $this->app->erp->Protokoll("Nicht erlaubter Zugriff auf $cmd von Benutzer ".$this->app->User->GetName()); + $this->app->erp->ExitWawi(); + } + + + + //$findcolstmp = $this->app->YUI->TableSearch("",$cmd,"findcols","","",$frommodule, $fromclass); + $findcolstmp = $YUIs['findcols']; + //$moreinfo = $this->app->YUI->TableSearch("",$cmd,"moreinfo","","",$frommodule, $fromclass); + $moreinfo = $YUIs['moreinfo']; + + if (isset($iSortCol_0) || ($moreinfo && $iSortCol_0 < 1)) + { + if($moreinfo){ + if(!($iSortCol_0 < 1)){ + $iSortCol_0++; + } + }else{ + $iSortCol_0++; + + } + if($iSortCol_0 < 1){ + $iSortCol_0 = 1; + } + + if(trim($findcolstmp[$iSortCol_0 - 1]) == 'belegnr' || + strpos($findcolstmp[$iSortCol_0 - 1], '.belegnr') !== false){ + if(preg_match_all('/([a-zA-Z0-9]*)(\.*)belegnr/', $findcolstmp[$iSortCol_0 - 1], $ergebnis)){ + if(isset($ergebnis[1][0]) && !isset($ergebnis[1][1])){ + $findcolstmp[$iSortCol_0 - 1] = $this->app->erp->BelegnummerSortierung($ergebnis[1][0]); + } + } + } + + $sOrder = 'ORDER BY ' . $findcolstmp[$iSortCol_0 - 1] . " $sSortDir_0"; + } + else + { + //standard einstellung nach datum absteigend wenn datumsspalte vorhanden + //$defaultorder = $this->app->YUI->TableSearch("",$cmd,"defaultorder","","",$frommodule, $fromclass); + $defaultorder = $YUIs['defaultorder']; + //$defaultorderdesc = $this->app->YUI->TableSearch("",$cmd,"defaultorderdesc","","",$frommodule, $fromclass); + $defaultorderdesc = $YUIs['defaultorderdesc']; + if($defaultorder<=0) { + $defaultorder = count($findcolstmp); + $defaultorderdesc = 1; + } + + if($defaultorderdesc=='1') { + $defaultorderdesc = ' DESC'; + } else { + $defaultorderdesc=''; + } + + + if($defaultorder >=0 && is_numeric($defaultorder)) + { + $defaultorder++; + //$findcolstmp = $this->app->YUI->TableSearch("",$cmd,"findcols","","",$frommodule, $fromclass); + $findcolstmp = $YUIs['findcols']; + if($defaultorder < 2) + { + $defaultorder = 2; + } + $sOrder = 'ORDER BY '.$findcolstmp[$defaultorder-2]." $defaultorderdesc"; + }else + { + $sOrder = 'ORDER BY '.$findcolstmp[0]." $defaultorderdesc"; + } + } + + + /* Filtering - NOTE this does not match the built-in DataTables filtering which does it + * word by word on any field. It's possible to do here, but concerned about efficiency + * on very large tables, and MySQL's regex functionality is very limited + */ + + $sWhere = ''; + //$where = $this->app->YUI->TableSearch("",$cmd,"where","","",$frommodule, $fromclass); + $where = $YUIs['where']; + //echo $where; + + $matchesql = !empty($YUIs['matchesql'])?$YUIs['matchesql']:''; + + if ($sSearch != '' && !empty($matchesql) && !empty($matchesql['sqlpre'])) + { + while(strpos($sSearch,' ') !== false) + { + $sSearch = str_replace(' ',' ', $sSearch); + } + while(strpos($sSearch2,' ') !== false) + { + $sSearch2 = str_replace(' ',' ', $sSearch2); + } + $sSearch = str_replace('%','%',$sSearch); + $sSearch2 = str_replace('%','%',$sSearch2); + $sSearcha = explode(' ', $sSearch); + $sSearcha2 = explode(' ', $sSearch2); + $sSearch = str_replace(' ','%',$sSearch); + $sSearch2 = str_replace(' ','%',$sSearch2); + $YUIs['sql'] = $matchesql['sqlpre']; + $unions = []; + foreach($matchesql['elements'] as $keyEl => $SqlElement) + { + $SqlElementQuery = $SqlElement['sql'].' WHERE '; + $whereArr = []; + $firstsubwhere = true; + if(!empty($SqlElement['where'])) + { + foreach($SqlElement['where'] as $keyWhere => $valWhere) + { + if(!$firstsubwhere) + { + $SqlElementQuery .= ' OR '; + } + if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) + { + if(count($sSearcha) > 1) + { + $SqlElementQuery .= $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha, $sSearcha2); + }else{ + $SqlElementQuery .= "({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR + {$valWhere} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; + } + }else{ + if(count($sSearcha) > 1) + { + $SqlElementQuery .= $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha); + }else{ + $SqlElementQuery .= "({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; + } + } + if($sSearch2!='' && ($sSearch2 !== $sSearch)) + { + if($this->app->DB->real_escape_string( $sSearch2 ) !== $this->app->erp->ConvertForTableSearch( $sSearch2 )) + { + $SqlElementQuery .=" OR ({$valWhere} LIKE '%".$this->app->DB->real_escape_string( $sSearch2 )."%' OR {$valWhere} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch2 )."%' ) "; + }else{ + if(count($sSearcha) > 1) + { + $SqlElementQuery .= ' OR ('. $this->AjaxTableWhereBuilderArray($valWhere, $sSearcha2).') '; + }else{ + $SqlElementQuery .= " OR ({$valWhere} LIKE '%" . $this->app->DB->real_escape_string($sSearch2) . "%') "; + } + } + } + $firstsubwhere = false; + } + } + if(!empty($SqlElement['match'])) + { + if(!$firstsubwhere) + { + $SqlElementQuery .= ' OR '; + } + $sSearchArr = explode('%', str_replace(['+','-','*','~'],['%','','%','%'], $sSearch)); + foreach($sSearchArr as $keyS => $keyv) + { + if(strlen($keyv) === 0) + { + unset($sSearchArr[$keyS]); + } + } + + $sSearchMatch = ''; + foreach ($sSearchArr as $sSearchItem) { + // $sSearchItem enthält einzelne Wörter evtl. mit HTML-Entities + // Problem 1: Das Ampersand-Zeichen der HTML-Entities wird im BOOLEAN MODE als Worttrenner gesehen. + // Problem 2: Das Ampersand-Zeichen kann im BOOLEAN MODE nicht escaped werden. + // Die einzige Lösung ist das Suchwort mit doppelten Anführungszeichen zu umschließen, + // die Worttrenner-Eigenschaft des Ampersandzeichens wird damit aufgehoben. + // Der Nachteil bei dieser Lösung: Es werden nur noch ganze Wörter gefunden. + $sSearchMatch .= sprintf('+%s* ', $this->app->DB->real_escape_string($sSearchItem)); + } + $SqlElementQuery .= ' MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$sSearchMatch.'\' IN BOOLEAN MODE) '; + if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) + { + $SqlElementQuery .= ' OR MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$this->app->erp->ConvertForTableSearch($sSearchMatch).'\' IN BOOLEAN MODE) '; + } + elseif(!empty($sSearch2) && $sSearch2 !== $sSearch) { + $sSearchArr2 = explode('%', str_replace(['+','-','*','~'],['%','','%','%'], $sSearch2)); + foreach($sSearchArr2 as $keyS => $keyv) + { + if(strlen($keyv) === 0) { + unset($sSearchArr2[$keyS]); + } + } + $sSearchMatch2 = '+'.implode('* +', $sSearchArr2).'*'; + $SqlElementQuery .= ' OR MATCH('.implode(',',$SqlElement['match']).') AGAINST (\''.$this->app->DB->real_escape_string($sSearchMatch2).'\' IN BOOLEAN MODE) '; + } + } + $SqlElementQuery .= implode(' OR ', $whereArr); + $unions[] = $SqlElementQuery; + } + $YUIs['sql'] .= implode(' + UNION + ', $unions); + $YUIs['sql'] .= $matchesql['sqlpost']; + + if($where!=''){ + $sWhere = " WHERE $where "; + } + } + elseif ( $sSearch != '' ) { + /* + $sWhere = "WHERE a.nummer LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%' OR ". + "p.abkuerzung LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%' OR ". + "a.name_de LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; + */ + //$searchsql = $this->app->YUI->TableSearch("",$cmd,"searchsql","","",$frommodule, $fromclass); + $searchsql = $YUIs['searchsql']; + $searchsql2 = null; + $datesearchcol2 = null; + $datesearchcol = $YUIs['datesearchsols']; + if(is_array($searchsql)) + { + foreach($searchsql as $k => $v) + { + if(is_array($v)) + { + foreach($v as $k2 => $v2) + { + $searchsql2[] = $v2; + if($datesearchcol && in_array($k, $datesearchcol)) { + $datesearchcol2[] = count($searchsql2)-1; + } + } + }else{ + $searchsql2[] = $v; + if($datesearchcol && in_array($k, $datesearchcol)) + { + $datesearchcol2[] = count($searchsql2)-1; + } + } + } + } + if($where==''){ + $sWhere = ' WHERE ('; + } + else + { + if(count($searchsql) > 0){ + $sWhere = " WHERE $where AND ("; + } + else{ + $sWhere = " WHERE $where "; + } + } + + // Prozent austauschen da dies mysql wildcat ist + + while(strpos($sSearch,' ') !== false) + { + $sSearch = str_replace(' ',' ', $sSearch); + } + while(strpos($sSearch2,' ') !== false) + { + $sSearch2 = str_replace(' ',' ', $sSearch2); + } + + $sSearch = str_replace('%','%',$sSearch); + $sSearch2 = str_replace('%','%',$sSearch2); + + //$sSearch3 = str_replace('%','%',$sSearch3); + //$sSearch3 = str_replace(' ','%',$sSearch3); + + $sSearcha = explode(' ', $sSearch); + $sSearcha2 = explode(' ', $sSearch2); + //$sSearcha = []; + //$sSearcha2 = []; + + $sSearch = str_replace(' ','%',$sSearch); + $sSearch2 = str_replace(' ','%',$sSearch2); + + + $csearchsql2 = $searchsql2?count($searchsql2):0; + for($i=0;$i<$csearchsql2;$i++) + { + if($this->app->DB->real_escape_string( $sSearch ) !== $this->app->erp->ConvertForTableSearch( $sSearch )) + { + if($datesearchcol2 && in_array($i, $datesearchcol2)) + { + $sWhere .= '('.$this->AjaxTableWhereBuilder($searchsql2[$i], $sSearch, true, false).' OR '.$this->AjaxTableWhereBuilder($searchsql2[$i], $this->app->erp->ConvertForTableSearch( $sSearch ), true, false).")"; + }else{ + if(count($sSearcha) > 1) + { + $sWhere .= $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha, $sSearcha2); + }else{ + $sWhere .= "({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR + {$searchsql2[$i]} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%' ) "; + } + } + }else{ + if($datesearchcol2 && in_array($i, $datesearchcol2)) { + $sWhere .= $this->AjaxTableWhereBuilder($searchsql2[$i], $sSearch, true, false); + }else{ + if(count($sSearcha) > 1) + { + $sWhere .= $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha); + }else{ + $sWhere .= "({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') "; + } + } + } + + + if($sSearch2!='' && ($sSearch2 !== $sSearch)) + { + if($this->app->DB->real_escape_string( $sSearch2 ) !== $this->app->erp->ConvertForTableSearch( $sSearch2 )) + { + $sWhere .=" OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch2 )."%' OR {$searchsql2[$i]} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch2 )."%' ) "; + }else{ + if(count($sSearcha) > 1) + { + $sWhere .= ' OR ('. $this->AjaxTableWhereBuilderArray($searchsql2[$i], $sSearcha2).') '; + }else{ + $sWhere .= " OR ({$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch2) . "%') "; + } + } + } + + if($sSearch3!='' && ($sSearch3 !== $sSearch || $sSearch3 !== $sSearch2)) + { + if($this->app->DB->real_escape_string( $sSearch3 ) !== $this->app->erp->ConvertForTableSearch( $sSearch3 )) + { + $sWhere .= "OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch3 )."%' OR {$searchsql2[$i]} LIKE '%".$this->app->erp->ConvertForTableSearch( $sSearch3 )."%' ) OR "; + }else{ + $sWhere .= "OR ({$searchsql2[$i]} LIKE '%".$this->app->DB->real_escape_string( $sSearch3 )."%') OR "; + } + } + else { + $sWhere .= ' OR '; + } + } + + //$searchfulltext = $this->app->YUI->TableSearch("",$cmd,"searchfulltext","","",$frommodule, $fromclass); + $searchfulltext = $YUIs['searchfulltext']; + if($searchfulltext!='' && $sSearch!='') + { + $sSearch = str_replace('"','"',$sSearch); + $sSearch .= '*'; + $searchfulltext = ' MATCH(e.subject,e.sender,e.action,e.action_html) AGAINST (\''.$this->app->erp->ConvertForTableSearch($sSearch).'\' IN BOOLEAN MODE ) '; + } + if(count($searchsql2) > 0){ + if($searchfulltext == '') + { + $sWhere .= ' 0)'; + }else{ + $sWhere .= ' '.$searchfulltext.')'; + /*$i--; + if($searchfulltext != ''){ + $searchfulltext = ' OR ' . $searchfulltext; + } + if($this->app->DB->real_escape_string($sSearch) !== $this->app->erp->ConvertForTableSearch($sSearch)){ + $sWhere .= "( {$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%' OR {$searchsql2[$i]} LIKE '%" . $this->app->erp->ConvertForTableSearch($sSearch) . "%') $searchfulltext )"; + }else{ + $sWhere .= "( {$searchsql2[$i]} LIKE '%" . $this->app->DB->real_escape_string($sSearch) . "%') $searchfulltext )"; + }*/ + } + } else { + $sWhere .= " AND $searchfulltext"; + } + + } else { + if($where!=''){ + $sWhere = " WHERE $where "; + } + } + + + //$searchsql = $this->app->YUI->TableSearch("",$cmd,"searchsql","","",$frommodule, $fromclass); + $searchsql = $YUIs['searchsql']; + + //$moreinfo = $this->app->YUI->TableSearch("",$cmd,"moreinfo","","",$frommodule, $fromclass); + $moreinfo = $YUIs['moreinfo']; + if($moreinfo) { + $offset = 1; + } else { + $offset=0; + } + if(!$YUIs['columnfilter']) + { + $searchsql = $YUIs['findcols']; + $offset = 0; + } + $csearchsql = $searchsql?count($searchsql):0; + for($isearch=0;$isearch<$csearchsql;$isearch++) + { + $sSearch = $this->app->Secure->GetGET('sSearch_'.$isearch); + if($sSearch!='' && $sSearch!='A') + { + if(isset($searchsql[$isearch-$offset]) && is_array($searchsql[$isearch-$offset])) + { + $gef = false; + foreach($searchsql[$isearch-$offset] as $v) + { + if($v != '') + { + if($sWhere == '') + { + //$sWhere = "WHERE (".$v." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; + $sWhere = 'WHERE ('.$this->AjaxTableWhereBuilder($v, $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); + $gef = true; + }else{ + $sWhere = "$sWhere "; + if(!$gef) + { + $sWhere .= ' AND ('; + }else{ + $sWhere .= ' OR '; + } + //$sWhere .= " (".$v." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%')"; + $sWhere .= $this->AjaxTableWhereBuilder($v, $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); + $gef = true; + } + } + } + if($gef){ + $sWhere .= ' ) '; + } + }else{ + if($sWhere=='') + { + if($searchsql[$isearch-$offset]!='') + { + //$sWhere = "WHERE ".$searchsql[$isearch-$offset]." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%'"; + $sWhere = 'WHERE '.$this->AjaxTableWhereBuilder($searchsql[$isearch-$offset], $sSearch ,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ); + } + } + else + { + if($searchsql[$isearch-$offset]!='') + { + //$sWhere = "$sWhere AND (".$searchsql[$isearch-$offset]." LIKE '%".$this->app->DB->real_escape_string( $sSearch )."%')"; + $sWhere = "$sWhere AND (".$this->AjaxTableWhereBuilder($searchsql[$isearch-$offset], $sSearch,isset($YUIs['datecols']) && is_array($YUIs['datecols']) && in_array($isearch-$offset,$YUIs['datecols'])?true:false,isset($YUIs['numbercols']) && is_array($YUIs['numbercols']) && in_array($isearch-$offset,$YUIs['numbercols'])?true:false ).")"; + } + } + } + } + } + + + + //$tmp = $this->app->YUI->TableSearch("",$cmd,"sql","","",$frommodule, $fromclass); + $tmp = $YUIs['sql']; + //$groupby = $this->app->YUI->TableSearch("",$cmd,"groupby","","",$frommodule, $fromclass); + $groupby = $YUIs['groupby']; + //$orderby = $this->app->YUI->TableSearch("",$cmd,"orderby","","",$frommodule, $fromclass); + $orderby = $YUIs['orderby']; + + $fastcount = isset($YUIs['fastcount'])?$YUIs['fastcount']:''; + if($orderby){ + $sOrder = $orderby; + } + $uid = $this->app->Secure->GetGET('uid'); + $pid = $this->app->User->GetParameter('tablesearch_'.$uid); + if(!empty($pid)) { + $pid = explode('|',$pid); + $sEchoCheck = !empty($pid[1])?(int)$pid[1]:0; + $pid = reset($pid); + if($sEchoCheck < $sEcho && $pid != $this->app->DB->connection->thread_id){ + $this->app->DB->kill($pid); + } + $this->app->User->deleteParameter('tablesearch_'.$uid); + } + //$sQuery = $sWhere." ".$sOrder." ". $sLimit; + + //$rResult = $this->app->DB->Query( $sQuery); + $sQuery = " + $tmp + $sWhere + $groupby + $sOrder + $sLimit + "; + if($fastcount || $limiert){ + $sQuery = str_replace('SQL_CALC_FOUND_ROWS','',$sQuery); + } + + $jsarray = null; + if(isset($this->app->stringcleaner)) { + $jsarray = $this->app->stringcleaner->CheckSQLHtml($sQuery); + } + if($this->app->erp->Firmendaten('schnellsuchecount') && strpos($sQuery, 'SQL_CALC_FOUND_ROWS')){ + $YUIs['count'] = ''; + } + + if(isset($YUIs['onequeryperuser']) && $YUIs['onequeryperuser']) { + $killId = $this->app->User->GetParameter('tablesearch_'.$cmd.'_id2'); + $killId = explode('|',$killId); + $sEchoCheck = !empty($killId[1])?(int)$killId[1]:0; + $killId = reset($killId); + if(!empty($killId) && $sEchoCheck < $sEcho) { + $this->app->DB->kill($killId); + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); + } + $killId = $this->app->User->GetParameter('tablesearch_'.$cmd.'_id'); + $killId = explode('|',$killId); + $sEchoCheck = !empty($killId[1])?(int)$killId[1]:0; + $killId = reset($killId); + if(!empty($killId) && $sEchoCheck < $sEcho) { + $this->app->DB->kill($killId); + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); + } + //TODO Alte Prozesse killen + $_sql = substr($this->app->YUI->CodiereSQLForOneQuery($tmp, $cmd),0, 100); + $processlist = $this->app->DB->SelectArr('SHOW PROCESSLIST'); + if(count($processlist) > 1) { + foreach($processlist as $v) { + if($v['Time'] > 1 && $v['db'] == $this->app->Conf->WFdbname && $v['User'] == $this->app->Conf->WFdbuser && substr($v['Info'], 0, 100) == $_sql) { + $this->app->DB->kill($v['Id']); + } + } + } + $this->app->User->SetParameter('tablesearch_'.$cmd.'_id', $this->app->DB->connection->thread_id); + } + $maxExecutionTime = 300; + if($cmd === 'report_table') { + $maxExecutionTime = 30; + } + $useasync = function_exists('mysqli_poll'); + if($useasync) { + ignore_user_abort(true); + $db2 = $this->app->DB->getClone(); + $threadid = $db2->connection->thread_id; + $this->app->User->SetParameter('tablesearch_'.$uid, $threadid.'|'.$sEcho); + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); + } + + $startExecutionTime = microtime(true); + $rResult = $db2->Query($sQuery, true); + $all_links = array($db2->connection); + $processed = 0; + do { + echo ' '; + flush(); + ob_flush(); + if(connection_aborted() == 1 + || ($maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) + ) { + $this->app->DB->kill($threadid); + if((int)$this->app->User->GetParameter('tablesearch_'.$uid) == $threadid) { + $this->app->User->deleteParameter('tablesearch_'.$uid); + } + exit; + } + $links = $errors = $reject = array(); + foreach ($all_links as $link) { + $links[] = $errors[] = $reject[] = $link; + } + if (!mysqli_poll($links, $errors, $reject, 0,50000)) { + continue; + } + foreach ($links as $link) { + if ($rResult = $link->reap_async_query()) { + break 2; + }; + $processed++; + } + } while ($processed < count($all_links)); + } + else{ + $rResult = $this->app->DB->Query($sQuery); + } + if($cmd === 'adresse_brief' && $this->app->DB->error() && strpos($this->app->DB->error(), 'COLLATION \'utf8_general_ci\' is not valid for CHARACTER') !== false) + { + if((String)$this->app->erp->GetKonfiguration('adresse_crm_collateerror') === ''){ + $this->app->erp->SetKonfigurationValue('adresse_crm_collateerror', 1); + } + }elseif($cmd === 'adresse_brief' && $this->app->DB->error() && $this->app->erp->GetKonfiguration('adresse_crm_collateerror')) + { + $this->app->erp->SetKonfigurationValue('adresse_crm_collateerror', 0); + } + + $iTotal = 0; + if(!$limiert) { + if($fastcount) { + $sQuery = "$fastcount $sWhere"; + if($useasync) { + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); + } + $startExecutionTime = microtime(true); + $rResultFilterTotal = $db2->Query($sQuery, true); + $threadid = $db2->connection->thread_id; + $all_links = array($db2->connection); + $processed = 0; + do { + echo ' '; + flush(); + ob_flush(); + if(connection_aborted() == 1 || ( + $maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) + ){ + $this->app->DB->kill($threadid); + exit; + } + $links = $errors = $reject = array(); + foreach ($all_links as $link) { + $links[] = $errors[] = $reject[] = $link; + } + if(!mysqli_poll($links, $errors, $reject, 0, 50000)){ + continue; + } + foreach ($links as $link) { + if($rResultFilterTotal = $link->reap_async_query()){ + break 2; + }; + $processed++; + } + } while ($processed < count($all_links)); + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); + } + } + else { + $rResultFilterTotal = $this->app->DB->Query($sQuery); + } + $aResultFilterTotal = $this->app->DB->Fetch_Row($rResultFilterTotal); + $this->app->DB->free($rResultFilterTotal); + $iFilteredTotal = $aResultFilterTotal[0]; + } + else { + $sQuery = ' + SELECT FOUND_ROWS() + '; + if($useasync) { + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->SetParameter('tablesearch_'.$cmd.'_id2', $db2->connection->thread_id.'|'.$sEcho); + } + $startExecutionTime = microtime(true); + $rResultFilterTotal = $db2->Query($sQuery, true); + $threadid = $db2->connection->thread_id; + $all_links = array($db2->connection); + $processed = 0; + do { + echo ' '; + flush(); + ob_flush(); + if(connection_aborted() == 1 || ( + $maxExecutionTime > 0 && microtime(true) - $startExecutionTime > $maxExecutionTime) + ) { + $this->app->DB->kill($threadid); + exit; + } + $links = $errors = $reject = array(); + foreach ($all_links as $link) { + $links[] = $errors[] = $reject[] = $link; + } + if(!mysqli_poll($links, $errors, $reject, 0, 50000)){ + continue; + } + foreach ($links as $link) { + if($rResultFilterTotal = $link->reap_async_query()){ + break 2; + }; + $processed++; + } + } while ($processed < count($all_links)); + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id2'); + } + } + else { + $rResultFilterTotal = $this->app->DB->Query($sQuery); + } + $aResultFilterTotal = $this->app->DB->Fetch_Row($rResultFilterTotal); + $this->app->DB->free($rResultFilterTotal); + $iFilteredTotal = $aResultFilterTotal[0]; + } + } + if($useasync) { + echo ' '; + flush(); + ob_flush(); + if(connection_aborted() == 1) { + if(!empty($db2)) { + $db2->Close(); + } + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); + } + $this->app->DB->Close(); + exit; + } + } + /* + $sQuery = " + SELECT COUNT(id) + FROM artikel + "; + */ + //$sQuery = $this->app->YUI->TableSearch("",$cmd,"count","","",$frommodule, $fromclass); + if(!$limiert){ + $sQuery = $YUIs['count']; + if((String)$sQuery !== '') { + $rResultTotal = $this->app->DB->Query( $sQuery); + + $aResultTotal = $this->app->DB->Fetch_Array($rResultTotal); + $this->app->DB->free($rResultTotal); + $iTotal = (int)$aResultTotal[0]; + } + else { + $iTotal = !empty($iFilteredTotal)?(int)$iFilteredTotal:0; + } + $this->app->erp->CheckBegrenzungLiveTabelle($cmd, $iTotal, microtime(true)-$starttime); + } + elseif(!empty($YUIs['cached_count'])) { + $aResultTotal = $this->app->DB->SelectArrCache($YUIs['cached_count'], 180, 'tablesearch_count'); + if(!empty($aResultTotal)) { + $iTotal = reset($aResultTotal); + $iTotal = reset($iTotal); + } + } + if(method_exists($this->app->erp,'CheckSchnellsuche')) { + $this->app->erp->CheckSchnellsuche($cmd, $iTotal, microtime(true) - $starttime); + } + //$heading = count($this->app->YUI->TableSearch("",$cmd,"heading","","",$frommodule, $fromclass)); + $heading = count($YUIs['heading']); + //$menu = $this->app->YUI->TableSearch("",$cmd,"menu","","",$frommodule, $fromclass); + $menu = $this->app->Tpl->ParseTranslation($YUIs['menu']); + $sOutput2 = ''; + $rowc = 0; + while ( $aRow = $this->app->DB->Fetch_Row( $rResult )) { + $rowc++; + if(!$limiert || ($rowc <= $iDisplayLength)) { + $sOutput2 .= '['; + for($i=1;$i<$heading;$i++) { + /*if(strpos($aRow[$i],'<') !== false) //30.07.2018 Bruno Entfernt wegen fehlerhaften Entfernen von Tags + { + if($jsarray && isset($jsarray[$i]) && !$jsarray[$i]) + { + $aRow[$i] = strip_tags($aRow[$i]); + }elseif(isset($jsarray[$i]) && 1 == $jsarray[$i]) + { + $aRow[$i] = $this->app->stringcleaner->xss_clean($aRow[$i], false); + } + }*/ + $aRow[$i] = $this->EntferneSteuerzeichen(trim(str_replace("'",''',$aRow[$i]))); + $aRow[$i] = str_replace("\r",'',$aRow[$i]); + $aRow[$i] = str_replace("\n",'',$aRow[$i]); + $sOutput2 .= '"'.addslashes($aRow[$i]).'",'; + } + + $sOutput2 .= '"'.addslashes(str_replace('%value%',$aRow[$i],$menu)).'"'; + + $sOutput2 .= '],'; + } + } + if($limiert) { + $sOutput = '{'; + $sOutput .= '"sEcho": '.(int)$sEcho.', '; + $sOutput .= '"iTotalRecords": '.(!empty($iTotal)?$iTotal:$rowc+(int)$iDisplayStart).', '; + $sOutput .= '"iTotalDisplayRecords": '.($rowc+(int)$iDisplayStart).', '; + $sOutput .= '"aaData": [ '; + } + else{ + $sOutput = '{'; + $sOutput .= '"sEcho": '.(int)$sEcho.', '; + $sOutput .= '"iTotalRecords": '.$iTotal.', '; + $sOutput .= '"iTotalDisplayRecords": '.$iFilteredTotal.', '; + $sOutput .= '"aaData": [ '; + } + $sOutput .= $sOutput2; + + $sOutput = substr_replace( $sOutput, "", -1 ); + $sOutput .= '] }'; + + $sOutput = str_replace("\t",'',$sOutput); + + // Eventuell deutsches Datumsformat in allen Tabellen und sortieren geht auch + //$repl = preg_replace('~\"([1-2]{1}\d{3})-(\d{2})-(\d{2})\"~', '" $3.$2.$1"', $sOutput); + //$repl = preg_replace('~\"([1-2]{1}\d{3})-(\d{2})-(\d{2})\s+~', '" $3.$2.$1 ', $repl); + //$repl = preg_replace('~\s+([1-2]{1}\d{3})-(\d{2})-(\d{2})\s+~', ' $3.$2.$1 ', $repl); + //$repl = preg_replace('~\"(\d{4})-(\d{2})-(\d{2})\"~', '"$3.$2.$1"', $sOutput); + $repl = $sOutput; + $repl = $this->app->erp->ClearDataBeforeOutput($repl); + $repl = json_encode(json_decode($repl)); + echo $repl; + if(!empty($YUIs['onequeryperuser'])) { + $this->app->User->deleteParameter('tablesearch_'.$cmd.'_id'); + } + $this->app->erp->ExitWawi(); + } + + /** + * @return void + */ + public function AjaxLiveTable(): void + { + /** @var Request request */ + $request = $this->app->Container->get('Request'); + $tableName = $request->get->get('srctable', ''); + $module = $request->get->get('srcmodule', ''); + $className = $request->get->get('srcclass', ''); + $className = StringUtil::toTitleCase($className, '-'); + + $this->app->BuildNavigation=false; + + if (empty($tableName)) { + $this->app->Tpl->Set( + 'MESSAGE', + '
Fehler: Tabelle ist nicht spezifiziert.
' + ); + $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); + + return; + } + + if ((empty($module) xor empty($className))) { + $this->app->Tpl->Set( + 'MESSAGE', + '
Fehler: Tabelle kann nicht gefunden werden.
' + ); + $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); + + return; + } + + if (!empty($module) && !str_ends_with(strtolower($module), '.php')) { + $module .= '.php'; + } + + $this->app->YUI->TableSearch('LIVETABLE', $tableName, 'show', '', '', $module, $className); + $this->app->Tpl->Parse('PAGE', 'livetable_async.tpl'); + } + + protected function EntferneSteuerzeichen($string) + { + $len = strlen($string); + $out = ''; + for($i = 0; $i < $len; $i++) { + $ord = ord($string[$i]); + if($ord != 127 && ($ord > 31 || $ord == 13 || $ord == 10 || $ord == 9)) { + $out .= $string[$i]; + } + } + return $out; + } + + protected function fnColumnToFieldPosition( $i ) + { + $cmd = $this->app->Secure->GetGET('cmd'); + $findcols = $this->app->YUI->TablePositionSearch('',$cmd,'findcols'); + + return !empty($findcols[$i])?$findcols[$i]:0; + } + + protected function fnColumnToField( $i ) + { + $cmd = $this->app->Secure->GetGET('cmd'); + $frommodule = $this->app->Secure->GetGET('frommodule'); + $fromclass = $this->app->Secure->GetGET('fromclass'); + $findcols = $this->app->YUI->TableSearch('',$cmd,'findcols','','',$frommodule, $fromclass); + + return $findcols[$i]; + } + +} + diff --git a/www/pages/artikel.php b/www/pages/artikel.php index 1274d722..54d5bdee 100644 --- a/www/pages/artikel.php +++ b/www/pages/artikel.php @@ -3678,7 +3678,14 @@ class Artikel extends GenArtikel { $id = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer='$id' AND intern_gesperrt!=1 LIMIT 1"); $warnung = 1-(int)$this->app->DB->Select("SELECT if(rabatt=1,1,vkmeldungunterdruecken) FROM artikel WHERE id = '$id' LIMIT 1"); $adresse = $this->app->DB->Select("SELECT adresse FROM $smodule WHERE id='$sid' LIMIT 1"); - $waehrung = $this->app->DB->Select("SELECT waehrung FROM $smodule WHERE id='$sid' LIMIT 1"); + + + if (!is_null($module)) { + if ($this->app->DB->Select("SHOW COLUMNS FROM `$module` LIKE 'waehrung'")) { + $waehrung = $this->app->DB->Select("SELECT waehrung FROM $smodule WHERE id='$sid' LIMIT 1"); + } + } + $posanz = (int)$this->app->DB->Select("SELECT count(id) FROM $smodule"."_position WHERE $smodule = '$sid'"); //if($posanz == 0){ // $waehrung = ''; diff --git a/www/pages/lieferschein.php b/www/pages/lieferschein.php index 7bc49b54..d3a0791e 100644 --- a/www/pages/lieferschein.php +++ b/www/pages/lieferschein.php @@ -1,2569 +1,2573 @@ -erp->ModulVorhanden('batches'); - $projectCol = 'p.abkuerzung'; - $abJoin = ''; - if($useProjectAb) { - $projectCol = 'IFNULL(pab.abkuerzung ,p.abkuerzung)'; - $abJoin = ' LEFT JOIN auftrag AS ab ON l.auftragid = ab.id - LEFT JOIN projekt AS pab ON ab.projekt = pab.id '; - } - switch($name) - { - case 'lieferscheineinbearbeitung': - $allowed['lieferschein'] = array('create', 'list'); - - // headings - $heading = array('', 'Lieferschein', 'Vom', 'Kd-Nr./Lf-Nr.', 'Kunde/Lieferant', 'Land', 'Projekt', 'Versand', 'Art', 'Status', 'Menü'); - $width = array('1%', '10%', '10%', '10%', '35%', '5%', '1%', '1%', '1%', '1%', '1%', '1%'); - $findcols = array('open', 'l.belegnr', 'l.datum', 'if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer)', 'l.name', 'l.land', $projectCol, 'l.versandart', 'l.lieferscheinart', 'l.status', 'id'); - $searchsql = array('l.id', 'DATE_FORMAT(l.datum,\'%d.%m.%Y\')', 'l.belegnr', 'if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer)', 'l.name', 'l.land', $projectCol, 'l.status', 'l.plz', 'l.id', 'adr.freifeld1', 'l.ihrebestellnummer','l.internebezeichnung','l.versandart'); - $defaultorder = 11; //Optional wenn andere Reihenfolge gewuenscht - - $defaultorderdesc = 1; - $menu = "
Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\">" . - " Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">" . - - // " app->Conf->WFconf['defaulttheme']}/images/stamp.png\" border=\"0\">". - " Conf->WFconf['defaulttheme']}/images/pdf.svg\" border=\"0\">". - " "."
"; - $menucol = 10; - - // SQL statement - $sql = "SELECT SQL_CALC_FOUND_ROWS l.id,'Conf->WFconf['defaulttheme']}/images/details_open.png class=details>' as open, 'ENTWURF' as belegnr, DATE_FORMAT(l.datum,'%d.%m.%Y') as vom, if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer) as kundennummer, - CONCAT(" . $app->erp->MarkerUseredit("l.name", "l.useredittimestamp") . ", if(l.internebezeichnung!='',CONCAT('
',l.internebezeichnung,''),'')) as kunde, - l.land as land, $projectCol as projekt, l.versandart as versandart, - l.lieferscheinart as art, UPPER(l.status) as status, l.id - FROM lieferschein AS l - LEFT JOIN projekt AS p ON p.id=l.projekt - LEFT JOIN adresse AS lfr ON l.lieferant=lfr.id - LEFT JOIN adresse AS adr ON l.adresse=adr.id ".$abJoin; - $where = " ( l.status='angelegt') " . $app->erp->ProjektRechte('p.id', true, 'l.vertriebid'); - - // gesamt anzahl - $count = "SELECT COUNT(l.id) FROM lieferschein l WHERE ( l.status='angelegt')"; - $moreinfo = true; - break; - case 'lieferscheineoffene': - $allowed['lieferschein'] = array('list'); - - // headings - $heading = array('', 'Lieferschein', 'Vom', 'Kd-Nr.', 'Kunde', 'Land', 'Projekt', 'Versand', 'Art', 'Status', 'Menü'); - $width = array('1%', '10%', '10%', '10%', '35%', '5%', '1%', '1%', '1%', '1%', '1%', '1%'); - $findcols = array('open', 'l.belegnr', 'l.datum', 'if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer)', 'l.name', 'l.land',$projectCol, 'l.versandart', 'l.lieferscheinart', 'l.status', 'id'); - $searchsql = array('l.id', 'DATE_FORMAT(l.datum,\'%d.%m.%Y\')', 'l.belegnr', 'if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer)', 'l.name', 'l.land', $projectCol, 'l.status', 'l.plz', 'l.id', 'adr.freifeld1', 'l.ihrebestellnummer','l.internebezeichnung','l.versandart'); - $defaultorder = 11; //Optional wenn andere Reihenfolge gewuenscht - - $defaultorderdesc = 1; - $menu = "
Conf->WFconf['defaulttheme']}/images/edit.svg\" border=\"0\">" . " Conf->WFconf['defaulttheme']}/images/delete.svg\" border=\"0\">" . - - // " app->Conf->WFconf['defaulttheme']}/images/stamp.png\" border=\"0\">". - " Conf->WFconf['defaulttheme']}/images/pdf.svg\" border=\"0\">
"; - $menucol = 10; - - // SQL statement - $sql = "SELECT SQL_CALC_FOUND_ROWS l.id,'Conf->WFconf['defaulttheme']}/images/details_open.png class=details>' as open, l.belegnr, DATE_FORMAT(l.datum,'%d.%m.%Y') as vom, if(l.lieferantenretoure=1,lfr.lieferantennummer,adr.kundennummer) as kundennummer, - CONCAT(" . $app->erp->MarkerUseredit("l.name", "l.useredittimestamp") . ", if(l.internebezeichnung!='',CONCAT('
',l.internebezeichnung,''),'')) as kunde, - l.land as land, $projectCol as projekt, l.versandart as versandart, - l.lieferscheinart as art, UPPER(l.status) as status, l.id - FROM lieferschein AS l - LEFT JOIN projekt AS p ON p.id=l.projekt - LEFT JOIN adresse AS lfr ON l.lieferant=lfr.id - LEFT JOIN adresse AS adr ON l.adresse=adr.id ".$abJoin; - $where = " l.id!='' AND l.status='freigegeben' " . $app->erp->ProjektRechte('p.id', true, 'l.vertriebid'); - - // gesamt anzahl - $count = "SELECT COUNT(l.id) FROM lieferschein l WHERE l.status='freigegeben'"; - $moreinfo = true; - break; - case "lieferschein_seriennummern_assistent": - $id = $app->Secure->GetGET('id'); - $heading = array('Artikel-Nr.','Artikel','Lagerplatz','Seriennummer','Menü'); - $width = array('10%','10%','10%','10%', '1%'); - $findcols = array('art.nummer','art.name_de','t2.seriennummer','lag.kurzbezeichnung','t2.id'); - $searchsql = array('art.nummer','art.name_de','t2.seriennummer','lag.kurzbezeichnung' ); - - $sql = "SELECT SQL_CALC_FOUND_ROWS t2.id, art.nummer, art.name_de, lag.kurzbezeichnung, t2.seriennummer ,CONCAT('this,',t2.menge) - FROM ( - SELECT ls.id, t.artikel, t.menge, count(s.id) as co, ls.seriennummer, ls.lager_platz - FROM lager_seriennummern AS ls - INNER JOIN - ( - SELECT lp.artikel, sum(menge) as menge - FROM lieferschein_position AS lp - WHERE lp.lieferschein = '$id' - GROUP BY lp.artikel - ) AS t ON ls.artikel = t.artikel - LEFT JOIN seriennummern s ON s.artikel = t.artikel AND s.lieferschein = '$id' AND s.seriennummer <> '' - GROUP BY ls.id, t.artikel - ) AS t2 - INNER JOIN artikel AS art ON t2.artikel = art.id - INNER JOIN lager_platz AS lag ON t2.lager_platz = lag.id - - "; - - $menu = "Conf->WFconf['defaulttheme']}/images/forward.svg border=\"0\">"; - - $where = "t2.menge > t2.co "; - $count = "SELECT count(t2.id) - FROM (SELECT ls.id, t.artikel, t.menge, count(s.id) as co, ls.seriennummer, ls.lager_platz - FROM lager_seriennummern ls - INNER JOIN - (SELECT lp.artikel, sum(menge) as menge - FROM lieferschein_position lp WHERE lp.lieferschein = '$id') t - ON ls.artikel = lp.artikel LEFT JOIN seriennummern s ON s.artikel = t.artikel AND s.lieferschein = '$id' AND s.seriennummer <> '' - GROUP BY ls.id, t.artikel) t2 - INNER JOIN artikel art ON t2.artikel = art.id - INNER JOIN lager_platz lag ON t2.lager_platz = lag.id - WHERE $where"; - - - - break; - - } - - $erg = []; - - foreach($erlaubtevars as $k => $v) - { - if(isset($$v)){ - $erg[$v] = $$v; - } - } - return $erg; - } - - /** @var Application $app */ - function __construct($app, $intern = false) - { - $this->app=$app; - if($intern)return; - $this->app->ActionHandlerInit($this); - - $this->app->ActionHandler("list","LieferscheinList"); - $this->app->ActionHandler("create","LieferscheinCreate"); - $this->app->ActionHandler("paketmarke","LieferscheinPaketmarke"); - $this->app->ActionHandler("positionen","LieferscheinPositionen"); - $this->app->ActionHandler("uplieferscheinposition","UpLieferscheinPosition"); - $this->app->ActionHandler("dellieferscheinposition","DelLieferscheinPosition"); - $this->app->ActionHandler("copylieferscheinposition","CopyLieferscheinPosition"); - $this->app->ActionHandler("downlieferscheinposition","DownLieferscheinPosition"); - $this->app->ActionHandler("positioneneditpopup","LieferscheinPositionenEditPopup"); - $this->app->ActionHandler("edit","LieferscheinEdit"); - $this->app->ActionHandler("copy","LieferscheinCopy"); - $this->app->ActionHandler("delete","LieferscheinDelete"); - $this->app->ActionHandler("freigabe","LieferscheinFreigabe"); - $this->app->ActionHandler("abschicken","LieferscheinAbschicken"); - $this->app->ActionHandler("abschliessen","LieferscheinAbschliessen"); - $this->app->ActionHandler("auslagern","LieferscheinAuslagern"); - $this->app->ActionHandler("pdf","LieferscheinPDF"); - $this->app->ActionHandler("inlinepdf","LieferscheinInlinePDF"); - $this->app->ActionHandler("protokoll","LieferscheinProtokoll"); - $this->app->ActionHandler("minidetail","LieferscheinMiniDetail"); - $this->app->ActionHandler("minidetailkommissionierung","LieferscheinMiniDetailkommissionierung"); - $this->app->ActionHandler("editable","LieferscheinEditable"); - $this->app->ActionHandler("livetabelle","LieferscheinLiveTabelle"); - $this->app->ActionHandler("schreibschutz","LieferscheinSchreibschutz"); - $this->app->ActionHandler("positionenetiketten","LieferscheinPositionenEtiketten"); - $this->app->ActionHandler("rechnung","LieferscheinRechnung"); - $this->app->ActionHandler("proformarechnung","LieferscheinProformarechnung"); - $this->app->ActionHandler("dateien","LieferscheinDateien"); - $this->app->ActionHandler("pdffromarchive","LieferscheinPDFfromArchiv"); - $this->app->ActionHandler("archivierepdf","LieferscheinArchivierePDF"); - - $this->app->DefaultActionHandler("list"); - - $id = $this->app->Secure->GetGET("id"); - $nummer = $this->app->Secure->GetPOST("adresse"); - - if($nummer==''){ - if($id > 0){ - $adresse = $this->app->DB->Select("SELECT a.name FROM lieferschein b INNER JOIN adresse a ON a.id=b.adresse WHERE b.id='$id' LIMIT 1"); - }else{ - $adresse = 0; - } - } - else{ - $adresse = $nummer; - } - if($id > 0){ - $nummer = $this->app->DB->Select("SELECT b.belegnr FROM lieferschein b LEFT JOIN adresse a ON a.id=b.adresse WHERE b.id='$id' LIMIT 1"); - }else{ - $nummer = ''; - } - if($nummer=="" || $nummer==0) $nummer="ohne Nummer"; - - $this->app->Tpl->Set('UEBERSCHRIFT',"Lieferschein: ".$adresse." (".$nummer.")"); - $this->app->Tpl->Set('FARBE',"[FARBE3]"); - - $this->app->erp->Headlines('Lieferschein'); - - $this->app->ActionHandlerListen($app); - } - - public function Install(){ - $this->app->erp->RegisterHook('supersearch_detail', 'lieferschein', 'LieferscheinSupersearchDetail'); - } - - /** - * @param \Xentral\Widgets\SuperSearch\Query\DetailQuery $detailQuery - * @param \Xentral\Widgets\SuperSearch\Result\ResultDetail $detailResult - * - * @return void - */ - public function LieferscheinSupersearchDetail($detailQuery, $detailResult) - { - if($detailQuery->getGroupKey() === 'deliverynote'){ - $this->LieferscheinSupersearchDetailDeliveryNote($detailQuery, $detailResult); - } - if ($detailQuery->getGroupKey() === 'trackingnumber') { - $this->LieferscheinSupersearchDetailTrackingNumber($detailQuery, $detailResult); - } - } - - /** - * @param \Xentral\Widgets\SuperSearch\Query\DetailQuery $detailQuery - * @param \Xentral\Widgets\SuperSearch\Result\ResultDetail $detailResult - * - * @return void - */ - public function LieferscheinSupersearchDetailDeliveryNote($detailQuery, $detailResult) - { - if ($detailQuery->getGroupKey() !== 'deliverynote') { - return; - } - - $lieferscheinId = $detailQuery->getItemIdentifier(); - $sql = sprintf( - "SELECT l.id, l.belegnr, l.datum FROM `lieferschein` AS `l` WHERE l.id = '%s' LIMIT 1", - $this->app->DB->real_escape_string($lieferscheinId) - ); - $lieferschein = $this->app->DB->SelectRow($sql); - if (empty($lieferschein)) { - return; - } - - $datum = date('d.m.Y', strtotime($lieferschein['datum'])); - $detailResult->setTitle(sprintf('Lieferschein %s vom %s', $lieferschein['belegnr'], $datum)); - $detailResult->addButton('Lieferschein Details', sprintf('index.php?module=lieferschein&action=edit&id=%s', $lieferschein['id'])); - $detailResult->setMiniDetailUrl(sprintf('index.php?module=lieferschein&action=minidetail&id=%s', $lieferschein['id'])); - } - - /** - * @param \Xentral\Widgets\SuperSearch\Query\DetailQuery $detailQuery - * @param \Xentral\Widgets\SuperSearch\Result\ResultDetail $detailResult - * - * @return void - */ - public function LieferscheinSupersearchDetailTrackingNumber($detailQuery, $detailResult) - { - if ($detailQuery->getGroupKey() !== 'trackingnumber') { - return; - } - - $versandId = $detailQuery->getItemIdentifier(); - $sql = sprintf( - "SELECT v.lieferschein FROM `versand` AS `v` WHERE v.id = '%s' LIMIT 1", - $this->app->DB->real_escape_string($versandId) - ); - $lieferscheinId = $this->app->DB->Select($sql); - - $sql = sprintf( - "SELECT l.id, l.belegnr, l.datum FROM `lieferschein` AS `l` WHERE l.id = '%s' LIMIT 1", - $this->app->DB->real_escape_string($lieferscheinId) - ); - $lieferschein = $this->app->DB->SelectRow($sql); - if (empty($lieferschein)) { - return; - } - - $datum = date('d.m.Y', strtotime($lieferschein['datum'])); - $detailResult->setTitle(sprintf('Lieferschein %s vom %s', $lieferschein['belegnr'], $datum)); - $detailResult->addButton('Lieferschein Details', sprintf('index.php?module=lieferschein&action=edit&id=%s', $lieferschein['id'])); - $detailResult->setMiniDetailUrl(sprintf('index.php?module=lieferschein&action=minidetail&id=%s', $lieferschein['id'])); - } - - - function LieferscheinMiniDetailkommissionierung() - { - $id = (int)$this->app->Secure->GetGET('id'); - - $table = new EasyTable($this->app); - $table->Query("SELECT date_format(datum,'%d.%m.%Y') as Datum,belegnr as Lieferschein FROM lieferschein WHERE kommissionierung = '$id' ORDER BY id"); - echo $table->DisplayNew('return', 'Lieferschein', 'noAction'); - exit; - } - - /** - * @param int $deliveryNoteId - */ - public function archivePdf($deliveryNoteId) - { - if($deliveryNoteId <= 0) { - return; - } - $projectId = $this->app->DB->Select( - sprintf( - 'SELECT projekt FROM lieferschein WHERE id = %d LIMIT 1', - $deliveryNoteId - ) - ); - if(class_exists('LieferscheinPDFCustom')) { - $Brief = new LieferscheinPDFCustom($this->app, $projectId); - } - else{ - $Brief = new LieferscheinPDF($this->app, $projectId); - } - $Brief->GetLieferschein($deliveryNoteId); - $tmpfile = $Brief->displayTMP(); - $Brief->ArchiviereDocument(1); - unlink($tmpfile); - $this->app->DB->Update( - sprintf( - 'UPDATE lieferschein SET schreibschutz=1 WHERE id = %d', - $deliveryNoteId - ) - ); - } - - function LieferscheinArchivierePDF() - { - $id = (int)$this->app->Secure->GetGET('id'); - $this->archivePdf($id); - header('Location: index.php?module=lieferschein&action=edit&id='.$id); - exit; - } - - - function LieferscheinAbschliessen() { - - $id = $this->app->Secure->GetGET("id"); - - if($id > 0) - { - $this->app->DB->Update("UPDATE lieferschein SET status='abgeschlossen' WHERE id='$id' LIMIT 1"); - $this->app->erp->LieferscheinProtokoll($id,"Lieferschein abgeschlossen"); - $auftragid = $this->app->DB->Select("SELECT auftragid FROM lieferschein WHERE id='$id' LIMIT 1"); - if($auftragid && $this->app->erp->ModulVorhanden('produktion') && method_exists($this->app->erp, 'ProduktionEinzelnBerechnen')) - { - $produktionen = $this->app->DB->SelectArr("SELECT id FROM produktion WHERE auftragid = '$auftragid'"); - if($produktionen) - { - foreach($produktionen as $v)$this->app->erp->ProduktionEinzelnBerechnen($v['id']); - } - } - } - $msg = $this->app->erp->base64_url_encode("
Der Lieferschein wurde als abgeschlossen markiert!
"); - header("Location: index.php?module=lieferschein&action=list&msg=$msg"); - exit; - } - - function LieferscheinAuslagern() - { - $id = (int)$this->app->Secure->GetGET("id"); - - if($id > 0) - { - if($this->LieferscheinCheck($id)) - { - // wenn alles lagernd ist und nicht ausgelagert ist - $standardlager = $this->app->DB->Select("SELECT standardlager FROM lieferschein WHERE id = '$id' LIMIT 1"); - if($standardlager && $this->app->DB->Select("SELECT count(id) FROM lager") <= 1)$standardlager = 0; - $this->app->erp->LieferscheinAuslagern($id, true, $standardlager, 'lieferschein', 0, true); - $this->app->erp->RunHook('lieferschein_auslagern', 1, $id); - $msg = $this->app->erp->base64_url_encode("
Der Lieferschein wurde ausgelagert!
"); - } else { - if($this->LieferscheinCheck($id, true)) { - $article = $this->LieferscheinCheck($id, 'article'); - $typ = ''; - if(!empty($article)) { - $mhd = $article['mindesthaltbarkeitsdatum'] > 0; - $charge = $article['chargenverwaltung'] > 0; - $sn = $article['seriennummern'] != '' && $article['seriennummern'] !== 'keine'; - if($mhd && $charge) { - $typ = 'MHD/Chargen'; - } - elseif($mhd) { - $typ = 'MHDs'; - } - elseif($charge) { - $typ = 'Chargen'; - } - elseif($sn) { - $typ = 'Seriennummern'; - } - } - if(!empty($typ)) { - $msg = $this->app->erp->base64_url_encode( - "
Der Lieferschein kann nicht ausgelagert werden da zu wenig ".$typ." im Artikel ".$article['nummer']." vorhanden sind!
" - ); - } - else { - $msg = $this->app->erp->base64_url_encode( - "
Der Lieferschein kann nicht ausgelagert werden da zu wenig MHD/Chargen/Seriennummern in einem Artikel vorhanden sind!
" - ); - } - } - else{ - // wenn nur teilmenge ausgelagert werden konnte - $msg = $this->app->erp->base64_url_encode("
Der Lieferschein kann nicht ausgelagert werden da nicht alle Artikel vorhanden sind!
"); - } - } - - header("Location: index.php?module=lieferschein&action=edit&id=$id&msg=$msg"); - } - exit; - } - - function LieferscheinPaketmarke() - { - $id = $this->app->Secure->GetGET("id"); - - $versandart = $this->app->DB->Select("SELECT versandart FROM lieferschein WHERE id='$id' LIMIT 1"); - $projekt = $this->app->DB->Select("SELECT projekt FROM lieferschein WHERE id = '$id' LIMIT 1"); - $this->LieferscheinMenu(); - $this->app->Tpl->Set('TABTEXT',"Paketmarke"); - - $versandart = strtolower($versandart); - $versandartenmodul = $this->app->DB->SelectArr("SELECT id, modul FROM versandarten WHERE aktiv = 1 AND ausprojekt = 0 AND modul != '' AND type = '".$this->app->DB->real_escape_string($versandart)."' AND (projekt = '$projekt' || projekt = 0) ORDER BY projekt DESC LIMIT 1"); - if($versandartenmodul && is_file(dirname(__DIR__).'/lib/versandarten/'.$versandartenmodul[0]['modul'].'.php')) - { - $this->app->erp->Paketmarke('TAB1','lieferschein',"",$versandart); - }else{ - if($versandart=="dpd") - $this->app->erp->PaketmarkeDPDEmbedded('TAB1',"lieferschein"); - else if($versandart=="express_dpd") - $this->app->erp->PaketmarkeDPDEmbedded('TAB1',"lieferschein","express"); - else if($versandart=="export_dpd") - $this->app->erp->PaketmarkeDPDEmbedded('TAB1',"lieferschein","export"); - else if($versandart=="ups") - $this->app->erp->PaketmarkeUPSEmbedded('TAB1',"lieferschein"); - else if($versandart=="fedex") - $this->app->erp->PaketmarkeFEDEXEmbedded('TAB1',"lieferschein"); - else if($versandart=="go") - $this->app->erp->PaketmarkeGo('TAB1',"lieferschein"); - else { - $this->app->erp->Paketmarke('TAB1','lieferschein',"",""); - } - //$this->app->erp->PaketmarkeDHLEmbedded('TAB1',"lieferschein"); - } - $this->app->Tpl->Parse('PAGE',"tabview.tpl"); - } - - function LieferscheinEditable() - { - $this->app->YUI->AARLGEditable(); - } - - function LieferscheinSchreibschutz() - { - - $id = $this->app->Secure->GetGET("id"); - $this->app->DB->Update("UPDATE lieferschein SET zuarchivieren='1' WHERE id='$id'"); - $this->app->DB->Update("UPDATE lieferschein SET schreibschutz='0' WHERE id='$id'"); - header("Location: index.php?module=lieferschein&action=edit&id=$id"); - exit; - - } - - - function LieferscheinLiveTabelle() - { - $id = $this->app->Secure->GetGET("id"); - $status = $this->app->DB->Select("SELECT status FROM lieferschein WHERE id='$id' LIMIT 1"); - - $table = new EasyTable($this->app); - - if($status=="freigegeben") - { - $table->Query("SELECT SUBSTRING(ap.bezeichnung,1,20) as artikel, ap.nummer as Nummer, ap.menge as M, - if(a.porto,'-',if((SELECT SUM(l.menge) FROM lager_platz_inhalt l WHERE l.artikel=ap.artikel) > ap.menge,(SELECT SUM(l.menge) FROM lager_platz_inhalt l WHERE l.artikel=ap.artikel), - if((SELECT SUM(l.menge) FROM lager_platz_inhalt l WHERE l.artikel=ap.artikel)>0,CONCAT('',(SELECT SUM(l.menge) FROM lager_platz_inhalt l WHERE l.artikel=ap.artikel),''), - if(a.lagerartikel=1,'aus','kein Lagerartikel' ))) as L - FROM lieferschein_position ap, artikel a WHERE ap.lieferschein='$id' AND a.id=ap.artikel"); - $artikel = $table->DisplayNew("return","A","noAction"); - } else { - $table->Query("SELECT SUBSTRING(ap.bezeichnung,1,20) as artikel, ap.nummer as Nummer, ap.menge as M - FROM lieferschein_position ap, artikel a WHERE ap.lieferschein='$id' AND a.id=ap.artikel"); - $artikel = $table->DisplayNew("return","Menge","noAction"); - } - echo $artikel; - exit; - } - - function LieferscheinCopy() - { - $id = $this->app->Secure->GetGET("id"); - - $newid = $this->CopyLieferschein($id); - - header("Location: index.php?module=lieferschein&action=edit&id=$newid"); - exit; - } - - - function Custom($typ) - { - return ''; - } - - function LieferscheinIconMenu($id,$prefix="") - { - $status = $this->app->DB->Select("SELECT status FROM lieferschein WHERE id='$id' LIMIT 1"); - $lieferantenretoure = $this->app->DB->Select("SELECT lieferantenretoure FROM lieferschein WHERE id='$id' LIMIT 1"); - - if($status=="angelegt" || $status=="") - $freigabe = ""; - - - if(($status=="versendet" || $status=="freigegeben") && $lieferantenretoure=="1") - $abschliessen = ""; - - - $checkifrgexists = $this->app->DB->Select("SELECT id FROM rechnung WHERE lieferschein='$id' LIMIT 1"); - - $optioncustom = $this->Custom('option'); - $casecustom = $this->Custom('case'); - - $projekt = $this->app->DB->Select("SELECT projekt FROM lieferschein WHERE id='$id' LIMIT 1"); - $auslagern = ''; - $erneut = ''; - $casehook = ''; - $optionhook = ''; - $this->app->erp->RunHook('lieferscheiniconmenu_option', 5, $id, $casehook, $optionhook, $status, $prefix); - - $hookoption = ''; - $hookcase = ''; - $this->app->erp->RunHook('Lieferschein_Aktion_option',3, $id, $status, $hookoption); - $this->app->erp->RunHook('Lieferschein_Aktion_case',3, $id, $status, $hookcase); - - - $bestellmengelagerartikel = $this->app->DB->Select("SELECT sum(lp.menge) as bestellmenge from lieferschein_position lp INNER JOIN artikel a on a.id=lp.artikel where a.lagerartikel=1 AND lp.lieferschein = '$id'"); - $liefermengelagerartikel = $this->app->DB->Select("SELECT sum(lp.geliefert) as liefermenge from lieferschein_position lp INNER JOIN artikel a on a.id=lp.artikel where a.lagerartikel=1 AND lp.lieferschein = '$id'"); - $liefermengelagerartikel2 = $this->app->DB->Select("SELECT sum(olp.menge) as liefermenge from lieferschein_position lp INNER JOIN objekt_lager_platz olp ON olp.objekt='lieferschein' AND olp.parameter=lp.id INNER JOIN artikel a on a.id=lp.artikel where a.lagerartikel=1 AND lp.lieferschein = '$id'"); - $lieferscheinpositionen = (int)$this->app->DB->Select("SELECT count(id) from lieferschein_position where lieferschein = '$id'"); - $mengegeliefert = $this->app->DB->Select("SELECT ifnull(sum(geliefert),0) from lieferschein_position where lieferschein = '$id'"); - $schreibschutz = $this->app->DB->Select("SELECT schreibschutz FROM lieferschein WHERE id='$id' LIMIT 1"); - - $mengegeliefert = $mengegeliefert + $this->app->DB->Select("SELECT ifnull(sum(olp.menge),0)+0 FROM objekt_lager_platz olp INNER JOIN lieferschein_position lp ON olp.objekt='lieferschein' AND olp.parameter=lp.id AND lp.lieferschein = '$id'"); - - if($mengegeliefert <= 0 && $liefermengelagerartikel > 0 && $schreibschutz=="1" && $status!='angelegt' && $status!='storniert') { - $auslagern = ''; - }else{ - //12.07.19 LG lieferscheinlager als kommissionierverfahren zum if hinzugefuegt - $projektkommissionierverfahren = $this->app->DB->Select("SELECT kommissionierverfahren FROM projekt where id = '$projekt'"); - if($projekt && ($projektkommissionierverfahren == "" || $projektkommissionierverfahren == "rechnungsmail" || $projektkommissionierverfahren == "lieferschein" || $projektkommissionierverfahren == "lieferscheinscan" || $projektkommissionierverfahren == "lieferscheinlager" || $projektkommissionierverfahren == "lieferscheinlagerscan")) - { - if(($bestellmengelagerartikel != $liefermengelagerartikel && $bestellmengelagerartikel != $liefermengelagerartikel2) && $status!='angelegt' && $status!='storniert') { - $auslagern = ''; - } - } - } - - if($status!="angelegt" && $lieferantenretoure!="1") - { - $alsrechnung = ""; - if($this->app->erp->RechteVorhanden('lieferschein', 'proformarechnung') && $this->app->erp->ModulVorhanden('proformarechnung')) - { - $alsrechnung .= ""; - } - } - - if($this->app->erp->RechteVorhanden('belegeimport', 'belegcsvexport')) - { - $casebelegeimport = "case 'belegeimport': window.location.href='index.php?module=belegeimport&action=belegcsvexport&cmd=lieferschein&id=%value%'; break;"; - $optionbelegeimport = ""; - } - - $etiketten_positionen = $this->app->DB->Select("SELECT etiketten_positionen FROM projekt WHERE id='$projekt' LIMIT 1"); - if($etiketten_positionen > 0) - $etiketten = ""; - $casestorno = "case 'storno': if(!confirm('Wirklich stornieren?')) return document.getElementById('aktion$prefix').selectedIndex = 0; else window.location.href='index.php?module=lieferschein&action=delete&id=%value%'; break;"; - if($this->app->DB->Select("SELECT olp.id FROM objekt_lager_platz olp INNER JOIN lieferschein_position pos ON olp.parameter = pos.id AND olp.objekt = 'lieferschein' WHERE pos.lieferschein = '$id' LIMIT 1"))$casestorno = "case 'storno': if(!confirm('Wirklich stornieren?')) return document.getElementById('aktion$prefix').selectedIndex = 0; else if(!confirm('Artikel wieder einlagern?')) window.location.href='index.php?module=lieferschein&action=delete&id=%value%';else window.location.href='index.php?module=lieferschein&action=delete&cmd=einlagern&id=%value%'; break;"; - - if($checkifrgexists>0) $extendtext = "HINWEIS: Es existiert bereits eine Rechnung zu diesem Lieferschein! "; else $extendtext=""; - $menu =" - - -  Aktion:   - - - "; - //$tracking = $this->AuftragTrackingTabelle($id); - - $menu = str_replace('%value%',$id,$menu); - return $menu; - } - - function LieferscheinPDFfromArchiv() - { - $id = $this->app->Secure->GetGET("id"); - $archiv = $this->app->DB->Select("SELECT table_id from pdfarchiv where id = '$id' LIMIT 1"); - if($archiv) - { - $projekt = $this->app->DB->Select("SELECT projekt from lieferschein where id = '".(int)$archiv."'"); - } - if(class_exists('LieferscheinPDFCustom')) - { - if($archiv)$Brief = new LieferscheinPDFCustom($this->app,$projekt); - }else{ - if($archiv)$Brief = new LieferscheinPDF($this->app,$projekt); - } - if($archiv && $content = $Brief->getArchivByID($id)) - { - header('Content-type: application/pdf'); - header('Content-Disposition: attachment; filename="'.$content['belegnr'].'.pdf"'); - echo $content['file']; - $this->app->ExitXentral(); - } - header('Content-type: application/pdf'); - header('Content-Disposition: attachment; filename="Fehler.pdf"'); - $this->app->ExitXentral(); - } - - function LieferscheinMiniDetail($parsetarget="",$menu=true) - { - $id = $this->app->Secure->GetGET("id"); - if($id > 0){ - $auftragArr = $this->app->DB->SelectArr("SELECT * FROM lieferschein WHERE id='$id' LIMIT 1"); - } - $kundennummer = ''; - $projekt = 0; - $kundenname = ''; - $lieferantenretoure = ''; - $lieferantenretoureinfo = ''; - if(!empty($auftragArr)) { - $kundennummer = $auftragArr[0]['kundennummer']; - $projektid = $auftragArr[0]['projekt']; - $projekt = ''; - if($projektid){ - $projekt = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='{$auftragArr[0]['projekt']}' LIMIT 1"); - } - $kundenname = ''; - if($auftragArr[0]['adresse'] > 0){ - $kundenname = $this->app->DB->Select("SELECT name FROM adresse WHERE id='{$auftragArr[0]['adresse']}' LIMIT 1"); - } - $lieferantenretoure = $auftragArr[0]['lieferantenretoure']; - $lieferantenretoureinfo = $auftragArr[0]['lieferantenretoureinfo']; - } - - - $this->app->Tpl->Set('LIEFERANTENRETOUREINFO',$lieferantenretoureinfo); - - if($lieferantenretoure!='1') { - $this->app->Tpl->Set('LIEFERANTENRETOUREINFOSTART','"; + //$tracking = $this->AuftragTrackingTabelle($id); + + $menu = str_replace('%value%',$id,$menu); + return $menu; + } + + function LieferscheinPDFfromArchiv() + { + $id = $this->app->Secure->GetGET("id"); + $archiv = $this->app->DB->Select("SELECT table_id from pdfarchiv where id = '$id' LIMIT 1"); + if($archiv) + { + $projekt = $this->app->DB->Select("SELECT projekt from lieferschein where id = '".(int)$archiv."'"); + } + if(class_exists('LieferscheinPDFCustom')) + { + if($archiv)$Brief = new LieferscheinPDFCustom($this->app,$projekt); + }else{ + if($archiv)$Brief = new LieferscheinPDF($this->app,$projekt); + } + if($archiv && $content = $Brief->getArchivByID($id)) + { + header('Content-type: application/pdf'); + header('Content-Disposition: attachment; filename="'.$content['belegnr'].'.pdf"'); + echo $content['file']; + $this->app->ExitXentral(); + } + header('Content-type: application/pdf'); + header('Content-Disposition: attachment; filename="Fehler.pdf"'); + $this->app->ExitXentral(); + } + + function LieferscheinMiniDetail($parsetarget="",$menu=true) + { + $id = $this->app->Secure->GetGET("id"); + if($id > 0){ + $auftragArr = $this->app->DB->SelectArr("SELECT * FROM lieferschein WHERE id='$id' LIMIT 1"); + } + $kundennummer = ''; + $projekt = 0; + $kundenname = ''; + $lieferantenretoure = ''; + $lieferantenretoureinfo = ''; + if(!empty($auftragArr)) { + $kundennummer = $auftragArr[0]['kundennummer']; + $projektid = $auftragArr[0]['projekt']; + $projekt = ''; + if($projektid){ + $projekt = $this->app->DB->Select("SELECT abkuerzung FROM projekt WHERE id='{$auftragArr[0]['projekt']}' LIMIT 1"); + } + $kundenname = ''; + if($auftragArr[0]['adresse'] > 0){ + $kundenname = $this->app->DB->Select("SELECT name FROM adresse WHERE id='{$auftragArr[0]['adresse']}' LIMIT 1"); + } + $lieferantenretoure = $auftragArr[0]['lieferantenretoure']; + $lieferantenretoureinfo = $auftragArr[0]['lieferantenretoureinfo']; + } + + + $this->app->Tpl->Set('LIEFERANTENRETOUREINFO',$lieferantenretoureinfo); + + if($lieferantenretoure!='1') { + $this->app->Tpl->Set('LIEFERANTENRETOUREINFOSTART','