Exemplo n.º 1
0
 /**
  * 
  * Extract and provide data to be delivered to template
  * @param array $dataObjects
  * @param array $textBlocks	Reference to template inherent textblocks (can be manipulated here)
  */
 protected static function getUniversalReceiptData(array $dataObjects, &$textBlocks)
 {
     self::getDataObjects($dataObjects, &$contact, &$receipt, &$job, &$order, &$debitor, &$creditor, &$sums, &$aPositions, &$sumTable, &$sumData, &$addData);
     $letterDrawee = $contact->getLetterDrawee();
     $shippingDrawee = $contact->getShippingDrawee();
     $invoiceDrawee = $contact->getInvoiceDrawee();
     $alternativeShippingDrawee = '';
     if ($invoiceDrawee !== $shippingDrawee) {
         $alternativeShippingDrawee = 'Lieferung an:' . chr(13) . chr(10) . $shippingDrawee->toText(true);
     }
     $totalBrutto = $sums['total']['sum']['brutto'];
     $monitionFee = $receipt->__get('monition_fee');
     $totalSum = $totalBrutto + $monitionFee;
     // overwrite payment conditions, if these are set in the record
     // otherwise use text from docmanager template
     $paymentMethod = $receipt->getForeignRecord('payment_method_id', Billing_Controller_PaymentMethod::getInstance());
     // if order state: PAYED -> get tb2 from payment method otherwise tb2
     if ($order->__get('payment_state') == 'PAYED') {
         $textBlocks['ZAHLUNGSBEDINGUNGEN'] = $paymentMethod->__get('text1');
     } else {
         $textBlocks['ZAHLUNGSBEDINGUNGEN'] = $paymentMethod->__get('text2');
     }
     if ($receipt->__get('payment_conditions')) {
         $textBlocks['ZAHLUNGSBEDINGUNGEN'] = $receipt->__get('payment_conditions');
     }
     $sumPositions = $sumTable['POSITIONS'];
     $aVat = array();
     foreach ($sumPositions as $sp) {
         $name = (string) 'vat' . floor($sp['vn_vatindex']);
         $aVat[$name] = $sp['vn_vat'];
     }
     $userContact = $dataObjects['userContact'];
     $user = $dataObjects['user'];
     $userName = $userContact->__get('n_family');
     $payerName = $contact->__get('n_fileas');
     $payerBankAccountNumber = $contact->__get('bank_account_number');
     $payerBankCode = $contact->__get('bank_code');
     $payerBankAccountName = $contact->__get('bank_account_name');
     $payerBankName = $contact->__get('bank_name');
     $cpInvoiceDrawee = $contact->getInvoiceDrawee()->toText();
     $cpShippingDrawee = $contact->getShippingDrawee()->toText();
     if ($receipt->hasAdditionalItem('contactPersonId')) {
         try {
             $contactPerson = Addressbook_Controller_ContactPerson::getInstance()->get((int) $receipt->getAdditionalItem('contactPersonId'));
             $cpInvoiceDrawee = $contact->getInvoiceDrawee()->setContactPerson($contactPerson)->toText();
             $cpShippingDrawee = $contact->getShippingDrawee()->setContactPerson($contactPerson)->toText();
         } catch (Exception $e) {
             echo $e;
             exit;
             //
         }
     }
     $result = array('JOB_NR' => $job ? $job->__get('job_nr') : null, 'ORDER_NR' => $order->__get('order_nr'), 'CALC_NR' => $receipt->__get('calc_nr'), 'BID_NR' => $receipt->__get('bid_nr'), 'BID_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('bid_date')), 'BID_SHIP_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('bid_shipping_date')), 'CONFIRM_NR' => $receipt->__get('confirm_nr'), 'CONFIRM_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('order_confirm_date')), 'INV_NR' => $receipt->__get('invoice_nr'), 'INV_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('invoice_date')), 'DUE_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('due_date')), 'CUST_NR' => $debitor->__get('debitor_nr'), 'SHIP_NR' => $receipt->__get('ship_nr'), 'SHIP_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('shipping_date')), 'CREDIT_NR' => $receipt->__get('credit_nr'), 'CREDIT_DATE' => \org\sopen\app\util\format\Date::format($receipt->__get('credit_date')), 'MONITION_NR' => $receipt->__get('monition_nr'), 'MONITION_LEVEL' => $receipt->__get('monition_level'), 'MONITION_DATE' => strftime('%d.%m.%Y'), 'TEXT1' => $receipt->__get('upper_textblock'), 'TEXT2' => $receipt->__get('lower_textblock'), 'SHIPPING_COND' => $receipt->__get('shipping_conditions'), 'PAYMENT_COND' => $receipt->__get('payment_conditions'), 'TODAY' => strftime('%d.%m.%Y'), 'NOW' => strftime('%d.%m.%Y %H:%M:%S'), 'CONTACT' => $contact, 'CONTACT_NR' => $contact->__get('id'), 'ADRESS' => array('ALTERNATIVE_SHIPPING_DRAWEE' => $alternativeShippingDrawee, 'LETTER_DRAWEE' => $contact->getLetterDrawee()->toText(), 'SHIPPING_DRAWEE' => $contact->getShippingDrawee()->toText(), 'INVOICE_DRAWEE' => $contact->getInvoiceDrawee()->toText(), 'SALUTATION' => $contact->__get('letter_salutation'), 'AP_INVOICE_DRAWEE' => $cpInvoiceDrawee, 'AP_SHIPPING_DRAWEE' => $cpShippingDrawee), 'POSDATA' => $sumTable['POSDATA'], 'POS_TABLE' => $aPositions, 'SUM_TABLE' => $sumTable, 'VALUES' => array_merge(array('vn_netto_sum' => number_format($sums['total']['sum']['netto'], 2, ',', '.'), 'vn_vat_sum' => number_format($sums['total']['sum']['vat'], 2, ',', '.'), 'vn_brutto_sum' => number_format($sums['total']['sum']['brutto'], 2, ',', '.'), 'add_perc' => $receipt->__get('add_percentage')), $aVat), 'SUMS' => $sumData, 'monition_fee' => number_format($monitionFee, 2, ',', '.'), 'total_sum' => number_format($totalSum, 2, ',', '.'), 'USER' => array('N' => $userName, 'NUPPER' => strtoupper($userName), 'NFULL' => $userContact->__get('n_fileas'), 'NFORE' => $userContact->__get('n_given'), 'NLAST' => $userContact->__get('n_family'), 'PHONE' => $userContact->__get('tel_work'), 'FAX' => $userContact->__get('tel_fax'), 'MAIL' => $userContact->__get('email')), 'INVOICE_DRAWEE' => $invoiceDrawee->toText(true), 'PAYER_NAME' => $payerName, 'P_ACC' => $payerBankAccountNumber, 'P_ACCOUNT_NAME' => $payerBankAccountName, 'P_ACCOUNT_NR' => $payerBankAccountNumber, 'P_BANK_CODE' => $payerBankCode, 'P_BANK_NAME' => $payerBankName, 'UST_ID' => $debitor->__get('ust_id'));
     $additionalData = $receipt->getAdditionalData();
     /*if(is_array($additionalData)){
     			if(array_key_exists('BALANCE', $additionalData)){
     				if((float)$additionalData['BALANCE']<0){
     					$additionalData['REMINDER'] = 'Wir erinnern höflich an den noch ausstehenden Jahresbeitrag 2012:';
     					$additionalData['remind'] = number_format(abs((float)$additionalData['BALANCE']),2,',','.') . ' EUR';
     				}elseif((float)$additionalData['BALANCE']>0){
     					$additionalData['REMINDER'] = 'davon bereits bezahlt:';
     					$additionalData['remind'] = number_format(abs((float)$additionalData['BALANCE']),2,',','.') . ' EUR';
     				}
     			}
     			$result = array_merge($result, $additionalData );
     		}*/
     if (is_array($additionalData)) {
         if (array_key_exists('OPEN', $additionalData)) {
             if ((double) $additionalData['OPEN'] > 0) {
                 $additionalData['OPEN_EUR'] = $additionalData['OPEN_EUR'] . ' EUR';
                 //$additionalData['REMINDER'] = 'Wir erinnern höflich an den noch ausstehenden Jahresbeitrag 2012:';
                 //$additionalData['remind'] = number_format(abs((float)$additionalData['BALANCE']),2,',','.') . ' EUR';
             } else {
                 $additionalData['OPEN_EUR'] = '';
             }
         }
         $result = array_merge($result, $additionalData);
     }
     $result = array_merge($result, $addData);
     //print_r($result);
     //exit;
     return $result;
 }
Exemplo n.º 2
0
 public function printMonitionExportPrepare($jobId, $filteredList, $filteredListData, $monitionProtocol = false, array $batchJobMonitionIds = null)
 {
     set_time_limit(0);
     ignore_user_abort(true);
     error_reporting(E_ALL);
     try {
         $job = Billing_Api_BatchJobManager::getInstance()->loadBatchJob($jobId);
         Billing_Api_BatchJobManager::getInstance()->startBatchJob();
         $db = Tinebase_Core::getDb();
         $tm = Tinebase_TransactionManager::getInstance();
         $tId = $tm->startTransaction($db);
         $data = $job->getData();
         $pagination = new Tinebase_Model_Pagination();
         //require_once 'Payment/Monition.php';
         $tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         if ($monitionProtocol) {
             $outputFileName = $tempFilePath . 'Protokoll-Mahnung-' . $job->getId() . '.pdf';
         } else {
             // get all open items (for debit)
             // grouped by debitors
             $filters[] = array('field' => 'job_id', 'operator' => 'equals', 'value' => $job->getId());
             $sort = array('sort' => 'n_family', 'dir' => 'ASC');
             if ($filteredList) {
                 if (!is_array($filteredListData)) {
                     $filteredListData = Zend_Json::decode($filteredListData);
                 }
                 $additionalFilters = $filteredListData['filter'];
                 if (count($additionalFilters) > 0) {
                     $filters = array_merge($filters, $additionalFilters);
                 }
                 $sort = array('sort' => $filteredListData['sort']['field'], 'dir' => $filteredListData['sort']['direction']);
             }
             $filter = new Billing_Model_BatchJobMonitionFilter($filters, 'AND');
             // count membership matching filters
             $batchJobMonitionIds = $this->search($filter, new Tinebase_Model_Pagination($sort), false, true);
             $outputFileName = $tempFilePath . 'Vorbereitungsliste-' . $job->getId() . '.pdf';
         }
         $contexts = array('MEMBERSHIP' => 'Beitrag', 'DONATOR' => 'Spende', 'ERP' => 'allg.');
         $data = array();
         $total = 0;
         $count = 0;
         //count($batchJobMonitionIds);
         $subSums = array();
         foreach ($batchJobMonitionIds as $batchJobDataId) {
             $batchJobData = $this->get($batchJobDataId);
             // keep out item which are diffed
             if (!$filteredList && $batchJobData->__get('monition_lock') == 1) {
                 continue;
             }
             $count++;
             $batchJobDataItems = Billing_Controller_BatchJobMonitionItem::getInstance()->getByBatchJobMonitionId($batchJobData->getId());
             $contact = $batchJobData->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
             $strOP = '';
             foreach ($batchJobDataItems as $item) {
                 // Kontext / Fällig am / Beleg / Betrag
                 $openItem = $item->getForeignRecord('open_item_id', Billing_Controller_OpenItem::getInstance());
                 /*if($openItem->__get('state') != 'OPEN'){
                 					
                 			// tried to include open item which was already done!!!
                 			// break the job
                 			$this->cleanupJob($jobId);
                 			
                 			// break job!
                 			throw new Billing_Exception_OpenItem('Open item '.$openItem->__get('op_nr').' is already finished.');
                 		}*/
                 $receipt = $openItem->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
                 $contactNr = $batchJobData->getForeignId('contact_id');
                 $receiptNr = $receipt->__get('invoice_nr');
                 if ($receipt->getAdditionalItem('MNR')) {
                     $contactNr = $receipt->getAdditionalItem('MNR');
                 }
                 $dueDate = $openItem->__get('due_date');
                 $erpContext = $contexts[$receipt->__get('erp_context_id')];
                 $sum = $openItem->__get('open_sum');
                 $context = $receipt->__get('erp_context_id');
                 $strOP .= $receiptNr . "<text:tab/><text:tab/>" . $contactNr . "<text:tab/><text:tab/>" . $erpContext . "<text:tab/><text:tab/>" . \org\sopen\app\util\format\Date::format($dueDate) . "<text:tab/><text:tab/>" . $openItem->__get('due_days') . "<text:tab/><text:tab/>" . $openItem->getNextMonitionStage() . "<text:tab/><text:tab/>" . number_format($sum, 2, ',', '.') . "<text:line-break/>";
                 if (!array_key_exists($context, $subSums)) {
                     $subSums[$context] = array('context' => $erpContext, 'method' => '', 'count' => 0, 'sum' => 0);
                 }
                 $subSums[$context]['sum'] += $sum;
                 $subSums[$context]['count']++;
             }
             $usage = array();
             $contactNr = $batchJobData->getForeignId('contact_id');
             $usage[] = 'Adr.Nr ' . $contactNr;
             //$this->extractUsageFromMonitionItems( $batchJobDataItems, &$usage, $contexts);
             $strUsage = implode('<text:line-break/>', $usage);
             /*
             				 ##MNR##
             				 ##LASTNAME##
             				 ##FORENAME##
             				 ##OPENITEMS##
             				 ##AMOUNT##
             */
             $data[] = array('MNR' => $contact->getId(), 'FORENAME' => $contact->__get('n_given'), 'LASTNAME' => $contact->__get('n_family'), 'FORENAME_PARTNER' => $contact->__get('partner_forename'), 'LASTNAME_PARTNER' => $contact->__get('partner_lastname'), 'COMPANY' => $contact->__get('org_name') . ($contact->__get('company2') ? ' ' . $contact->__get('company2') : ''), 'USAGE' => $strUsage, 'OPENITEMS' => $strOP, 'OPEN' => number_format($batchJobData->__get('open_sum'), 2, ',', '.'), 'SALDO' => number_format($batchJobData->__get('total_saldation'), 2, ',', '.'), 'TOTAL' => number_format($batchJobData->__get('total_sum'), 2, ',', '.'));
             $total += $batchJobData->__get('total_sum');
         }
         $dynTable = array();
         foreach ($subSums as $context => $subItem) {
             $dynTable[] = array('headers' => array(), 'rows' => array(array('text' => $subItem['context'], 'dcount' => $subItem['count'], 'dsum' => number_format($subItem['sum'], 2, ',', '.'))));
         }
         $fullData = array(array('REPEATABLE_DYN_TABLE' => $dynTable, 'POS_TABLE' => $data, 'total' => number_format($total, 2, ',', '.'), 'count' => $count));
         $outputFileName = $tempFilePath . md5(serialize($job) . 'preparePDF' . microtime()) . '.pdf';
         $templateId = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::TEMPLATE_MONITION_PREPARE);
         Billing_Controller_PrintJobRecordData::getInstance()->export($fullData, $templateId, 'Vorbereitungsliste-' . $job->getId() . '.pdf', true, $outputFileName);
         if (!$monitionProtocol) {
             if (!$filteredList) {
                 Billing_Api_BatchJobManager::getInstance()->jobAddData('preparePDF', $outputFileName);
                 Billing_Api_BatchJobManager::getInstance()->jobAddData('preparePDFDownloadFilename', 'Vorbereitungsliste-' . $job->getId() . '.pdf');
             } else {
                 Billing_Api_BatchJobManager::getInstance()->jobAddData('filteredPreparePDF', $outputFileName);
                 Billing_Api_BatchJobManager::getInstance()->jobAddData('filteredPreparePDFDownloadFilename', 'Gefilterte-Vorbereitungsliste-' . $job->getId() . '.pdf');
             }
         } else {
             Billing_Api_BatchJobManager::getInstance()->jobAddData('protocolPDF', $outputFileName);
             Billing_Api_BatchJobManager::getInstance()->jobAddData('protocolPDFDownloadFilename', 'Protokoll-Monition-' . $job->getId() . '.pdf');
         }
         $tm->commitTransaction($tId);
         Billing_Api_BatchJobManager::getInstance()->finish();
         return array('state' => 'success', 'result' => null);
     } catch (Exception $e) {
         echo $e->__toString();
         $tm->rollback($tId);
         Billing_Api_BatchJobManager::getInstance()->finishError($e->__toString());
         return array('state' => 'failure', 'result' => null, 'errorInfo' => array('message' => $e->getMessage(), 'trace' => $e->getTrace()));
     }
 }
Exemplo n.º 3
0
 public function printLists($period, $definition, &$processArray)
 {
     set_time_limit(0);
     ignore_user_abort(true);
     $processArray = array();
     $values = array('VOR' => array(), 'JETZT' => array(), 'NACH' => array());
     $fixValues = array('prev_period' => $period - 1, 'now_period' => $period, 'next_period' => $period + 1);
     $periods = array('VOR' => $period - 1, 'JETZT' => $period, 'NACH' => $period + 1);
     $res = array('VOR' => array(), 'JETZT' => array(), 'NACH' => array());
     // Mitgliederbeiträge nach Beitragsgruppen:
     $date = new Zend_Date();
     $date->setYear($period);
     $beginDate = $definition->getStartDate(new Zend_Date());
     $endDate = $definition->getEndDate(new Zend_Date());
     /*$beginDate = clone $date;
     		$endDate = clone $date;
     		
     		$beginDate->setMonth(1);
     		$beginDate->setDay(1);
     		
     		$endDate->setMonth(12);
     		$endDate->setDay(31);*/
     $baseOpFilter = array();
     $baseDonationFilter = array();
     $baseOpFilter[] = array('field' => 'payment_date', 'operator' => 'afterOrAt', 'value' => $beginDate->toString('yyyy-MM-dd'));
     $baseOpFilter[] = array('field' => 'payment_date', 'operator' => 'beforeOrAt', 'value' => $endDate->toString('yyyy-MM-dd'));
     $baseOpFilter[] = array('field' => 'state', 'operator' => 'not', 'value' => 'OPEN');
     $baseDonationFilter[] = array('field' => 'donation_date', 'operator' => 'afterOrAt', 'value' => $beginDate->toString('yyyy-MM-dd'));
     $baseDonationFilter[] = array('field' => 'donation_date', 'operator' => 'beforeOrAt', 'value' => $endDate->toString('yyyy-MM-dd'));
     $baseOpFilter = new Billing_Model_OpenItemFilter($baseOpFilter, 'AND');
     $baseDonationFilter = new Donator_Model_DonationFilter($baseDonationFilter, 'AND');
     $feeGroups = Membership_Controller_FeeGroup::getInstance()->getAllFeeGroups('key');
     $feeGroupSum = 0;
     $resultValues = array();
     $nowSum = $previousSum = $nextSum = $totalDonationSum = 0;
     $opPaging = new Tinebase_Model_Pagination(array('sort' => array('payment_date', 'pay.debitor_id'), 'dir' => 'ASC'));
     $bgMap = array();
     foreach ($feeGroups as $feeGroup) {
         $opFilter = null;
         $opFilter = clone $baseOpFilter;
         $opFilter->addFilter($opFilter->createFilter('fee_group_id', 'equals', $feeGroup->__get('id'), 'rc'));
         $innerArray = array();
         $innerArray['bg_name'] = $feeGroup->__get('name');
         $bgMap[$feeGroup->__get('name')] = $feeGroup->__get('key');
         foreach ($values as $key => $value) {
             $innerOpFilter = null;
             $innerOpFilter = clone $opFilter;
             switch ($key) {
                 case 'VOR':
                     $innerOpFilter->addFilter($innerOpFilter->createFilter('period', 'less', $period, 'rc'));
                     $ids = Billing_Controller_OpenItem::getInstance()->search($innerOpFilter, $opPaging, false, true);
                     $res['VOR'][$feeGroup->__get('name')] = $ids;
                 case 'JETZT':
                     $innerOpFilter->addFilter($innerOpFilter->createFilter('period', 'equals', $period, 'rc'));
                     $ids = Billing_Controller_OpenItem::getInstance()->search($innerOpFilter, $opPaging, false, true);
                     $res['JETZT'][$feeGroup->__get('name')] = $ids;
                     break;
                 case 'NACH':
                     $innerOpFilter->addFilter($innerOpFilter->createFilter('period', 'greater', $period, 'rc'));
                     $ids = Billing_Controller_OpenItem::getInstance()->search($innerOpFilter, $opPaging, false, true);
                     $res['NACH'][$feeGroup->__get('name')] = $ids;
             }
         }
     }
     foreach ($res as $key => $bgOps) {
         foreach ($bgOps as $bgName => $ops) {
             $items = array();
             $total = 0;
             foreach ($ops as $opId) {
                 //var_dump($opId);
                 $openItem = Billing_Controller_OpenItem::getInstance()->get($opId);
                 $debi = $openItem->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
                 $contact = $debi->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
                 $openSum = $openItem->__get('open_sum');
                 $payedSum = $openItem->__get('payed_sum');
                 /*##CNR##
                 ##COMPANY##
                 ##LASTNAME##
                 ##FORENAME##
                 ##DDATE##
                 ##USAGE##
                 ##AMOUNT##
                 */
                 $items[] = array('CNR' => $contact->__get('id'), 'COMPANY' => $contact->__get('org_name'), 'LASTNAME' => $contact->__get('n_family'), 'FORENAME' => $contact->__get('n_given'), 'SDATE' => \org\sopen\app\util\format\Date::format($openItem->__get('receipt_date')), 'PDATE' => \org\sopen\app\util\format\Date::format($openItem->__get('payment_date')), 'USAGE' => $openItem->__get('usage'), 'TOTAL' => number_format($openItem->__get('total_brutto'), 2, ',', '.'), 'PAYED' => number_format($payedSum, 2, ',', '.'), 'OPEN' => number_format($openSum, 2, ',', '.'));
                 $total += $payedSum;
             }
             $processArray[] = array('values' => $items, 'sums' => array(), 'header' => array('BGKEY' => $bgMap[$bgName], 'BGNAME' => $bgName, 'PERIOD' => $periods[$key], 'total' => $total));
         }
     }
 }
Exemplo n.º 4
0
 public function exportArticleSellList($data, $exportType)
 {
     $export = Billing_Custom_ArticleExportData::create($data);
     if ($export->hasNoGrouping() || $exportType == 'CSV') {
         $export->setRecordSet(Billing_Controller_ArticleSold::getInstance()->search($export->getFilter(), $export->getPagination()));
     } elseif ($export->hasGroupingCustomer()) {
         // get all customers
         // -> maybe a huge set
         // check restrictions of filter regarding customer (customer_group)
         /*	$debitorFilter = new Billing_Model_DebitorFilter(array(),'AND');
         			$debFilter = null;
         			$articleFilter = $export->getFilter();
         			
         			if($articleFilter->isFilterSet('debitor_id')){
         				$debFilter = $articleFilter->getFilter('debitor_id');
         				
         				if($debFilter->isFilterSet('id')){
         					$debitorFilter->addFilter($debFilter->get('id'));
         				}
         				
         				if($debFilter->isFilterSet('debitor_group_id')){
         					$debitorFilter->addFilter($debFilter->get('debitor_group_id'));
         				}
         			}*/
         $debitorIds = Billing_Controller_ArticleSold::getInstance()->getDebitorIds($export->getFilter());
         foreach ($debitorIds as $debitorId) {
             $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
             $export->addCustomerRecordSet(Billing_Controller_ArticleSold::getInstance()->search($export->getCustomerFilter($debitor), $export->getPagination()), $debitorId);
         }
     }
     switch ($exportType) {
         case 'PDF':
             $outputFileName = 'Artikel-Verkaufsliste-' . strftime('%d-%m-%Y %H-%M-%S') . '.pdf';
             $templateId = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::TEMPLATE_ARTICLE_SOLD);
             if ($export->hasGroupingCustomer()) {
                 $data = array();
                 $aResult = $export->customerRecordsToArray(true);
                 foreach ($aResult as $debitorId => $result) {
                     $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
                     $contact = $debitor->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
                     $data[$contact->__get('n_fileas')] = array('POS_TABLE' => $result['data'], 'customer_nr' => $debitor->__get('debitor_nr'), 'customer_name' => $contact->__get('n_fileas'), 'begin_date' => \org\sopen\app\util\format\Date::format(new Zend_Date($export->getStartDate())), 'end_date' => $export->getEndDate() ? \org\sopen\app\util\format\Date::format(new Zend_Date($export->getEndDate())) : 'heute', 'sum_total_netto' => number_format($result['total_netto'], 2, ',', '.'), 'sum_total_brutto' => number_format($result['total_brutto'], 2, ',', '.'));
                 }
                 ksort($data);
             } else {
                 $data = array(array('POS_TABLE' => $export->toArray(true), 'begin_date' => \org\sopen\app\util\format\Date::format(new Zend_Date($export->getStartDate())), 'end_date' => $export->getEndDate() ? \org\sopen\app\util\format\Date::format(new Zend_Date($export->getEndDate())) : 'heute', 'sum_total_netto' => number_format($export->getSumTotalNetto(), 2, ',', '.'), 'sum_total_brutto' => number_format($export->getSumTotalBrutto(), 2, ',', '.')));
             }
             Billing_Controller_PrintJobRecordData::getInstance()->export($data, $templateId, $outputFileName);
             break;
         case 'CSV':
             $this->exportAsCsv($export, 'Artikel-Verkaufsliste-' . strftime('%d-%m-%Y %H-%M-%S') . '.csv');
             break;
     }
 }
Exemplo n.º 5
0
 /**
  * 
  * Export to DATEV
  * @param string $filters Json encoded filters
  */
 public function exportFibu($filters)
 {
     set_time_limit(0);
     $db = Tinebase_Core::getDb();
     $tm = Tinebase_TransactionManager::getInstance();
     $tId = $tm->startTransaction($db);
     try {
         $filters = Zend_Json::decode($filters);
         $checkFilter = new Billing_Model_OpenItemFilter($filters, 'AND');
         $pagination = array('sort' => 'op_nr', 'dir' => 'ASC');
         $oIController = Billing_Controller_OpenItem::getInstance();
         $debController = Billing_Controller_Debitor::getInstance();
         $rController = Billing_Controller_Receipt::getInstance();
         $oController = Billing_Controller_Order::getInstance();
         $oPController = Billing_Controller_OrderPosition::getInstance();
         $aController = Billing_Controller_Article::getInstance();
         $cController = Addressbook_Controller_Contact::getInstance()->_setRightChecks(false)->_setContainerACLChecks(false);
         // if filter contains fibu_exp_date-filter -> force reexport!
         if (!$checkFilter->isFilterSet('fibu_exp_date')) {
             $fibuFilter = array('field' => 'fibu_exp_date', 'operator' => 'isnull', 'value' => '');
             $filters[] = $fibuFilter;
         }
         $filter = new Billing_Model_OpenItemFilter($filters, 'AND');
         $openItemIds = $oIController->search($filter, new Tinebase_Model_Pagination($pagination), false, true);
         /*
         			 *
         					- Rechnungsnummer (redundant für alle Positionen)
         					
         					- Rechnungsdatum (redundant für alle Positionen)
         					
         					- Datum Fälligkeit (redundant für alle Positionen)
         					
         					- Debitorennummer (redundant für alle Positionen)
         					
         					- Betrag netto
         					
         					- MWST
         					
         					- Betrag brutto
         					
         					- Artikelnummer
         					
         					- Artikelbezeichnung
         					
         					- Erlöskonto (aus Artikelstamm gemäß MWST = 0 oder > 0)
         *
         
         Umsatz (mit Soll/Haben-Kz)	Konto	Gegenkonto (ohne BU-Schl�ssel)	Belegdatum	Belegfeld 1	Buchungstext	Kennzeichen			D_Opos
         299,22						1000200	440000							12.01.2012	101			Rechnung101		Forderungsart "1"	D_Opos
         
         
         
         *
         */
         $csvArray = array('Umsatz (mit Soll/Haben-Kz)', 'Konto', 'Gegenkonto (ohne BU-Schlüssel)', 'Belegdatum', 'Belegfeld', 'Buchungstext', 'Kennzeichen', 'D_Opos');
         /*
         	    	 * 
         	    	 * 
         	    	  	- Debitorennummer
         
         				- Vorname
         				
         				- Name
         				
         				- Anrede
         				
         				- Titel
         				
         				- Firma 1
         				
         				- Firma 2
         				
         				- Zusatz
         				
         				- Straße
         				
         				- PLZ
         				
         				- Ort
         				
         				- Land
         				
         Kontonummer	Unternehmen			Anrede	Titel		Vorname	Name1	Adressattyp	UST ID	Stra�e	Postfach	Postleitzahl	Ort	Land	Bankleitzahl 1	Bankbez. 1	Bank-Kontonummer 1	Bank-L�nderkennz. 1	IBAN-Nr. 1	SWIFT-Code 1	Bankleitzahl 2	Bankbez. 2	Bank-Kontonummer2	Bank-L�nderkennz. 2	IBAN-Nr. 2	SWIFT-Code 2
         5841100		Acuarios Jandia Sotavento Beach Club B.Lehmann				Lehmann & Buschmann	2	DE111667148	Wefelen 27		35627	Costa-Calma/Fuerte.	Spanien	70050000	Bayern LB M�nchen	2034343	DE	DE14700500000002034343	BYLADEMM						
         5841200							Herr	Prof. Dr.	Hansi	Gustavo	1	DE111667148	Wefelen 29		52134	Herzogenrath		39050000	Sparkasse Aachen	47176987									
         */
         $debsArray = array('Kontonummer', 'Unternehmen', 'Anrede', 'Titel', 'Vorname', 'Name1', 'Adressattyp', 'UST ID', 'Straße', 'Postfach', 'Postleitzahl', 'Ort', 'Land', 'Bankleitzahl 1', 'Bankbez. 1', 'Bank-Kontonummer 1', 'Bank-Länderkennz. 1', 'IBAN-Nr. 1', 'SWIFT-Code 1', 'Bankbez. 2', 'Bank-Kontonummer 2', 'Bank-Länderkennz. 2', 'IBAN-Nr. 2', 'SWIFT-Code 2');
         $tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         $itemsFilename = $tempFilePath . strftime('%Y%m%d%H%M%S') . 'items_temp.csv';
         $debsFilename = $tempFilePath . strftime('%Y%m%d%H%M%S') . 'debs_temp.csv';
         $zipFilename = $tempFilePath . strftime('%Y%m%d%H%M%S') . 'archive_temp.csv';
         if (file_exists($itemsFilename)) {
             unlink($itemsFilename);
         }
         $itemsFileHandle = fopen($itemsFilename, 'w');
         //$filePointer, $dataArray, $delimiter=',', $enclosure='"', $escapeEnclosure='"'
         Tinebase_Export_Csv::fputcsvEncoding('ISO-8859-1//TRANSLIT', $itemsFileHandle, $csvArray, chr(9), '"', '');
         if (file_exists($debsFilename)) {
             unlink($debsFilename);
         }
         $debsFileHandle = fopen($debsFilename, 'w');
         Tinebase_Export_Csv::fputcsvEncoding('ISO-8859-1//TRANSLIT', $debsFileHandle, $debsArray, chr(9), '"', '');
         $zeroVat = Billing_Controller_Vat::getInstance()->getByName('0');
         $creditorZeroAccount = $zeroVat->__get('credit_account');
         $fibuExpDate = new Zend_Date(strftime('%Y-%m-%d'));
         $adType = 1;
         foreach ($openItemIds as $openItemId) {
             $oI = Billing_Controller_OpenItem::getInstance()->get($openItemId);
             $oI->flatten();
             $receiptId = $oI->__get('receipt_id');
             $receipt = $rController->get($receiptId);
             if (!$receipt->__get('fibu_exp_date')) {
                 $receipt->__set('fibu_exp_date', $fibuExpDate);
                 $receipt->flatten();
                 //print_r($receipt);
                 $rController->update($receipt);
             }
             $oI->__set('fibu_exp_date', $fibuExpDate);
             $oIController->update($oI);
             $positions = $rController->getOrderPositions($receiptId);
             //$sums = $rController->getReceiptSumValues($receiptId);
             $orderId = $receipt->__get('order_id');
             $order = $oController->get($orderId);
             $debitor = $order->__get('debitor_id');
             $debitorNr = $debitor->__get('debitor_nr');
             $contact = $debitor->getForeignRecord('contact_id', $cController);
             $debitor->flatten();
             $contactId = $debitor->__get('contact_id');
             $name = $contact->__get('n_fileas');
             $receiptNr = $oI->__get('receipt_nr');
             $adType = 1;
             if ($contact->__get('org_name') && $contact->getLetterDrawee()->isCompany()) {
                 $adType = 2;
             }
             $dueDate = $receipt->__get('due_date');
             if (!$debitor->__get('fibu_exp_date')) {
                 $drawee = $contact->getInvoiceDrawee();
                 $postal = $drawee->getPostalAddress();
                 $pf = '';
                 $street = '';
                 if (strpos($postal->getStreet(), 'Post')) {
                     $pf = $postal->getStreet();
                 } else {
                     $street = $postal->getStreet();
                 }
                 // export debitor
                 $debsArray = array($debitorNr, $contact->__get('org_name'), $drawee->getSalutationText(), $drawee->getTitle(), $contact->__get('n_given'), $contact->__get('n_family'), $adType, $debitor->__get('ust_id'), $street, $pf, $postal->getPostalCode(), $postal->getLocation(), $postal->getCountryCode('DE'), $contact->__get('bank_code'), $contact->__get('bank_name'), $contact->__get('bank_account_number'), trim($contact->__get('bank_code')) ? $postal->getCountryCode() : '', '', '', '', '', '', '', '', '');
                 Tinebase_Export_Csv::fputcsvEncoding('ISO-8859-1//TRANSLIT', $debsFileHandle, $debsArray, chr(9), '"', '');
                 $debitor->__set('fibu_exp_date', new Zend_Date());
                 $debController->update($debitor);
             }
             //	    		$values = array();
             //	    		$values[] = array(
             //				'value' => $sums['total']['sum']['netto'],
             //				'credit_account' => $creditorZeroAccount
             //	    		);
             //
             //	    		foreach($sums['vat_sums'] as $vatSum){
             //	    			$values[] = array(
             //					'value' =>  $vatSum['sum']['netto'],
             //					'credit_account' =>  $vatSum['sum']['vatcreditaccount']
             //	    			);
             //	    		}
             //Umsatz (mit Soll/Haben-Kz)	Konto	Gegenkonto (ohne BU-Schl�ssel)	Belegdatum	Belegfeld 1	Buchungstext	Kennzeichen			D_Opos
             //299,22						1000200	440000							12.01.2012	101			Rechnung101		Forderungsart "1"	D_Opos
             $receiptText = '';
             if ($receipt->__get('type') == Billing_Model_Receipt::TYPE_INVOICE) {
                 $receiptText = 'Rechnung';
                 $receiptDate = $receipt->__get('invoice_date');
                 $receiptNr = $receipt->__get('invoice_nr');
             } else {
                 $receiptText = 'Gutschrift';
                 $receiptDate = $receipt->__get('credit_date');
                 $receiptNr = $receipt->__get('credit_nr');
             }
             $bookingText = $receiptText . $receiptNr;
             /*if($oI->__get('usage')){
             			$bookingText = $oI->__get('usage');
             		}*/
             $paymentMethodId = $receipt->getForeignId('payment_method_id');
             $mapPaymentMethod = array('PREPAYMENT' => 1, 'BANKTRANSFER' => 2, 'DEBIT' => 3, 'CASH' => 4, 'CREDITCARD' => 5, 'PAYPAL' => 6, 'IMMEDIATETRANSFER' => 7);
             $intPaymentMethod = $mapPaymentMethod[$paymentMethodId];
             foreach ($positions as $position) {
                 $brutto = $position->__get('total_brutto');
                 //$vatSum = $oPController->getVatSum($position);
                 //$article = $position->getForeignRecord('article_id', $aController);
                 //$articleName = $article->__get('name');
                 //$articleNr = $article->__get('article_nr');
                 $revAccount = $oPController->getRevenueAccountAccordingToVat($position) . '00';
                 $csvArray = array(number_format($brutto, 2, ',', '.'), $debitorNr, $revAccount, \org\sopen\app\util\format\Date::format($receiptDate), $receiptNr, $bookingText, 'Forderungsart ' . $intPaymentMethod, 'D_Opos');
                 Tinebase_Export_Csv::fputcsvEncoding('ISO-8859-1//TRANSLIT', $itemsFileHandle, $csvArray, chr(9), '"', '');
             }
         }
         fclose($itemsFileHandle);
         fclose($debsFileHandle);
         // -> generate zip archive containing Debitoren.csv and Forderungen.csv
         $zip = new ZipArchive();
         $zipFile = $zipFilename . ".zip";
         if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== TRUE) {
             exit("cannot open <{$zipFile}>\n");
         }
         $zip->addFile($debsFilename, 'Debitoren.csv');
         $zip->addFile($itemsFilename, 'Forderungen.csv');
         $zip->close();
         $tm->commitTransaction($tId);
     } catch (Exception $e) {
         $tm->rollback($tId);
         echo $e->__toString();
         exit;
     }
     header("Content-type: application/zip;\n");
     header("Content-Transfer-Encoding: binary");
     $len = filesize($zipFile);
     header("Content-Length: {$len};\n");
     header("Content-Disposition: attachment; filename=\"DATEV.zip\";\n\n");
     readfile($zipFile);
     unlink($zipFile);
     unlink($debsFilename);
     unlink($itemsFilename);
 }