Ejemplo n.º 1
0
 /**
  * appends sql to given select statement
  *
  * @param Zend_Db_Select                $_select
  * @param Tinebase_Backend_Sql_Abstract $_backend
  */
 public function appendFilterSql($_select, $_backend)
 {
     $filterData = array('field' => $this->_field, 'operator' => $this->_operator, 'value' => array($this->_value));
     //print_r($filterData);
     $oFilter = new Billing_Model_OrderFilter(array(), 'AND');
     $oFilter->addFilter($oFilter->createFilter($this->_field, $this->_operator, $this->_value));
     /*Filter = $oFilter->toArray();
      	print_r($aFilter);
      	*/
     $orderIds = Billing_Controller_Order::getInstance()->search($oFilter, null, false, true);
     //print_r($orderIds);
     $filter = new Billing_Model_ReceiptFilter(array(), 'AND');
     if (count($orderIds) > 0) {
         $filter->addFilter(new Tinebase_Model_Filter_Id('order_id', 'in', $orderIds));
     } else {
         $filter->addFilter(new Tinebase_Model_Filter_Id('order_id', 'in', array(0 => null)));
     }
     $receiptIds = Billing_Controller_Receipt::getInstance()->search($filter, null, false, true);
     if (count($receiptIds) > 0) {
         $filter1 = new Billing_Model_ArticleSoldFilter(array(), 'AND');
         $filter1->addFilter(new Tinebase_Model_Filter_Id('receipt_id', 'in', $receiptIds));
         Tinebase_Backend_Sql_Filter_FilterGroup::appendFilters($_select, $filter1, $_backend);
     } else {
         $filter1 = new Billing_Model_ArticleSoldFilter(array(), 'AND');
         $filter1->addFilter(new Tinebase_Model_Filter_Id('receipt_id', 'in', array(0 => null)));
         Tinebase_Backend_Sql_Filter_FilterGroup::appendFilters($_select, $filter1, $_backend);
     }
     //	echo $_select->assemble();
 }
Ejemplo n.º 2
0
 /**
  * the constructor
  *
  * don't use the constructor. use the singleton
  */
 private function __construct()
 {
     $this->_applicationName = 'Billing';
     $this->_receiptController = Billing_Controller_Receipt::getInstance();
     $this->_supplyReceiptController = Billing_Controller_SupplyReceipt::getInstance();
     $this->_currentAccount = Tinebase_Core::getUser();
     $this->_doContainerACLChecks = FALSE;
 }
 /**
  * appends sql to given select statement
  *
  * @param Zend_Db_Select                $_select
  * @param Tinebase_Backend_Sql_Abstract $_backend
  */
 public function appendFilterSql($_select, $_backend)
 {
     $filterData = array(array('field' => 'combi_type', 'operator' => $this->_operator, 'value' => $this->_value));
     $filter = new Billing_Model_ReceiptFilter($filterData, 'AND');
     $receiptIds = Billing_Controller_Receipt::getInstance()->search($filter, null, false, true);
     if (count($receiptIds) > 0) {
         $filter1 = new Billing_Model_ArticleSoldFilter(array(), 'AND');
         $filter1->addFilter(new Tinebase_Model_Filter_Id('receipt_id', 'in', $receiptIds));
         Tinebase_Backend_Sql_Filter_FilterGroup::appendFilters($_select, $filter1, $_backend);
     } else {
         $filter1 = new Billing_Model_ArticleSoldFilter(array(), 'AND');
         $filter1->addFilter(new Tinebase_Model_Filter_Id('receipt_id', 'in', array(0 => null)));
         Tinebase_Backend_Sql_Filter_FilterGroup::appendFilters($_select, $filter1, $_backend);
     }
     //	echo $_select->assemble();
 }
Ejemplo n.º 4
0
 /**
  * (non-PHPdoc)
  * @see Tinebase_Controller_Record_Abstract::update()
  */
 public function update(Tinebase_Record_Interface $_record)
 {
     parent::update($_record);
     // after update
     if ($this->mustUpdateReceiptAtOnce()) {
         try {
             $receiptPosition = Billing_Controller_ReceiptPosition::getInstance()->getByOrderPositionId($_record->getId());
             $receipt = $receiptPosition->getForeignRecordBreakNull('receipt_id', Billing_Controller_Receipt::getInstance());
             if ($receipt) {
                 Billing_Controller_ReceiptPosition::getInstance()->updateReceipt($receipt);
             }
         } catch (Tinebase_Exception_NotFound $e) {
             // no receipt to be updated
         }
     }
     return $this->get($_record->getId());
 }
Ejemplo n.º 5
0
 public function bookBillableReceipt($receipt, $renew = false)
 {
     $receipt = Billing_Controller_Receipt::getInstance()->get($receipt->getId());
     $booking = new Billing_Model_Booking(null, true);
     $booking->__set('booking_date', $receipt->getBillableReceiptDate());
     $booking->__set('booking_text', $receipt->getBookingText());
     $booking->__set('erp_context_id', $receipt->__get('erp_context_id'));
     $booking->__set('booking_receipt_nr', $receipt->getBookingReceiptNumber());
     $booking->__set('receipt_unique_nr', $receipt->getBookingReceiptNumber());
     $booking->__set('receipt_id', $receipt->getId());
     $booking->__set('is_cancelled', $receipt->__get('is_cancelled'));
     $booking->__set('is_cancellation', $receipt->__get('is_cancellation'));
     $value = abs($receipt->__get('total_brutto'));
     $fordKto = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::FIBU_KTO_DEBITOR);
     $bookingData = $receipt->getBookingData($fordKto);
     if ($receipt->isDonation()) {
         $booking->__set('donation_id', $receipt->getForeignId('donation_id'));
     }
     $booking = Billing_Controller_Booking::getInstance()->create($booking);
     Billing_Controller_AccountBooking::getInstance()->multiCreateAccountBookings($booking->getId(), $bookingData);
     return $booking;
 }
Ejemplo n.º 6
0
 public function saveReceiptPosition($recordData)
 {
     $receiptId = null;
     if (array_key_exists('receipt_id', $recordData)) {
         if ($recordData['receipt_id']) {
             $receiptId = $recordData['receipt_id'];
         }
     }
     $orderPosition = $this->_save($recordData, Billing_Controller_OrderPosition::getInstance(), 'OrderPosition');
     if ($orderPosition instanceof Tinebase_Model_OrderPosition) {
         $orderPosId = $orderPosition->getId();
     } else {
         $orderPosId = $orderPosition['id'];
     }
     $orderPosition = Billing_Controller_OrderPosition::getInstance()->get($orderPosId);
     if ($receiptId) {
         // -> activate immediate update of receipt!
         // in order to have correct total sums
         Billing_Controller_ReceiptPosition::getInstance()->setUpdateReceiptAtOnce(true);
         $receipt = Billing_Controller_Receipt::getInstance()->get($receiptId);
         Billing_Controller_ReceiptPosition::getInstance()->addOrderPositions($receipt, array($orderPosition));
     }
     return $orderPosition;
 }
Ejemplo n.º 7
0
 public function runMonitionExport($jobId, $dueDate)
 {
     set_time_limit(0);
     error_reporting(E_ALL);
     $job = Billing_Api_BatchJobManager::getInstance()->loadBatchJob($jobId);
     Billing_Api_BatchJobManager::getInstance()->startBatchJob();
     try {
         $db = Tinebase_Core::getDb();
         $tm = Tinebase_TransactionManager::getInstance();
         $tId = $tm->startTransaction($db);
         set_time_limit(0);
         $data = $job->getData();
         $filters = $data['filters'];
         $pagination = new Tinebase_Model_Pagination();
         $contexts = array('MEMBERSHIP' => 'Beitrag', 'DONATOR' => 'Spende', 'ERP' => 'allg.');
         // get all open items (for debit)
         // grouped by debitors
         $filters[] = array('field' => 'job_id', 'operator' => 'equals', 'value' => $job->getId());
         $filter = new Billing_Model_BatchJobMonitionFilter($filters, 'AND');
         // count membership matching filters
         $batchJobMonitionIds = $this->search($filter, new Tinebase_Model_Pagination(array('sort' => 'n_family', 'dir' => 'ASC')), false, true);
         $tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         $hash = md5(microtime());
         $protocolBatchJobMonitionIds = array();
         $bufferMonitionIds = array();
         foreach ($batchJobMonitionIds as $batchJobMonitionId) {
             $batchJobMonition = $this->get($batchJobMonitionId);
             // keep out items which are locked
             if ($batchJobMonition->__get('monition_lock')) {
                 continue;
             }
             $usage = array();
             $contactNr = $batchJobMonition->getForeignId('contact_id');
             $batchJobMonitionItems = Billing_Controller_BatchJobMonitionItem::getInstance()->getByBatchJobMonitionId($batchJobMonitionId);
             // get last open item (grab last order, for relating monition to)
             $lastOpenItem = Billing_Controller_BatchJobMonitionItem::getInstance()->getLastOpenItem($batchJobMonitionItems);
             $orderId = $lastOpenItem->getForeignId('order_id');
             $lastReceipt = $lastOpenItem->getReceipt();
             $monition = Billing_Model_Receipt::createMonition();
             $monition->__set('order_id', $orderId);
             $lastReceipt->copyAdditionalDataTo($monition);
             $monition = Billing_Controller_Receipt::getInstance()->create($monition);
             $bufferMonitionIds[] = $monition->getId();
             $overallMonitionStage = 0;
             foreach ($batchJobMonitionItems as $batchJobMonitionItem) {
                 $openItem = $batchJobMonitionItem->getForeignRecord('open_item_id', Billing_Controller_OpenItem::getInstance());
                 $openItem->manifestNextMonitionStage();
                 $monitionStage = $openItem->__get('monition_stage');
                 $overallMonitionStage = max($overallMonitionStage, $monitionStage);
                 $openItemMonition = Billing_Model_OpenItemMonition::createFromBatchJobMonitionItem($monition, $batchJobMonitionItem);
                 $openItemMonition = Billing_Controller_OpenItemMonition::getInstance()->create($openItemMonition);
                 Billing_Controller_OpenItem::getInstance()->update($openItem);
             }
             $monition->__set('monition_level', $overallMonitionStage);
             if (Billing_Custom_Template::isToPrint($monition, Billing_Controller_Print::TYPE_MONITION, $templateId)) {
                 $monition->__set('template_id', $templateId);
             }
             Billing_Controller_Receipt::getInstance()->update($monition);
             $batchJobMonition->__set('action_state', 'DONE');
             $batchJobMonition->__set('process_datetime', Zend_Date::now());
             $batchJobMonition->__set('processed_by_user', Tinebase_Core::get(Tinebase_Core::USER)->getId());
             $this->update($batchJobMonition);
             $protocolBatchJobMonitionIds[] = $batchJobMonitionId;
         }
         $printController = Billing_Controller_Print::getInstance();
         $printController->printReceipts($bufferMonitionIds, false, null, false, false, false);
         $storage = $printController->getPrintJobStorage();
         $tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         $filename = $tempFilePath . md5(microtime()) . '.pdf';
         $storage->copyOut("//out/result/merge/pdf/final", $filename);
         $storage->close();
         Billing_Api_BatchJobManager::getInstance()->jobAddData('MONITION', $filename);
         Billing_Api_BatchJobManager::getInstance()->jobAddData('MonitionDownloadFilename', 'Monition-' . $job->__get('job_nr') . '.pdf');
         $tm->commitTransaction($tId);
         //Billing_Api_BatchJobManager::getInstance()->finish();
         $this->printMonitionExportPrepare($jobId, false, null, true, $protocolBatchJobMonitionIds);
         return array('state' => 'success', 'result' => null);
         //        $outputFileName = $tempFilePath . md5(serialize($job).'preparePDF'.microtime()).'.pdf';
     } 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()));
     }
 }
Ejemplo n.º 8
0
 public function updateReceipt($receipt)
 {
     $aCalc = $this->getCalculationByReceiptId($receipt->getId());
     $receipt->__set('total_netto', $aCalc['total_netto']);
     $receipt->__set('total_brutto', $aCalc['total_brutto']);
     $receipt->__set('total_weight', $aCalc['total_weight']);
     $receipt = Billing_Controller_Receipt::getInstance()->update($receipt);
 }
Ejemplo n.º 9
0
 public function getReceipt()
 {
     return $this->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
 }
Ejemplo n.º 10
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());
         } */
 }
Ejemplo n.º 11
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();
     }
 }
Ejemplo n.º 12
0
 public function getPositions()
 {
     if (!$this->isMonition()) {
         return Billing_Controller_Receipt::getInstance()->getOrderPositions($this->getId());
     } else {
         return Billing_Controller_OpenItemMonition::getInstance()->getByReceiptId($this->getId());
     }
 }
Ejemplo n.º 13
0
 public function onBillableReceiptBooked($receipt, $openItem, $booking)
 {
     if ($receipt->isCredit() || $receipt->isInvoice()) {
         // suchen und neu oder update -> debitor account
         $receipt = Billing_Controller_Receipt::getInstance()->get($receipt->getId());
         $totalBrutto = $receipt->__get('total_brutto');
         try {
             $debitorAccount = Billing_Controller_DebitorAccount::getInstance()->getByReceiptId($receipt->getId());
             if (!$debitorAccount) {
                 throw new Exception('');
             }
             $debitorAccount->__set('s_brutto', $totalBrutto);
             Billing_Controller_DebitorAccount::getInstance()->update($debitorAccount);
         } catch (Exception $e) {
             $debitorAccount = Billing_Controller_DebitorAccount::getInstance()->getEmptyDebitorAccount();
             $order = $receipt->getForeignRecord('order_id', Billing_Controller_Order::getInstance());
             $debitorAccount->__set('receipt_id', $receipt->getId());
             $debitorAccount->__set('debitor_id', $order->getForeignId('debitor_id'));
             $debitorAccount->__set('erp_context_id', $receipt->__get('erp_context_id'));
             $debitorAccount->__set('usage', $receipt->__get('usage'));
             $debitorAccount->__set('booking_id', $booking->getId());
             //$debitorAccount->__set('open_item_id', $openItem->getId());
             $debitorAccount->__set('is_cancelled', $receipt->__get('is_cancelled'));
             $debitorAccount->__set('is_cancellation', $receipt->__get('is_cancellation'));
             if ($receipt->isInvoice()) {
                 $debitorAccount->__set('item_type', 'DEBIT');
                 $debitorAccount->__set('create_date', new Zend_Date($receipt->__get('invoice_date')));
                 $debitorAccount->__set('value_date', new Zend_Date($receipt->__get('invoice_date')));
                 $debitorAccount->__set('s_brutto', $totalBrutto);
             }
             if ($receipt->isCredit()) {
                 $debitorAccount->__set('item_type', 'CREDIT');
                 $debitorAccount->__set('create_date', new Zend_Date($receipt->__get('credit_date')));
                 $debitorAccount->__set('value_date', new Zend_Date($receipt->__get('credit_date')));
                 $debitorAccount->__set('h_brutto', $totalBrutto * -1);
             }
             $this->create($debitorAccount);
         }
     }
 }
Ejemplo n.º 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()));
     }
 }
Ejemplo n.º 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);
 }
Ejemplo n.º 16
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;
 }
Ejemplo n.º 17
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, ',', '.') : '');
     }
 }
Ejemplo n.º 18
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);
     }
 }