public function getLastOpenItem(Tinebase_Record_RecordSet $batchJobMonitionItems)
 {
     if ($batchJobMonitionItems->getCount() == 0) {
         throw new Billing_Exception_OpenItem('Recordset does not contain any monition open items and therefore no related order.');
     }
     $batchJobMonitionItems->sort('open_item_id', 'DESC');
     $record = $batchJobMonitionItems->getFirstRecord();
     $openItem = $record->getForeignRecord('open_item_id', Billing_Controller_OpenItem::getInstance());
     return $openItem;
 }
Example #2
0
 public function pay($payment)
 {
     $totalBrutto = $this->__get('open_sum');
     if ($payment->__get('amount') == $totalBrutto) {
         $this->__set('payment_state', 'PAYED');
         $this->__set('open_sum', 0);
         $this->__set('payed_sum', $totalBrutto);
     } elseif ($payment->__get('amount') == 0) {
         $this->__set('payment_state', 'TOBEPAYED');
     } elseif ($payment->__get('amount') < $totalBrutto) {
         $this->__set('payment_state', 'PARTLYPAYED');
         $this->__set('open_sum', $totalBrutto - $payment->__get('amount'));
         $this->__set('payed_sum', $payment->__get('amount'));
     }
     Billing_Controller_OpenItem::getInstance()->update($this);
     Tinebase_Event::fireEvent(new Billing_Events_OpenItemPayed($payment, $this));
 }
 public static function createFromBatchJobMonitionItem(Billing_Model_Receipt $monitionReceipt, Billing_Model_BatchJobMonitionItem $batchJobMonitionItem)
 {
     $fromRecord = clone $batchJobMonitionItem;
     $fromRecord->flatten();
     $openItem = $fromRecord->getForeignRecord('open_item_id', Billing_Controller_OpenItem::getInstance());
     $obj = new self();
     $obj->__set('erp_context_id', $fromRecord->__get('erp_context_id'));
     $obj->__set('monition_receipt_id', $monitionReceipt->getId());
     $obj->__set('open_item_id', $openItem->getId());
     $obj->__set('debitor_id', $openItem->getForeignId('debitor_id'));
     $obj->__set('due_date', $openItem->__get('due_date'));
     $obj->__set('monition_date', new Zend_Date());
     $obj->__set('open_sum', $fromRecord->__get('open_sum'));
     $obj->__set('total_sum', $fromRecord->__get('total_sum'));
     $obj->__set('due_days', $fromRecord->__get('due_days'));
     $obj->__set('monition_stage', $fromRecord->__get('monition_stage'));
     return $obj;
 }
Example #4
0
 public function directDebit($aPaymentMethodKeys, $filters)
 {
     error_reporting(E_ALL);
     ini_set('display_errors', 'on');
     Billing_Controller_OpenItem::getInstance()->directDebit($aPaymentMethodKeys, $filters);
 }
Example #5
0
 /**
  * 
  * Get data objects from given array of objects
  * 
  * @param array $dataObjects
  * @param Addressbook_Model_Contact $contact
  * @param Billing_Model_Receipt 	$receipt
  * @param Billing_Model_Job 		$job
  * @param Billing_Model_Order 		$order
  * @param Billing_Model_Debitor 	$debitor
  * @param Billing_Model_Creditor 	$creditor
  * @param array $sums
  * @param array $aPositions
  * @param array $sumTable
  */
 protected static function getDataObjects($dataObjects, &$contact, &$receipt, &$job, &$order, &$debitor, &$creditor, &$sums, &$aPositions, &$sumTable, &$sumData, &$addData)
 {
     $contact = $dataObjects['contact'];
     $receipt = $dataObjects['receipt'];
     $order = $dataObjects['order'];
     $positions = $dataObjects['positions'];
     $sums = $dataObjects['sums'];
     $debitor = null;
     if (array_key_exists('debitor', $dataObjects)) {
         $debitor = $dataObjects['debitor'];
     }
     $creditor = null;
     if (array_key_exists('creditor', $dataObjects)) {
         $creditor = $dataObjects['creditor'];
     }
     $job = $order->__get('job_id');
     $addData = array();
     if (!$receipt->isMonition()) {
         $aPositions = array();
         $posData = array();
         $sum1Netto = 0;
         $sum1Brutto = 0;
         $sum2Netto = 0;
         $sum2Brutto = 0;
         $sumDonation = 0;
         foreach ($positions as $pos) {
             $unitTotalNetto = $pos['price_netto'] + $pos['price2_netto'];
             $unitTotalBrutto = $pos['price_brutto'] + $pos['price2_brutto'];
             $sum1Netto += $pos['total1_netto'];
             $sum1Brutto += $pos['total1_brutto'];
             $sum2Netto += $pos['total2_netto'];
             $sum2Brutto += $pos['total2_brutto'];
             $sumDonation += $pos['donation_amount'];
             $desc = $pos['description'];
             $result = array('nr' => $pos['position_nr'], 'amount' => $pos['amount'], 'unit' => $pos['unit_id']['name'], 'article_nr' => $pos['article_id']['article_nr'], 'article_name' => $pos['name'], 'article_desc' => $pos['description'], 'crlf_article_desc' => '<text:line-break/>' . preg_replace('/$\\R?^/m', '<text:line-break/>', $desc), 'comment' => $pos['comment'], 'crlf' => '<text:line-break/>', 'crlf_comment' => '<text:line-break/>' . str_replace(chr(13) . chr(10), '<text:line-break/>', $pos['comment']), 'unit_price_netto' => number_format($pos['price_netto'], 2, ',', '.'), 'unit_price_brutto' => number_format($pos['price_brutto'], 2, ',', '.'), 'unit_price2_netto' => number_format($pos['price2_netto'], 2, ',', '.'), 'unit_price2_brutto' => number_format($pos['price2_brutto'], 2, ',', '.'), 'unit_total_netto' => number_format($unitTotalNetto, 2, ',', '.'), 'unit_total_brutto' => number_format($unitTotalBrutto, 2, ',', '.'), 'price_netto' => number_format($pos['total_netto'], 2, ',', '.'), 'price_brutto' => number_format($pos['total_brutto'], 2, ',', '.'), 'donation_amount' => number_format($pos['donation_amount'], 2, ',', '.'), 'vat' => $pos['vat_id']['name'], 'price1_netto' => number_format($pos['total1_netto'], 2, ',', '.'), 'price1_brutto' => number_format($pos['total1_brutto'], 2, ',', '.'), 'price2_netto' => number_format($pos['total2_netto'], 2, ',', '.'), 'price2_brutto' => number_format($pos['total2_brutto'], 2, ',', '.'), 'vat2' => $pos['price2_vat_id']['name'], 'discount_percentage' => $pos['discount_percentage'], 'add_perc' => $pos['add_percentage'], 'discount_total' => number_format($pos['discount_total'], 2, ',', '.'));
             $posData['p' . $pos['position_nr'] . '_brutto'] = number_format($pos['total_brutto'], 2, ',', '.');
             $additionalData = Zend_Json::decode($pos['additional_data']);
             if (is_array($additionalData)) {
                 foreach ($additionalData as $key => $value) {
                     $result[$key] = $value;
                 }
             }
             $aPositions[] = $result;
         }
         $sumTable = array('POSITIONS' => array(), 'SUM' => array(), 'POSDATA' => $posData);
         foreach ($sums['vat_sums'] as $sum) {
             $sumTable['POSITIONS'][] = array('vn_vatindex' => number_format($sum['sum']['vatindex'], 1, ',', '.'), 'vn_netto' => number_format($sum['sum']['netto'], 2, ',', '.'), 'vn_vat' => number_format($sum['sum']['vat'], 2, ',', '.'), 'vn_brutto' => number_format($sum['sum']['brutto'], 2, ',', '.'));
         }
         $sumTable['SUM'][] = array('netto1_sum' => number_format($sum1Netto, 2, ',', '.'), 'brutto1_sum' => number_format($sum1Brutto, 2, ',', '.'), 'netto2_sum' => number_format($sum2Netto, 2, ',', '.'), 'brutto2_sum' => number_format($sum2Brutto, 2, ',', '.'), '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, ',', '.'));
         $sumData = array('netto1_sum' => number_format($sum1Netto, 2, ',', '.'), 'donation_sum' => number_format($sumDonation, 2, ',', '.'), 'brutto1_sum' => number_format($sum1Brutto, 2, ',', '.'), 'netto2_sum' => number_format($sum2Netto, 2, ',', '.'), 'brutto2_sum' => number_format($sum2Brutto, 2, ',', '.'), '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, ',', '.'));
     } elseif ($receipt->isMonition()) {
         $aPositions = array();
         $posData = array();
         $sum = 0;
         $sumExcludingMaxOp = 0;
         $maxOp = null;
         foreach ($positions as $pos) {
             $opId = $pos['open_item_id'];
             $op = Billing_Controller_OpenItem::getInstance()->get($opId);
             $receipt = $op->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
             $additionalData = $receipt->getAdditionalData();
             $usage = $op->__get('usage');
             $opNr = $op->__get('op_nr');
             $sum += (double) $pos['open_sum'];
             $result = array('created_at' => (double) strftime('YmdHMS', $receipt->__get('creation_time')), 'op_nr' => $opNr, 'usage' => $usage, 'open_sum' => $pos['open_sum'], 'open_f' => number_format($pos['open_sum'], 2, ',', '.'), 'monition_stage' => $pos['monition_stage'], 'due_date' => \org\sopen\app\util\format\Date::format($pos['due_date']));
             $result = array_merge($additionalData, $result);
             if (is_null($maxOp) || $result['created_at'] > $maxOp['created_at']) {
                 $maxOp = $result;
             }
             $aPositions[] = $result;
         }
         $sumExcludingMaxOp = $sum - (double) $maxOp['open_sum'];
         $addData = array('lastop' => $maxOp, 'sum' => number_format($sum, 2, ',', '.'), 'sum2' => $sumExcludingMaxOp > 0 ? number_format($sumExcludingMaxOp, 2, ',', '.') : '');
     }
 }
Example #6
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 #7
0
 public function onBillableReceiptCreated($receipt)
 {
     $booking = $this->bookBillableReceipt($receipt);
     $openItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($receipt->getId());
     Tinebase_Event::fireEvent(new Billing_Events_BillableReceiptBooked($receipt, $openItem, $booking));
     return $booking;
 }
Example #8
0
 /**
  * inspect update of one record
  * 
  * @param   Tinebase_Record_Interface $_record      the update record
  * @param   Tinebase_Record_Interface $_oldRecord   the current persistent record
  * @return  void
  */
 protected function _inspectUpdate($_record, $_oldRecord)
 {
     if ($_record->__get('order_id')) {
         $order = $_record->getForeignRecord('order_id', Billing_Controller_Order::getInstance());
         if ($order->__get('payment_state') != $_record->__get('payment_state')) {
             $order->__set('payment_state', $_record->__get('payment_state'));
             Billing_Controller_Order::getInstance()->update($order);
         }
     }
     $openItem = null;
     if ($_record->__get('payment_state') == 'PAYED') {
         try {
             $openItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($_record->getId());
             if ($openItem->__get('state') != 'DONE') {
                 $openItem->__set('state', 'DONE');
                 $openItem->__set('open_sum', 0);
                 $openItem->__set('payed_sum', $_record->__get('total_brutto'));
                 $openItem->__set('payment_method_id', $_record->getForeignId('payment_method_id'));
             }
         } catch (Exception $e) {
             // silent failure, as open item might not exist already
         }
     }
     if ($_record->isCancelled()) {
         if (is_null($openItem)) {
             $openItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($_record->getId());
         }
         $openItem->__set('is_cancelled', true);
         $reversionReceiptId = $_record->getForeignId('reversion_record_id');
         try {
             $reversionOpenItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($reversionReceiptId);
             $openItem->__set('open_sum', $openItem->__get('total_brutto') + $reversionOpenItem->__get('total_brutto'));
             $openItem->__set('payed_sum', -1 * $reversionOpenItem->__get('payed_sum'));
             $openItem->__set('reversion_record_id', $reversionOpenItem->getId());
         } catch (Exception $e) {
             //failure OK: open item for reversion record might not already exist
             // will be set in on of the next update calls, as soon, the open item exists.
         }
     }
     if (!$_record->getForeignIdBreakNull('payment_method_id')) {
         $_record->__set('payment_method_id', 'BANKTRANSFER');
     }
     if ($openItem) {
         if (!$openItem->getForeignIdBreakNull('payment_method_id')) {
             $openItem->__set('payment_method_id', 'BANKTRANSFER');
         }
         Billing_Controller_OpenItem::getInstance()->update($openItem);
     }
 }
Example #9
0
 public function payOpenItems($data, $paymentRecord, $donationData)
 {
     return Billing_Controller_OpenItem::getInstance()->payOpenItems($data, $paymentRecord, $donationData);
 }
 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 #11
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 #12
0
 /**
  * event handler function
  *
  * all events get routed through this function
  *
  * @param Tinebase_Event_Abstract $_eventObject the eventObject
  *
  * @todo    write test
  */
 public function handleEvents(Tinebase_Event_Abstract $_eventObject)
 {
     try {
         if ($_eventObject instanceof Billing_Events_BillableReceiptCreated) {
             // create open item out of invoice or credit
             $db = Tinebase_Core::getDb();
             $tm = Tinebase_TransactionManager::getInstance();
             $tId = $tm->startTransaction($db);
             try {
                 $receipt = Billing_Controller_Receipt::getInstance()->get($_eventObject->receipt->getId());
                 // set payed and open sum
                 Billing_Controller_Receipt::getInstance()->onBillableReceiptCreated($receipt);
                 // create according open item
                 Billing_Controller_OpenItem::getInstance()->onBillableReceiptCreated($receipt);
                 if (Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::FIBU_INSTANT_BOOK_BILLABLE)) {
                     // do fibu booking -> fire event: BillableReceiptBooked
                     Billing_Controller_Booking::getInstance()->onBillableReceiptCreated($receipt);
                 }
                 $tm->commitTransaction($tId);
             } catch (Exception $e) {
                 $tm->rollback($tId);
                 throw $e;
             }
         }
         if ($_eventObject instanceof Billing_Events_PaymentReverted) {
             // TODO: NRW
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentCreated) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_Booking::getInstance()->onPaymentCreated($payment);
                 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);
                 }
                 if ($payment->isReturnDebit()) {
                     Tinebase_Event::fireEvent(new Billing_Events_PaymentDebitReturnCreated($payment));
                 }
             } catch (Exception $e) {
                 echo $e->__toString();
             }
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentDebitReturnCreated) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_OpenItem::getInstance()->onPaymentDebitReturnCreated($payment);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentBooked) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 $booking = $_eventObject->booking;
                 Billing_Controller_DebitorAccount::getInstance()->onPaymentBooked($payment, $booking);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_PaymentDonationDetected) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_DebitorAccount::getInstance()->onPaymentDonationDetected($payment);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_BillableReceiptBooked) {
             try {
                 // TODO: NRW
                 $receipt = Billing_Controller_Receipt::getInstance()->get($_eventObject->receipt->getId());
                 $openItem = $_eventObject->openItem;
                 $booking = $_eventObject->booking;
                 // after booking -> debitor account gets  created
                 Billing_Controller_DebitorAccount::getInstance()->onBillableReceiptBooked($receipt, $openItem, $booking);
                 $receipt->__set('booking_id', $booking->getId());
                 $openItem->__set('booking_id', $booking->getId());
                 Billing_Controller_Receipt::getInstance()->update($receipt);
                 Billing_Controller_OpenItem::getInstance()->update($openItem);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_BillableReceiptReverted) {
             try {
                 // TODO: NRW
                 $receipt = $_eventObject->revertedReceipt;
                 $reversionReceipt = $_eventObject->reversionReceipt;
                 // after booking -> debitor account gets  created
                 Billing_Controller_DebitorAccount::getInstance()->onBillableReceiptReverted($receipt, $reversionReceipt);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn($e->__toString());
         echo $e->__toString();
     }
 }
Example #13
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 #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
 /**
  * 
  * 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);
 }