public function printDocs()
 {
     // print payments which are debit returns and have flag print inquiry
     $resultData = array();
     $filters = array(array('field' => 'is_return_debit', 'operator' => 'equals', 'value' => '1'), array('field' => 'print_inquiry', 'operator' => 'equals', 'value' => '1'), array('field' => 'inquiry_print_date', 'operator' => 'isnull', 'value' => ''));
     $objFilter = new Billing_Model_PaymentFilter($filters, 'AND');
     $paymentIds = Billing_Controller_Payment::getInstance()->search($objFilter, null, null, true);
     foreach ($paymentIds as $paymentId) {
         $payment = Billing_Controller_Payment::getInstance()->get($paymentId);
         // get base payment
         $basePayment = $payment->getForeignRecordBreakNull('return_debit_base_payment_id', Billing_Controller_Payment::getInstance());
         if ($basePayment) {
             $batchJobDta = $basePayment->getForeignRecordBreakNull('batch_job_dta_id', Billing_Controller_BatchJobDta::getInstance());
             if ($batchJobDta) {
                 $bankAccount = Billing_Api_BankAccount::getFromBatchJobDta($batchJobDta);
                 $debitor = $payment->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
                 $contact = $debitor->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
                 $data = array();
                 $dummyTextBlocks = null;
                 $data = array_merge($data, Addressbook_Custom_Template::getContactData(array('contact' => $contact, 'user' => Tinebase_Core::get(Tinebase_Core::USER), 'userContact' => Addressbook_Controller_Contact::getInstance()->getContactByUserId(Tinebase_Core::get(Tinebase_Core::USER)->getId())), $dummyTextBlocks));
                 $data = array_merge($data, array('bank_name' => $bankAccount->getBank(), 'account_name' => $bankAccount->getName(), 'account_nr' => $bankAccount->getNumber(), 'bank_code' => $bankAccount->getBankCode()));
                 $resultData[$contact->__get('n_fileas')] = $data;
                 $payment->__set('inquiry_print_date', new Zend_Date());
                 Billing_Controller_Payment::getInstance()->update($payment);
             }
         }
     }
     $outputFileName = 'Ruecklastschrift-Nachforschung-' . strftime('%d-%m-%Y %H-%M-%S') . '.pdf';
     $templateId = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::TEMPLATE_DEBIT_RETURN_INQUIRY);
     ksort($resultData);
     Billing_Controller_PrintJobRecordData::getInstance()->export($resultData, $templateId, $outputFileName);
 }
Example #2
0
 protected function appendDependentRecords($record)
 {
     Tinebase_User::getInstance()->resolveUsers($record, 'created_by');
     Tinebase_User::getInstance()->resolveUsers($record, 'last_modified_by');
     //Tinebase_User::getInstance()->resolveMultipleUsers($_records, 'account_id', true);
     if ($record->__get('order_id')) {
         $this->appendForeignRecordToRecord($record, 'order_id', 'order_id', 'id', new Billing_Backend_Order());
         $order = $record->__get('order_id');
         try {
             if ($order instanceof Billing_Model_Order) {
                 $debitorId = $order->__get('debitor_id');
             } else {
                 $debitorId = $order->debitor_id;
             }
             $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
             if ($order instanceof Billing_Model_Order) {
                 $order->__set('debitor_id', $debitor->toArray());
             } else {
                 $order->debitor_id = $debitor->toArray();
             }
         } catch (Exception $e) {
         }
         $record->__set('order_id', $order);
     }
     if ($record->__get('booking_id')) {
         $this->appendForeignRecordToRecord($record, 'booking_id', 'booking_id', 'id', new Billing_Backend_Booking());
     }
     if ($record->__get('payment_method_id')) {
         $this->appendForeignRecordToRecord($record, 'payment_method_id', 'payment_method_id', 'id', new Billing_Backend_PaymentMethod());
     }
     if ($record->__get('fee_group_id')) {
         $this->appendForeignRecordToRecord($record, 'fee_group_id', 'fee_group_id', 'id', new Membership_Backend_FeeGroup());
     }
     //        $rBackend = new Billing_Backend_ReceiptPosition();
     //        $receiptPositions = $rBackend->getByReceiptId($record->getId());
     //        $sumNetto = 0;
     //        $sumBrutto = 0;
     //        $count = 0;
     //        $totalWeight = 0;
     //        foreach($receiptPositions as $pos){
     //        	$netto = $pos->__get('total_netto');
     //        	$brutto = $pos->__get('total_brutto');
     //        	$weight = $pos->__get('total_weight');
     //        	$sumNetto += $netto;
     //        	$sumBrutto += $brutto;
     //        	$totalWeight += $weight;
     //        	$count++;
     //        }
     //        $record->__set('total_netto', $sumNetto);
     //        $record->__set('total_brutto', $sumBrutto);
     //        $record->__set('pos_count', $count);
     //        $record->__set('total_weight', $totalWeight);
 }
Example #3
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;
     }
 }
 public static function accountBookingToExternalArray(Billing_Model_AccountBooking $accountBooking, &$debSum, &$credSum)
 {
     $booking = $accountBooking->getForeignRecord('booking_id', Billing_Controller_Booking::getInstance());
     //$accountSystem = $accountSystem->getForeignRecord('account_system_id', Billing_Controller_Booking::getInstance());
     $debitorNr = '';
     $debitor = $accountBooking->getForeignRecordBreakNull('debitor_id', Billing_Controller_Debitor::getInstance());
     if ($debitor) {
         $debitorNr = $debitor->__get('debitor_nr');
     }
     $contraBookings = $accountBooking->getContraBookings();
     $aContraText = array();
     foreach ($contraBookings as $contraBooking) {
         $accountSystem = $contraBooking->getForeignRecord('account_system_id', Billing_Controller_AccountSystem::getInstance());
         $accountSystemNr = $accountSystem->__get('number') . ' (' . number_format($contraBooking->__get('value'), 2, ',', '.') . ') ';
         $aContraText[] = $accountSystemNr;
     }
     $strContraText = implode(',', $aContraText);
     $debSum += $accountBooking->__get('debit_value') ? $accountBooking->__get('debit_value') : 0;
     $credSum += (double) ($accountBooking->__get('credit_value') ? $accountBooking->__get('credit_value') : 0);
     $bDate = new Zend_Date($accountBooking->__get('booking_date'));
     $result = array('bnr' => $booking->__get('booking_nr'), 'receipt_nr' => $booking->__get('booking_receipt_nr'), 'usage' => $booking->__get('booking_text'), 'debitor_nr' => $debitorNr, 'contra_account' => $strContraText, 'date' => $bDate->toString('dd.MM.yyyy'), 'deb_value' => $accountBooking->__get('debit_value'), 'deb_value_f' => $accountBooking->__get('debit_value') != 0 ? number_format($accountBooking->__get('debit_value'), 2, ',', '.') : '', 'cred_value' => $accountBooking->__get('credit_value'), 'cred_value_f' => $accountBooking->__get('credit_value') != 0 ? number_format($accountBooking->__get('credit_value'), 2, ',', '.') : '');
     return $result;
 }
Example #5
0
 public static function import($fileName)
 {
     $result = array('failcount' => 0, 'totalcount' => 0, 'duplicatecount' => 0, 'status' => 'success');
     try {
         $reader = new Reader();
         $statements = $reader->getStatements(file_get_contents($fileName));
         foreach ($statements as $statement) {
             foreach ($statement->getTransactions() as $transaction) {
                 //echo $transaction->getAmount() . "\n";
                 $amount = (double) $transaction->getAmount();
                 $description = $transaction->getDescription();
                 $accountNumber = $statement->getAccount()->getNumber();
                 //echo $accountNumber;
                 $num = null;
                 $debitorNr = null;
                 $memberNr = null;
                 $receiptNr = null;
                 $context = 'ERP';
                 $cdesc = strtolower($description);
                 $opNr = null;
                 $openItemId = null;
                 $debitorId = null;
                 $opId = null;
                 $type = null;
                 $state = 'RED';
                 $opAmount = 0;
                 $overpay = 0;
                 if ($amount < 0) {
                     $type = 'DEBIT';
                 } else {
                     $type = 'CREDIT';
                 }
                 if (strpos($cdesc, 'mitg') || strpos($cdesc, 'tgli') || strpos($cdesc, 'beitr')) {
                     $context = 'MEMBERSHIP';
                 } elseif (strpos($cdesc, 'spend')) {
                     $context = 'DONATOR';
                 }
                 $isReturnDebit = false;
                 if (strpos($cdesc, 'rueckbelast')) {
                     $isReturnDebit = true;
                 }
                 $numDesc = $transaction->getDescriptionConcat(1, 7);
                 $numDescCheck = strtolower($numDesc);
                 $pos = strpos($numDescCheck, 'mitg');
                 if (!$pos) {
                     $pos = strpos($numDescCheck, 'tgli');
                 }
                 if (!pos) {
                     $pos = strpos($numDescCheck, 'beitr');
                 }
                 if (!pos) {
                     $pos = strpos($numDescCheck, 'rech');
                 }
                 if ($numDesc && $pos) {
                     if (preg_match('/([0-9]{5,7})/', substr($numDesc, $pos), $match)) {
                         $num = $match[1];
                     }
                 }
                 if ($num && !$isReturnDebit) {
                     if (strpos($cdesc, 'rech')) {
                         try {
                             $receiptNr = $num;
                             $receiptId = Billing_Controller_Receipt::getInstance()->getIdByProperty('invoice_nr', $num);
                             $receipt = Billing_Controller_Receipt::getInstance()->get($receiptId);
                             $context = $receipt->getForeignId('erp_context_id');
                             $order = $receipt->getForeignRecordBreakNull('order_id', Billing_Controller_Order::getInstance());
                             $debitor = $order->getForeignRecordBreakNull('debitor_id', Billing_Controller_Debitor::getInstance());
                             if ($debitor) {
                                 $debitorId = $debitor->getId();
                                 $state = 'ORANGE';
                                 $openItems = Billing_Controller_OpenItem::getInstance()->getByDebitor($debitorId);
                                 foreach ($openItems as $op) {
                                     if ($op->__get('state') != 'DONE') {
                                         $openItem = $op;
                                         break;
                                     }
                                 }
                                 //$openItem = $openItems->getFirstRecord();
                                 $openItemId = $openItem->getId();
                                 $opAmount = $openItem->__get('open_sum');
                             }
                             if (abs($amount) > abs($opAmount)) {
                                 $overpay = abs($amount) - abs($opAmount);
                             }
                             if ($overpay == 0) {
                                 $state = 'GREEN';
                             }
                             /*if((float)abs($openItem->__get('total_brutto')) == (float)abs($amount)){
                             			$state = 'GREEN';
                             		}*/
                         } catch (Exception $e) {
                         }
                     } elseif (strpos($cdesc, 'mitg')) {
                         $memberNr = $num;
                         try {
                             $member = Membership_Controller_SoMember::getInstance()->getSoMemberByMemberNr($memberNr);
                             $contactId = $member->getForeignId('contact_id');
                             $debitorId = Billing_Controller_Debitor::getInstance()->getIdByContactId($contactId);
                             $state = 'ORANGE';
                             $openItems = Billing_Controller_OpenItem::getInstance()->getByDebitor($debitorId);
                             foreach ($openItems as $op) {
                                 if ($op->__get('state') != 'DONE') {
                                     $openItem = $op;
                                     break;
                                 }
                             }
                             //$openItem = $openItems->getFirstRecord();
                             if ($openItem) {
                                 $openItemId = $openItem->getId();
                                 $opAmount = $openItem->__get('open_sum');
                                 if (abs($amount) > abs($opAmount)) {
                                     $overpay = abs($amount) - abs($opAmount);
                                 }
                                 if ($overpay == 0) {
                                     $state = 'GREEN';
                                 }
                             }
                             /*if((float)abs($openItem->__get('total_brutto')) == (float)abs($amount)){
                             			$state = 'GREEN';
                             		}*/
                         } catch (Exception $e) {
                         }
                     } else {
                         try {
                             $contactId = (int) trim($num);
                             $debitorId = Billing_Controller_Debitor::getInstance()->getIdByContactId($contactId);
                             $state = 'ORANGE';
                             $openItems = Billing_Controller_OpenItem::getInstance()->getByDebitor($debitorId);
                             foreach ($openItems as $op) {
                                 if ($op->__get('state') != 'DONE') {
                                     $openItem = $op;
                                     break;
                                 }
                             }
                             // changed behviour: was only correct in first period :-/
                             //$openItem = $openItems->getFirstRecord();
                             if ($openItem) {
                                 $openItemId = $openItem->getId();
                                 $opAmount = $openItem->__get('open_sum');
                             }
                             if (abs($amount) > abs($opAmount)) {
                                 $overpay = abs($amount) - abs($opAmount);
                             }
                             if ($overpay == 0) {
                                 $state = 'GREEN';
                             }
                             //if((float)abs($openItem->__get('total_brutto')) == (float)abs($amount)){
                             //	$state = 'GREEN';
                             //}
                         } catch (Exception $e) {
                         }
                     }
                 }
                 if ($isReturnDebit) {
                     $returnDebitFee = (double) Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::DEBIT_RETURN_FEE);
                     if ($num) {
                         $contactId = (int) trim($num);
                         $debitorId = null;
                         try {
                             $debitorId = Billing_Controller_Debitor::getInstance()->getIdByContactId($contactId);
                             $state = 'ORANGE';
                         } catch (Exception $e) {
                             $state = 'RED';
                         }
                         try {
                             $toReturnPayment = Billing_Controller_Payment::getInstance()->getDebitToReturn($debitorId, $amount, $returnDebitFee, 'DEBIT');
                             $returnPaymentId = $toReturnPayment->getId();
                             if ($returnPaymentId && $debitorId && $toReturnPayment->__get('is_cancelled') == false) {
                                 $state = 'GREEN';
                             }
                             if ($toReturnPayment->__get('is_cancelled') == true) {
                                 $returnPaymentId = null;
                             }
                         } catch (Exception $e) {
                             $returnPaymentId = null;
                         }
                     }
                 }
                 $id = md5($cdesc);
                 try {
                     $payment = Billing_Controller_MT940Payment::getInstance()->get($id);
                 } catch (Exception $e) {
                     $payment = Billing_Controller_MT940Payment::getInstance()->getEmptyMT940Payment();
                     $bankAccount = Billing_Controller_AccountSystem::getInstance()->getDefaultBankAccount();
                     $fordAccount = Billing_Controller_AccountSystem::getInstance()->getByNumber('14000');
                     if (!$isReturnDebit) {
                         if ($type == 'DEBIT') {
                             $payment->__set('account_system_id', $bankAccount->getId());
                             $payment->__set('account_system_id_haben', $fordAccount->getId());
                         } else {
                             $payment->__set('account_system_id', $fordAccount->getId());
                             $payment->__set('account_system_id_haben', $bankAccount->getId());
                         }
                     } else {
                         $debitSettleAccount = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::FIBU_KTO_DEBITOR);
                         $payment->__set('account_system_id', $debitSettleAccount);
                         $payment->__set('account_system_id_haben', $bankAccount->getId());
                         $payment->__set('is_return_debit', true);
                         $payment->__set('print_inquiry', true);
                         $payment->__set('set_accounts_banktransfer', true);
                         $payment->__set('return_inquiry_fee', $returnDebitFee);
                         $payment->__set('return_debit_base_payment_id', $returnPaymentId);
                     }
                     $payment->__set('id', $id);
                     $payment->__set('erp_context_id', $context);
                     if ($opNr) {
                         $payment->__set('op_nr', $opNr);
                     }
                     if ($openItemId) {
                         $payment->__set('op_id', $openItemId);
                         $payment->__set('due_date', new Zend_Date($openItem->__get('due_date')));
                         $payment->__set('op_amount', $openItem->__get('total_brutto'));
                     }
                     if ($debitorId) {
                         $payment->__set('debitor_id', $debitorId);
                     }
                     $payment->__set('type', $type);
                     $payment->__set('payment_date', new Zend_Date($transaction->getBookDate()->format('Y-m-d H:i:s')));
                     $payment->__set('payment_amount', abs($amount));
                     $payment->__set('state', $state);
                     $payment->__set('usage_payment', $description);
                     $payment->__set('usage', $numDesc);
                     $payment->__set('overpay_amount', $overpay);
                     Billing_Controller_MT940Payment::getInstance()->create($payment);
                 }
             }
             /*echo $statement->getOpeningBalance()->getAmount() . "\n";
               
                  foreach ($statement->getTransactions() as $transaction) {
                      echo $transaction->getAmount() . "\n";
                  }
               
                  echo $statement->getClosingBalance()->getAmount() . "\n";*/
         }
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' ' . 'TD-Import - Es trat ein Fehler auf. Nicht ausgeführt.' . print_r($e->__toString(), true));
         $result['status'] = 'error';
         $result['errorInfo'] = $e->getMessage();
         $result['errorTrace'] = $e->getTrace();
     }
     return $result;
 }
Example #6
0
 public function printAddressLabelsByFilter($outputType, $filters, $userOptions, $types, $sort)
 {
     $sortField = 'creation_time';
     $sortDir = 'ASC';
     $sort = Zend_Json::decode($sort);
     $this->setUseSorting(true);
     if (is_array($sort) && array_key_exists('field', $sort) && array_key_exists('order', $sort)) {
         if (in_array($sort['field'], array('creation_time', 'order_nr'))) {
             $sortField = $sort['field'];
         }
         if (in_array($sort['order'], array('ASC', 'DESC'))) {
             $sortDir = $sort['order'];
         }
     }
     $this->setTypes(Zend_Json::decode($types));
     $this->setOutputType($outputType);
     $this->setPreview($preview);
     $this->setFilters($filters);
     $this->setUserOptions($userOptions);
     $filters = $this->createFilters();
     $paging = new Tinebase_Model_Pagination(array('sort' => $sortField, 'dir' => $sortDir));
     // -> get ids only
     $receipts = $this->_receiptController->search($filters, $paging);
     $orderIds = $receipts->__getFlattened('order_id');
     $orders = Billing_Controller_Order::getInstance()->getMultiple($orderIds);
     $debitorIds = $orders->__getFlattened('debitor_id');
     $debitorController = Billing_Controller_Debitor::getInstance();
     $contactIds = array();
     foreach ($debitorIds as $debitorId) {
         $contactIds[] = $debitorController->getContactIdForDebitorId($debitorId);
     }
     // print adress labels for given contact ids
     Addressbook_Controller_Contact::getInstance()->printAddressLabelsForContactIds($contactIds, Addressbook_Model_Contact::INVOICE_ADDRESS, array('DE'));
 }
Example #7
0
 /**
  * 
  * Save a debitor record (create/update)
  * @param array $recordData
  */
 public function saveDebitor($recordData)
 {
     return $this->_save($recordData, Billing_Controller_Debitor::getInstance(), 'Debitor');
 }
 public function prepareMonitionExport(Billing_Model_BatchJob $job)
 {
     error_reporting(E_ALL);
     set_time_limit(0);
     \org\sopen\dev\DebugLogger::openLogFileOverwrite(CSopen::instance()->getCustomerPath() . '/conf/logs/mon.log');
     //throw new Exception(CSopen::instance()->getCustomerPath().'/conf/logs/mon.log');
     try {
         $db = Tinebase_Core::getDb();
         $tm = Tinebase_TransactionManager::getInstance();
         $tId = $tm->startTransaction($db);
         $job = Billing_Api_BatchJobManager::getInstance()->loadBatchJob($job->getId());
         //			Billing_Api_BatchJobManager::getInstance()->startBatchJob();
         $data = $job->getData();
         $filters = $data['filters'];
         $aContexts = $data['contexts'];
         if (!is_array($aContexts)) {
             $aContexts = Zend_Json::decode($aContexts);
         }
         $pagination = new Tinebase_Model_Pagination();
         //require_once 'Payment/Monition.php';
         if (!is_array($filters)) {
             $filters = Zend_Json::decode($filters);
         }
         /*if(!is_array($paymentTypeKeys)){
         				$paymentTypeKeys = Zend_Json::decode($paymentTypeKeys);
         			}
         
         			$paymentTypeKeys = array(
         				1 => 'DEBIT',
         				2 => 'DEBIT_GM'
         			);*/
         $monitionStage1Days = (int) Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::MONITION_STAGE1);
         // get all open items (for debit)
         // grouped by debitors
         $filters[] = array('field' => 'due_days', 'operator' => 'greater', 'value' => $monitionStage1Days);
         /*		$filters[] = array(
            		'field' => 'type',
            		'operator' => 'notin',
            		'value' => $paymentTypeKeys
           		);*/
         $filters[] = array('field' => 'state', 'operator' => 'not', 'value' => 'DONE');
         $contextFilters = array();
         foreach ($aContexts as $context => $flag) {
             if ($flag) {
                 $contextFilters[] = $context;
             }
         }
         $filters[] = array('field' => 'erp_context_id', 'operator' => 'in', 'value' => $contextFilters);
         //$rawFilters = $filters;
         //$paymentTypeCount = count($paymentTypeKeys);
         /*$filters[] = array(
         		'field' => 'payment_method_id',
         		'operator' => 'equals',
         		'value' => $paymentTypeKeys[1]
         		);*/
         //print_r($filters);
         $filter = new Billing_Model_OpenItemFilter($filters, 'AND');
         // count membership matching filters
         $openItemIds = Billing_Controller_OpenItem::getInstance()->search($filter, new Tinebase_Model_Pagination(array('sort' => 'id', 'dir' => 'ASC')), false, true);
         //print_r($openItemIds);
         $debitorOpenItemIds = array();
         foreach ($openItemIds as $openItemId) {
             $openItem = Billing_Controller_OpenItem::getInstance()->get($openItemId);
             $debitorId = $openItem->getForeignId('debitor_id');
             if (!array_key_exists($debitorId, $debitorOpenItemIds)) {
                 $debitorOpenItemIds[$debitorId] = array();
             }
             $debitorOpenItemIds[$debitorId][] = $openItemId;
         }
         foreach ($debitorOpenItemIds as $debitorId => $debitorOpenItems) {
             $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
             $contact = $debitor->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
             $aSaldation = Billing_Controller_DebitorAccount::getInstance()->getSummationByDebitorId($debitorId, $contextFilters);
             $saldation = $aSaldation['sum'];
             $batchJobMonition = new Billing_Model_BatchJobMonition(null, true);
             $batchJobMonition->setFromArray(array('job_id' => $job->getId(), 'contact_id' => $contact->getId(), 'debitor_id' => $debitor->getId(), 'monition_stage' => 1, 'total_sum' => 0, 'open_sum' => 0, 'total_saldation' => 0, 'count_pos' => 0, 'monition_lock' => $debitor->__get('is_monition_locked'), 'skip' => false, 'action_text' => '', 'action_data' => null, 'action_type' => 'DRYRUN', 'action_state' => 'OPEN', 'error_info' => $errorInfo, 'created_datetime' => Zend_Date::now(), 'valid_datetime' => Zend_Date::now(), 'to_process_datetime' => Zend_Date::now(), 'process_datetime' => Zend_Date::now(), 'usage' => ''));
             $batchJobMonition = $this->create($batchJobMonition);
             $batchJobMonitionId = $batchJobMonition->getId();
             $posCount = count($debitorOpenItems);
             $totalSum = 0;
             $totalBruttoSum = 0;
             $usages = array();
             $maxMonitionStage = 1;
             foreach ($debitorOpenItems as $openItemId) {
                 $openItem = Billing_Controller_OpenItem::getInstance()->get($openItemId);
                 $sum = (double) $openItem->__get('open_sum');
                 $totalBrutto = (double) $openItem->__get('total_brutto');
                 $batchJobMonitionItem = new Billing_Model_BatchJobMonitionItem(null, true);
                 $batchJobMonitionItem->setFromArray(array('batch_monition_id' => $batchJobMonitionId, 'open_item_id' => $openItem->getId(), 'erp_context_id' => $openItem->__get('erp_context_id'), 'open_sum' => $sum, 'total_sum' => $totalBrutto, 'monition_stage' => $openItem->getNextMonitionStage(), 'due_days' => $openItem->__get('due_days'), 'skip' => false, 'usage' => $openItem->__get('usage')));
                 $usages[] = $openItem->__get('usage');
                 $totalSum += $sum;
                 $totalBruttoSum += $totalBrutto;
                 $maxMonitionStage = max($maxMonitionStage, $openItem->getNextMonitionStage());
                 Billing_Controller_BatchJobMonitionItem::getInstance()->create($batchJobMonitionItem);
             }
             $usage = implode(' ', $usages);
             $batchJobMonition->__set('usage', $usage);
             $batchJobMonition->__set('open_sum', $totalSum);
             $batchJobMonition->__set('total_sum', $totalBruttoSum);
             $batchJobMonition->__set('total_saldation', $saldation);
             $batchJobMonition->__set('monition_stage', $maxMonitionStage);
             $batchJobMonition->__set('count_pos', $posCount);
             $this->update($batchJobMonition);
         }
         Billing_Api_BatchJobManager::getInstance()->finish();
         $tm->commitTransaction($tId);
         \org\sopen\dev\DebugLogger::close();
         return array('state' => 'success', 'result' => null);
     } catch (Exception $e) {
         // $e->__toString();
         $tm->rollback($tId);
         Billing_Api_BatchJobManager::getInstance()->finishError($e->__toString());
         \org\sopen\dev\DebugLogger::log($e->__toString);
         \org\sopen\dev\DebugLogger::close();
         return array('state' => 'failure', 'result' => null, 'errorInfo' => array('message' => $e->getMessage(), 'trace' => $e->getTrace()));
     }
 }
Example #9
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);
 }
Example #10
0
 public function directDebit($paymentTypeKeys, $filters)
 {
     $db = Tinebase_Core::getDb();
     $tm = Tinebase_TransactionManager::getInstance();
     try {
         require_once 'Payment/DTA.php';
         if (!is_array($filters)) {
             $filters = Zend_Json::decode($filters);
         }
         if (!is_array($paymentTypeKeys)) {
             $paymentTypeKeys = Zend_Json::decode($paymentTypeKeys);
         }
         $filters[] = array('field' => 'banking_exp_date', 'operator' => 'isnull', 'value' => '');
         $rawFilters = $filters;
         $paymentTypeCount = count($paymentTypeKeys);
         $filters[] = array('field' => 'payment_method_id', 'operator' => 'equals', 'value' => $paymentTypeKeys[1]);
         $filter1 = new Billing_Model_OpenItemFilter($filters, 'AND');
         $filter = new Tinebase_Model_Filter_FilterGroup(array(), 'OR');
         $filter->addFilterGroup($filter1);
         if ($paymentTypeCount > 1) {
             unset($paymentTypeKeys[1]);
             foreach ($paymentTypeKeys as $paymentTypeKey) {
                 $newFilters = $rawFilters;
                 $newFilters[] = array('field' => 'payment_method_id', 'operator' => 'equals', 'value' => $paymentTypeKey);
                 $pFilterGroup = new Billing_Model_OpenItemFilter($newFilters, 'AND');
                 $filter->addFilterGroup($pFilterGroup);
             }
         }
         // start transaction
         $tId = $tm->startTransaction($db);
         // count membership matching filters
         $openItemIds = $this->search($filter, new Tinebase_Model_Pagination(array('sort' => 'due_date', 'dir' => 'ASC')), false, true);
         $tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         $mandators = \Tinebase_Config::getInstance()->getConfig('mandators', NULL, TRUE)->value;
         $mandator = $mandators[1]['bankdata'];
         $hash = md5(serialize($mandator) . microtime());
         $dtaFile = new DTA(DTA_DEBIT);
         $dtaFile->setAccountFileSender(array("name" => $mandator['account_holder'], "bank_code" => $mandator['bank_code'], "account_number" => $mandator['account_number']));
         // 		create DTA file
         foreach ($openItemIds as $openItemId) {
             $openItem = $this->get($openItemId);
             // value
             $val = (double) $openItem->__get('open_sum');
             $usage = $openItem->__get('usage');
             $u = explode(',', $usage);
             $u1 = $u2 = '';
             if (count($u) > 0) {
                 $u1 = $u[0];
                 $u2 = $u[1];
             } else {
                 $u1 = $usage;
             }
             if ($val > 0) {
                 $debitor = $openItem->getForeignRecordBreakNull('debitor_id', Billing_Controller_Debitor::getInstance());
                 if (!$debitor) {
                     continue;
                 }
                 $contact = $debitor->getForeignRecordBreakNull('contact_id', Addressbook_Controller_Contact::getInstance());
                 if (!$contact) {
                     continue;
                 }
                 $receipt = $openItem->getForeignRecordBreakNull('receipt_id', Billing_Controller_Receipt::getInstance());
                 $dtaFile->addExchange(array("name" => $contact->__get('bank_account_name'), "bank_code" => $contact->__get('bank_code'), "account_number" => $contact->__get('bank_account_number')), (string) $val, array($u1, $u2));
             }
             $openItem->__set('banking_exp_date', new Zend_Date());
             $this->update($openItem);
         }
         $dtaFile->saveFile($tempFilePath . 'DTAUS0' . $hash);
         $meta = $dtaFile->getMetaData();
         $date = strftime("%d.%m.%y", $meta["date"]);
         $execDate = strftime("%d.%m.%y", $meta["exec_date"]);
         $count = $meta["count"];
         $sumEUR = $meta["sum_amounts"];
         $sumKto = $meta["sum_accounts"];
         $sumBankCodes = $meta["sum_bankcodes"];
         $sender = $mandator['account_holder'];
         $senderBank = $mandator['bank'];
         $senderBankCode = $mandator['bank_code'];
         $senderAccount = $mandator['account_number'];
         $handoutContent = "Datenträger-Begleitzettel\n\tErstellungsdatum: {$date} \n\tAusführungsdatum: {$execDate}\n\tAnzahl der Lastschriften: {$count}\n\tSumme der Beträge in EUR: {$sumEUR}\n\tKontrollsumme Kontonummern: {$sumKto}\n\tKontrollsumme Bankleitzahlen: {$sumBankCodes}\n\tAuftraggeber: {$sender}\n\tBeauftragtes Bankinstitut: {$senderBank}\n\tBankleitzahl: {$senderBankCode}\n\tKontonummer: {$senderAccount}";
         $zip = new ZipArchive();
         $filename = "{$tempFilePath}/DTAUS0-{$ogNr}.zip";
         if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) {
             exit("cannot open <{$filename}>\n");
         }
         $zip->addFromString("begleitzettel.txt", $handoutContent);
         $zip->addFile($tempFilePath . 'DTAUS0' . $hash, 'DTAUS0');
         $zip->close();
         header("Content-type: application/zip;\n");
         header("Content-Transfer-Encoding: binary");
         $len = filesize($filename);
         header("Content-Length: {$len};\n");
         $outname = "DTAUS0-{$ogNr}.zip";
         header("Content-Disposition: attachment; filename=\"{$outname}\";\n\n");
         readfile($filename);
         unlink($filename);
         $tm->commitTransaction($tId);
     } catch (Exception $e) {
         $tm->rollback($tId);
     }
 }
Example #11
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));
         }
     }
 }
Example #12
0
 /**
  * 
  * Fetches a debitor record by it's contact_id or creates it, if it does not exist
  * @param int $contactId
  */
 public function getByContactOrCreate($contactId, $additionalData = null)
 {
     try {
         $debitor = $this->_backend->getByContactId($contactId);
     } catch (Exception $e) {
         $contact = Addressbook_Controller_Contact::getInstance()->get($contactId);
         $debitor = Addressbook_Custom_Contact::createDebitorFromContact($contact);
         if (is_array($additionalData)) {
             $debitor->setFromArray($additionalData);
             return Billing_Controller_Debitor::getInstance()->update($debitor);
         }
         $debitor = Billing_Controller_Debitor::getInstance()->get($debitor->getId());
     }
     return $debitor;
 }
Example #13
0
 public function onPaymentBooked($payment, $booking)
 {
     if ($payment->__get('debitor_id')) {
         $debitorAccount = Billing_Controller_DebitorAccount::getInstance()->getEmptyDebitorAccount();
         $debitor = $payment->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
         $debitorAccount->__set('debitor_id', $debitor->getId());
         $debitorAccount->__set('create_date', new Zend_Date($payment->__get('payment_date')));
         $debitorAccount->__set('value_date', new Zend_Date($payment->__get('payment_date')));
         $debitorAccount->__set('usage', $payment->__get('usage'));
         $debitorAccount->__set('erp_context_id', $payment->__get('erp_context_id'));
         $debitorAccount->__set('payment_id', $payment->__get('id'));
         $debitorAccount->__set('booking_id', $booking->getId());
         $debitorAccount->__set('receipt_id', $payment->getForeignId('receipt_id'));
         //			$debitorAccount->__set('open_item_id', $payment->getForeignId('open_item_id'));
         $debitorAccount->__set('donation_id', $payment->getForeignId('donation_id'));
         // other object: like donation for example (not a clean approach)
         $debitorAccount->__set('object_id', $payment->getForeignId('object_id'));
         $debitorAccount->__set('donation_id', $payment->getForeignId('donation_id'));
         $debitorAccount->__set('is_cancelled', $payment->__get('is_cancelled'));
         $debitorAccount->__set('is_cancellation', $payment->__get('is_cancellation'));
         //$cKto = $payment->getForeignId('account_system_id_haben');
         //$dKto = $payment->getForeignId('account_system_id');
         switch ($payment->__get('type')) {
             case 'DEBIT':
                 $debitorAccount->__set('item_type', 'DEBIT');
                 $debitorAccount->__set('h_brutto', abs($payment->getAmount(false)));
                 break;
             case 'CREDIT':
                 $debitorAccount->__set('item_type', 'CREDIT');
                 $debitorAccount->__set('s_brutto', abs($payment->getAmount(false)));
                 break;
         }
         if ($payment->__get('payment_type') == 'PAYMENT') {
             $debitorAccount->__set('item_type', 'PAYMENT');
         } else {
             $debitorAccount->__set('item_type', 'DISAGIO');
         }
         Billing_Controller_DebitorAccount::getInstance()->create($debitorAccount);
     }
     /*
         	if($payment->__get('receipt_id')){
             	$receipt = $payment->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
             	
             	$openItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($receipt->getId());
             	Billing_Controller_OpenItem::getInstance()->payOpenItem($openItem->getId(), $payment);
             	
             	$totalBrutto = $receipt->__get('total_brutto');
             	$amount = $payment->__get('amount');
             	if($payment->__get('amount') == $totalBrutto){
             		$receipt->__set('payment_state', 'PAYED');
             	}elseif($payment->__get('amount') == 0){
             		$receipt->__set('payment_state', 'TOBEPAYED');
             	}elseif($payment->__get('amount') < $totalBrutto){
             		$receipt->__set('payment_state', 'PARTLYPAYED');
             	}
             	$receipt = Billing_Controller_Receipt::getInstance()->update($receipt);
             }*/
 }
Example #14
0
 public function prepareDebitDtaExport(Billing_Model_BatchJob $job)
 {
     error_reporting(E_ALL);
     set_time_limit(0);
     try {
         $dueDate = new Zend_Date();
         $db = Tinebase_Core::getDb();
         $tm = Tinebase_TransactionManager::getInstance();
         $tId = $tm->startTransaction($db);
         $job = Billing_Api_BatchJobManager::getInstance()->loadBatchJob($job->getId());
         //			Billing_Api_BatchJobManager::getInstance()->startBatchJob();
         $data = $job->getData();
         $filters = $data['filters'];
         $aContexts = $data['contexts'];
         if (!is_array($aContexts)) {
             $aContexts = Zend_Json::decode($aContexts);
         }
         $pagination = new Tinebase_Model_Pagination();
         //require_once 'Payment/DTA.php';
         if (!is_array($filters)) {
             $filters = Zend_Json::decode($filters);
         }
         // get all open items (for debit)
         // grouped by debitors
         /*$filters[] = array(
         		'field' => 'banking_exp_date',
         		'operator' => 'isnull',
         		'value' => ''
         		);*/
         $filters[] = array('field' => 'state', 'operator' => 'not', 'value' => 'DONE');
         $filters[] = array('field' => 'type', 'operator' => 'equals', 'value' => 'DEBIT');
         $filters[] = array('field' => 'is_cancelled', 'operator' => 'equals', 'value' => 0);
         $filters[] = array('field' => 'is_cancellation', 'operator' => 'equals', 'value' => 0);
         //$contextFilters = array('ERP');
         $contextFilters = array();
         foreach ($aContexts as $context => $flag) {
             if ($flag) {
                 $contextFilters[] = $context;
             }
         }
         $filters[] = array('field' => 'erp_context_id', 'operator' => 'in', 'value' => $contextFilters);
         $rawFilters = $filters;
         $paymentTypeCount = count($paymentTypeKeys);
         $filter = new Billing_Model_OpenItemFilter($filters, 'AND');
         // due date: means date of execution of debit -> necessary for determination of sepa mandates
         // Telefonat: Rudat, hhartl 14.05.2014
         // "wenn im Filter angegeben, dann verwenden, ansonsten Tagesdatum"
         if ($filter->isFilterSet("due_date")) {
             $dueDate = new Zend_Date($filter->getFilter("due_date")->getValue());
         }
         // count membership matching filters
         $openItemIds = Billing_Controller_OpenItem::getInstance()->search($filter, new Tinebase_Model_Pagination(array('sort' => 'id', 'dir' => 'ASC')), false, true);
         //ob_start();
         $debitorOpenItemIds = array();
         $limit = 0;
         //echo "global count: ".count($openItemIds);
         foreach ($openItemIds as $openItemId) {
             /*if($limit++ > 250){
             			break;
             		}*/
             $openItem = Billing_Controller_OpenItem::getInstance()->get($openItemId);
             $debitorId = $openItem->getForeignId('debitor_id');
             if (!array_key_exists($debitorId, $debitorOpenItemIds)) {
                 $debitorOpenItemIds[$debitorId] = array();
             }
             $debitorOpenItemIds[$debitorId][] = $openItemId;
         }
         $addFilters = array();
         $addFilters[] = array('field' => 'membership_type', 'operator' => 'notin', 'value' => array('MEMBER_EX', 'MEMBER_GESCHENK', 'SCHENKER'));
         foreach ($debitorOpenItemIds as $debitorId => $debitorOpenItems) {
             $debitor = null;
             $contact = null;
             $contactId = null;
             $isError = false;
             try {
                 $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
                 $contactId = $debitor->getForeignId('contact_id');
                 $contact = $debitor->getForeignRecord('contact_id', Addressbook_Controller_Contact::getInstance());
                 $valid = 'UNKNOWN';
                 $activeMembershipIds = Membership_Controller_SoMember::getInstance()->getActiveMembershipsByContactId($contact->getId(), $dueDate, $addFilters);
                 $mandate = null;
                 $count = count($activeMembershipIds);
                 if (count($activeMembershipIds) == 1) {
                     $membership = Membership_Controller_SoMember::getInstance()->getSoMember($activeMembershipIds[0]);
                     if ($membership->allowsSepaDirectDebit($dueDate)) {
                         //echo "has::";
                         $hasMandate = true;
                         $mandate = $membership->getForeignRecordBreakNull('sepa_mandate_id', Billing_Controller_SepaMandate::getInstance());
                         $valid = 'YES';
                     }
                     $bankAccount = $membership->getForeignRecordBreakNull('bank_account_id', Billing_Controller_BankAccount::getInstance());
                 } elseif (count($activeMembershipIds) == 0) {
                     $regularDonations = Donator_Controller_RegularDonation::getInstance()->getByContactId($contact->getId());
                     foreach ($regularDonations as $regDon) {
                         if ($regDon->allowsSepaDirectDebit()) {
                             $mandate = $regDon->getForeignRecordBreakNull('sepa_mandate_id', Billing_Controller_SepaMandate::getInstance());
                             $valid = 'YES';
                             //echo "has::";
                             break;
                         }
                     }
                 }
                 $bankAccountName = '';
                 $bankName = '';
                 //echo "adr $contactId - count: $count\r\n";
                 if (is_null($mandate)) {
                     $bankAccount = null;
                     $valid = 'NO';
                     $sepaMandateId = null;
                     $bankAccountId = null;
                     $receipt = $openItem->getForeignRecordBreakNull('receipt_id', Billing_Controller_Receipt::getInstance());
                     $text = 'Kein gültiges Sepa-Mandat';
                     if ($receipt->getForeignId('payment_method_id') != 'DEBIT') {
                         continue;
                     }
                 } else {
                     $text = 'Sepa-Lastschrift';
                     $bankAccountId = $mandate->getForeignIdBreakNull('bank_account_id');
                     $sepaMandateId = $mandate->getId();
                 }
                 $errorInfo = '';
                 // REMARK[HH, 2013-08-23]: now set saldation contexts chosen by checkbox in start dialog:
                 // fixes quickhack hardcoded array('MEMBERSHIP','DONATOR')
                 //
                 $aSaldation = Billing_Controller_DebitorAccount::getInstance()->getSummationByDebitorId($debitorId, $contextFilters);
                 $saldation = $aSaldation['sum'];
                 $actionState = 'OPEN';
             } catch (Exception $e) {
                 $isError = true;
                 $valid = "NO";
                 $text = "Fehler - Debitor {$debitorId} kann nicht verarbeitet werden.";
                 $em = "";
                 if (is_null($debitor)) {
                     $em .= "Debitor konnte nicht geladen werden " . $debitorId . " ";
                 }
                 if (is_null($contact) || is_null($contactId)) {
                     $em .= "Kontakt konnte nicht geladen werden. Debitor.Nr.:" . $debitorId;
                 }
                 $errorInfo = "Fehler: " . $em . " <br/>\r\n Original-Meldung: " . $e->__toString();
                 $bankAccountId = null;
                 $mandate = null;
                 $actionState = 'ERROR';
                 $bankAccountName = "";
                 $bankName = "";
                 $sepaMandateId = null;
                 $contactId = $debitorId;
             }
             $batchJobDta = new Billing_Model_BatchJobDta(null, true);
             $batchJobDta->setFromArray(array('job_id' => $job->getId(), 'contact_id' => $contactId, 'debitor_id' => $debitorId, 'bank_account_id' => $bankAccountId, 'bank_account_usage_id' => 1, 'sepa_mandate_id' => $sepaMandateId, 'bank_valid' => $valid, 'bank_account_number' => 0, 'bank_code' => 0, 'bank_account_name' => $bankAccountName, 'bank_name' => $bankName, 'total_sum' => 0, 'total_saldation' => $saldation, 'diff_saldation' => 0, 'count_pos' => 0, 'skip' => !is_null($mandate), 'action_text' => $text, 'action_data' => null, 'action_type' => 'DRYRUN', 'action_state' => $actionState, 'error_info' => $errorInfo, 'created_datetime' => Zend_Date::now(), 'valid_datetime' => Zend_Date::now(), 'to_process_datetime' => Zend_Date::now(), 'process_datetime' => Zend_Date::now(), 'usage' => ''));
             $batchJobDta = $this->create($batchJobDta);
             if (!$isError) {
                 $batchJobDtaId = $batchJobDta->getId();
                 $posCount = count($debitorOpenItems);
                 $totalSum = 0;
                 $usages = array();
                 foreach ($debitorOpenItems as $openItemId) {
                     $openItem = Billing_Controller_OpenItem::getInstance()->get($openItemId);
                     $sum = (double) $openItem->__get('open_sum');
                     $batchJobDtaItem = new Billing_Model_BatchJobDtaItem(null, true);
                     $batchJobDtaItem->setFromArray(array('batch_dta_id' => $batchJobDtaId, 'open_item_id' => $openItem->getId(), 'erp_context_id' => $openItem->__get('erp_context_id'), 'total_sum' => $sum, 'skip' => false, 'usage' => $openItem->__get('usage')));
                     $usages[] = $openItem->__get('usage');
                     $totalSum += $sum;
                     Billing_Controller_BatchJobDtaItem::getInstance()->create($batchJobDtaItem);
                 }
                 $usage = implode(' ', $usages);
                 $batchJobDta->__set('usage', $usage);
                 $batchJobDta->__set('total_sum', $totalSum);
                 $batchJobDta->__set('diff_saldation', $totalSum + $saldation);
                 if ($totalSum + $saldation != 0) {
                     $batchJobDta->__set('action_text', $batchJobDta->__get('action_text') . ' Differenz überprüfen');
                 }
                 $batchJobDta->__set('count_pos', $posCount);
                 $this->update($batchJobDta);
             }
         }
         //$log = ob_get_clean();
         //Billing_Api_BatchJobManager::getInstance()->finishError($log);
         Billing_Api_BatchJobManager::getInstance()->finish();
         $tm->commitTransaction($tId);
         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()));
     }
 }
Example #15
0
 public function bookPayments($payments)
 {
     //throw new Zend_Exception('Temporarily disabled');
     foreach ($payments as $payment) {
         if ($payment->hasAdditionalItem('donation')) {
             $donationData = $payment->getAdditionalItem('donation');
         } else {
             $donationData = null;
         }
         if ($payment->hasMultipleOpenItems()) {
             $additionalData = $payment->getAdditionalData();
             if ($payment->hasAdditionalItem('openItems')) {
                 $data = $payment->getAdditionalItem('openItems');
                 $donationData = $payment->getAdditionalItem('donation');
                 $payment->flatten();
                 $paymentRecord = $payment->toArray();
                 $paymentRecord['amount'] = $paymentRecord['payment_amount'];
                 Billing_Controller_OpenItem::getInstance()->payOpenItems($data, $paymentRecord, $donationData);
             }
         } else {
             $pExtract = clone $payment;
             $pExtract->flatten();
             $paymentRecord = $pExtract->toArray();
             $paymentO = Billing_Controller_Payment::getInstance()->getEmptyPayment();
             if (array_key_exists('id', $paymentRecord)) {
                 unset($paymentRecord['id']);
             }
             $paymentO->setFromArray($paymentRecord);
             $paymentO->__set('amount', $payment->__get('payment_amount'));
             $openItem = $payment->getForeignRecordBreakNull('op_id', Billing_Controller_OpenItem::getInstance());
             if ($openItem) {
                 if ($payment->__get('overpay') == 'DONATION' && !$payment->__get('is_return_debit') && $donationData) {
                     $opAmount = abs((double) $openItem->__get('open_sum'));
                     $pAmount = abs((double) $payment->__get('payment_amount'));
                     if ($pAmount > $opAmount) {
                         $donationAmount = $pAmount - $opAmount;
                         $payment2 = clone $paymentO;
                         $payment2->__set('id', null);
                         $payment2->__set('amount', $donationAmount);
                         $payment2->__set('erp_context_id', 'DONATOR');
                         $payment2 = Billing_Controller_Payment::getInstance()->create($payment2);
                         $paymentDebitor = $payment2->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
                         $contactId = $paymentDebitor->getForeignId('contact_id');
                         if ($donationData) {
                             $campaignId = $donationData['campaign'];
                         } else {
                             $campaign = Donator_Controller_Campaign::getInstance()->getDefaultCampaign();
                             $campaignId = $campaign->getId();
                         }
                         $usage = 'Spende Adress-Nr: ' . $paymentDebitor->__get('debitor_nr');
                         $date = $payment->__get('payment_date');
                         $donation = Donator_Controller_FundMaster::getInstance()->donateByContactId($contactId, $donationAmount, $campaignId, $date, $usage, $payment2);
                         $paymentO->__set('amount', $pAmount - $donationAmount);
                     }
                 }
                 // in case of overpay
                 if ($paymentO->__get('amount') != 0) {
                     $paymentO = Billing_Controller_Payment::getInstance()->create($paymentO);
                     Billing_Controller_OpenItem::getInstance()->payOpenItem($openItem->getId(), $paymentO, abs((double) $openItem->__get('open_sum')));
                 }
             } else {
                 // can be donation or prepay of member fee
                 if ($payment->__get('is_return_debit')) {
                     $paymentO = Billing_Controller_Payment::getInstance()->create($paymentO);
                     // prepay member fee
                 } elseif ($payment->__get('overpay') == 'PREPAYMEMBERFEE') {
                     // do nothing else, payment is stored with context membership
                     // so balance is positive
                     $paymentO->__set('erp_context_id', 'MEMBERSHIP');
                     $paymentO = Billing_Controller_Payment::getInstance()->create($paymentO);
                 } else {
                     // donation
                     $paymentO->__set('erp_context_id', 'DONATOR');
                     //$paymentO = Billing_Controller_Payment::getInstance()->create($paymentO);
                     $donationData = $payment->getAdditionalItem('donation');
                     $donationAmount = abs((double) $payment->__get('payment_amount'));
                     $payment2 = clone $paymentO;
                     $payment2->__set('id', null);
                     $payment2->__set('amount', $donationAmount);
                     $payment2->__set('erp_context_id', 'DONATOR');
                     $payment2 = Billing_Controller_Payment::getInstance()->create($payment2);
                     $paymentDebitor = $payment2->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
                     $contactId = $paymentDebitor->getForeignId('contact_id');
                     if ($donationData) {
                         $campaignId = $donationData['campaign'];
                     } else {
                         $campaign = Donator_Controller_Campaign::getInstance()->getDefaultCampaign();
                         $campaignId = $campaign->getId();
                     }
                     $usage = 'Spende Adress-Nr: ' . $paymentDebitor->__get('debitor_nr');
                     $date = $payment->__get('payment_date');
                     $donation = Donator_Controller_FundMaster::getInstance()->donateByContactId($contactId, $donationAmount, $campaignId, $date, $usage, $payment2);
                 }
             }
         }
     }
 }
Example #16
0
 public function getDebitor()
 {
     return $this->getForeignRecord('debitor_id', Billing_Controller_Debitor::getInstance());
 }
Example #17
0
 protected function appendDependentRecords($record)
 {
     if ($record->__get('debitor_id')) {
         $this->appendForeignRecordToRecord($record, 'debitor_id', 'debitor_id', 'id', new Billing_Backend_Debitor());
         $debitor = $record->__get('debitor_id');
         try {
             if (is_object($debitor)) {
                 $contactId = $debitor->__get('contact_id');
             } else {
                 $contactId = $debitor->contact_id;
             }
             $contact = Addressbook_Controller_Contact::getInstance()->get($contactId);
             if (is_object($debitor)) {
                 $debitor->__set('contact_id', $contact->toArray());
             } else {
                 $debitor->contact_id = $contact->toArray();
             }
         } catch (Exception $e) {
         }
         $record->__set('debitor_id', $debitor);
     }
     if ($record->__get('order_id')) {
         $this->appendForeignRecordToRecord($record, 'order_id', 'order_id', 'id', new Billing_Backend_Order());
         $order = $record->__get('order_id');
         try {
             if ($order instanceof Billing_Model_Order) {
                 $debitorId = $order->__get('debitor_id');
             } else {
                 $debitorId = $order->debitor_id;
             }
             $debitor = Billing_Controller_Debitor::getInstance()->get($debitorId);
             if ($order instanceof Billing_Model_Order) {
                 $order->__set('debitor_id', $debitor->toArray());
             } else {
                 $order->debitor_id = $debitor->toArray();
             }
         } catch (Exception $e) {
         }
         $record->__set('order_id', $order);
     }
     if ($record->__get('receipt_id')) {
         $this->appendForeignRecordToRecord($record, 'receipt_id', 'receipt_id', 'id', new Billing_Backend_Receipt());
         $receipt = $record->getForeignRecordBreakNull('receipt_id', Billing_Controller_Receipt::getInstance());
         if ($receipt) {
             try {
                 if ($receipt instanceof Billing_Model_Order) {
                     $orderId = $receipt->__get('order_id');
                 } else {
                     $orderId = $receipt->order_id;
                 }
                 $order = Billing_Controller_Order::getInstance()->get($orderId);
                 if ($order instanceof Billing_Model_Order) {
                     $receipt->__set('order_id', $order->toArray());
                 } else {
                     $receipt->order_id = $order->toArray();
                 }
             } catch (Exception $e) {
             }
             $record->__set('receipt_id', $receipt);
         }
     }
     if ($record->__get('account_system_id')) {
         $this->appendForeignRecordToRecord($record, 'account_system_id', 'account_system_id', 'id', new Billing_Backend_AccountSystem());
     }
     if ($record->__get('account_system_id_haben')) {
         $this->appendForeignRecordToRecord($record, 'account_system_id_haben', 'account_system_id_haben', 'id', new Billing_Backend_AccountSystem());
     }
     if ($record->__get('booking_id')) {
         $this->appendForeignRecordToRecord($record, 'booking_id', 'booking_id', 'id', new Billing_Backend_Booking());
     }
     if ($record->__get('account_booking_id')) {
         $this->appendForeignRecordToRecord($record, 'account_booking_id', 'account_booking_id', 'id', new Billing_Backend_AccountBooking());
     }
     if ($record->__get('payment_method_id')) {
         $this->appendForeignRecordToRecord($record, 'payment_method_id', 'payment_method_id', 'id', new Billing_Backend_PaymentMethod());
     }
     if ($record->__get('open_item_id')) {
         $this->appendForeignRecordToRecord($record, 'open_item_id', 'open_item_id', 'id', new Billing_Backend_OpenItem());
     }
     if ($record->__get('return_debit_base_payment_id')) {
         $this->appendForeignRecordToRecord($record, 'return_debit_base_payment_id', 'return_debit_base_payment_id', 'id', new Billing_Backend_Payment());
     }
     /*if($record->__get('batch_job_dta_id')){
     		$this->appendForeignRecordToRecord($record, 'batch_job_dta_id', 'batch_job_dta_id', 'id', new Billing_Backend_BatchJobDta());
         } */
 }