/**
  * set each billable of this accountable billed
  *
  * @param Sales_Model_Invoice $invoice
  */
 public function clearBillables(Sales_Model_Invoice $invoice)
 {
     $tsController = Timetracker_Controller_Timesheet::getInstance();
     $this->_disableTimesheetChecks($tsController);
     $filter = new Timetracker_Model_TimesheetFilter(array(), 'AND');
     $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'is_cleared', 'operator' => 'equals', 'value' => 0)));
     $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'timeaccount_id', 'operator' => 'equals', 'value' => $this->getId())));
     $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $invoice->getId())));
     // if this timeaccount has a budget, close and bill this and set cleared at date
     if (intval($this->budget) > 0) {
         $this->is_open = 0;
         $this->status = 'billed';
         $this->cleared_at = Tinebase_DateTime::now();
         Timetracker_Controller_Timeaccount::getInstance()->update($this);
         // also clear all timesheets belonging to this invoice and timeaccount
         $tsController->updateMultiple($filter, array('is_cleared' => 1));
     } else {
         // otherwise clear all timesheets of this invoice
         $tsController->updateMultiple($filter, array('is_cleared' => 1));
     }
     $this->_enableTimesheetChecks($tsController);
 }
 /**
  * create auto invoices for one contract
  * 
  * @param Sales_Model_Contract $contract
  * @param Tinebase_DateTime $currentDate
  * @param boolean $merge
  */
 protected function _createAutoInvoicesForContract(Sales_Model_Contract $contract, Tinebase_DateTime $currentDate, $merge = false)
 {
     // set this current billing date (user timezone)
     $this->_currentBillingDate = clone $currentDate;
     $this->_currentBillingDate->setDate($this->_currentBillingDate->format('Y'), $this->_currentBillingDate->format('m'), 1);
     $this->_currentBillingDate->setTime(0, 0, 0);
     // check all prerequisites needed for billing of the contract
     if (!$this->_validateContract($contract)) {
         return false;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Processing contract "' . $this->_currentBillingContract->number . '"');
     }
     // fire event to allow other applications do some work before billing
     $this->_firePrebillEvent();
     // find product aggregates of the current contract
     $productAggregates = $this->_findProductAggregates();
     // find month that needs to be billed next (note: _currentMonthToBill is the 01-01 00:00:00 of the next month, its the border, like last_autobill)
     $this->_currentMonthToBill = null;
     foreach ($productAggregates as $productAggregate) {
         if (null != $productAggregate->last_autobill) {
             $tmp = clone $productAggregate->last_autobill;
             $tmp->setDate($tmp->format('Y'), $tmp->format('m'), 1);
             $tmp->setTime(0, 0, 0);
             if (null == $this->_currentMonthToBill || $tmp->isLater($this->_currentMonthToBill)) {
                 $this->_currentMonthToBill = $tmp;
             }
         }
     }
     // this contract has no productAggregates, maybe just time accounts? use last invoice to find already billed month
     if (null == $this->_currentMonthToBill) {
         // find newest invoice of contract (probably can be done more efficient!)
         $invoiceRelations = Tinebase_Relations::getInstance()->getRelations('Sales_Model_Contract', 'Sql', $contract->getId(), NULL, array(), TRUE, array('Sales_Model_Invoice'));
         // do not modify $newestInvoiceTime!!!! it does NOT get cloned!
         $newestInvoiceTime = null;
         $newestInvoice = null;
         foreach ($invoiceRelations as $invoiceRelation) {
             $invoiceRelation->related_record->setTimezone(Tinebase_Core::getUserTimezone());
             if (null == $newestInvoiceTime || $invoiceRelation->related_record->creation_time->isLater($newestInvoiceTime)) {
                 $newestInvoiceTime = $invoiceRelation->related_record->creation_time;
                 $newestInvoice = $invoiceRelation->related_record;
             }
         }
         if (null != $newestInvoice) {
             // we can only take the end_date because there are no product aggregates (that have a last_autobill set) in this contract, otherwise it might be one interval ahead!
             $this->_currentMonthToBill = clone $newestInvoice->end_date;
             $this->_currentMonthToBill->addDay(4);
             $this->_currentMonthToBill->subMonth(1);
             //$this->_currentMonthToBill->setTimezone(Tinebase_Core::getUserTimezone());
         }
     }
     $_addMonth = true;
     if (null == $this->_currentMonthToBill) {
         $this->_currentMonthToBill = clone $contract->start_date;
         $_addMonth = false;
     }
     $this->_currentMonthToBill->setTimezone(Tinebase_Core::getUserTimezone());
     $this->_currentMonthToBill->setDate($this->_currentMonthToBill->format('Y'), $this->_currentMonthToBill->format('m'), 1);
     $this->_currentMonthToBill->setTime(0, 0, 0);
     if ($_addMonth) {
         $this->_currentMonthToBill->addMonth(1);
     }
     $doSleep = false;
     if (($merge || $contract->merge_invoices) && $this->_currentMonthToBill->isEarlier($this->_currentBillingDate)) {
         $this->_currentMonthToBill = clone $this->_currentBillingDate;
     }
     while ($this->_currentMonthToBill->isEarlierOrEquals($this->_currentBillingDate)) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' $this->_currentMonthToBill: ' . $this->_currentMonthToBill . ' $this->_currentBillingDate ' . $this->_currentBillingDate);
             foreach ($productAggregates as $productAggregate) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $productAggregate->id . ' ' . $productAggregate->last_autobill . ' ' . $productAggregate->interval);
             }
         }
         //required to have one sec difference in the invoice creation_time, can be optimized to look for milliseconds
         if ($doSleep) {
             sleep(1);
             $doSleep = false;
         }
         // prepare relations and find all billable accountables of the current contract
         list($relations, $billableAccountables) = $this->_prepareInvoiceRelationsAndFindBillableAccountables($productAggregates);
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' count $billableAccountables: ' . count($billableAccountables));
             foreach ($billableAccountables as $ba) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' accountable: ' . get_class($ba['ac']) . ' id: ' . $ba['ac']->getId());
             }
         }
         // find invoice positions and the first start date and last end date of all billables
         list($invoicePositions, $earliestStartDate, $latestEndDate) = $this->_findInvoicePositionsAndInvoiceInterval($billableAccountables);
         /**** TODO ****/
         // if there are no positions, no more bills need to be created,
         // but the last_autobill info is set, if the current date is later
         if ($invoicePositions->count() > 0) {
             // prepare invoice
             $invoice = new Sales_Model_Invoice(array('is_auto' => TRUE, 'description' => $this->_currentBillingContract->title . ' (' . $this->_currentMonthToBill->toString() . ')', 'type' => 'INVOICE', 'address_id' => $this->_currentBillingContract->billing_address_id, 'credit_term' => $this->_currentBillingCustomer['credit_term'], 'customer_id' => $this->_currentBillingCustomer['id'], 'costcenter_id' => $this->_currentBillingCostCenter->getId(), 'start_date' => $earliestStartDate, 'end_date' => $latestEndDate, 'positions' => $invoicePositions->toArray(), 'date' => clone $this->_currentMonthToBill, 'sales_tax' => 19));
             $invoice->relations = $relations;
             $invoice->setTimezone('UTC', TRUE);
             // create invoice
             $invoice = $this->create($invoice);
             $this->_autoInvoiceIterationResults[] = $invoice->getId();
             $this->_autoInvoiceIterationDetailResults[] = $invoice;
             $paToUpdate = array();
             // conjunct billables with invoice, find out which productaggregates to update
             foreach ($billableAccountables as $ba) {
                 $ba['ac']->conjunctInvoiceWithBillables($invoice);
                 if ($ba['pa']->getId()) {
                     $paToUpdate[$ba['pa']->getId()] = $ba['pa'];
                 }
             }
             foreach ($paToUpdate as $paId => $productAggregate) {
                 $firstBill = !$productAggregate->last_autobill;
                 $lab = $productAggregate->last_autobill ? clone $productAggregate->last_autobill : ($productAggregate->start_date ? clone $productAggregate->start_date : clone $this->_currentBillingContract->start_date);
                 $lab->setTimezone(Tinebase_Core::getUserTimezone());
                 $lab->setDate($lab->format('Y'), $lab->format('m'), 1);
                 $lab->setTime(0, 0, 0);
                 if (!$firstBill) {
                     $lab->addMonth($productAggregate->interval);
                 } else {
                     if ($productAggregate->billing_point == 'end') {
                         // if first bill, add interval on billing_point end
                         $lab->addMonth($productAggregate->interval);
                     }
                 }
                 while ($this->_currentMonthToBill->isLater($lab)) {
                     $lab->addMonth($productAggregate->interval);
                 }
                 if ($lab->isLater($this->_currentMonthToBill)) {
                     $lab->subMonth($productAggregate->interval);
                 }
                 $productAggregate->last_autobill = $lab;
                 $productAggregate->setTimezone('UTC');
                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Updating last_autobill of "' . $productAggregate->getId() . '": ' . $lab->__toString());
                 }
                 Sales_Controller_ProductAggregate::getInstance()->update($productAggregate);
                 $productAggregate->setTimezone(Tinebase_Core::getUserTimezone());
             }
             $doSleep = true;
         } elseif (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' $invoicePositions->count() == false');
         }
         $this->_currentMonthToBill->addMonth(1);
     }
 }
 /**
  * returns true if this invoice needs to be recreated because data changed
  *
  * @param Tinebase_DateTime $date
  * @param Sales_Model_ProductAggregate $productAggregate
  * @param Sales_Model_Invoice $invoice
  * @param Sales_Model_Contract $contract
  * @return boolean
  */
 public function needsInvoiceRecreation(Tinebase_DateTime $date, Sales_Model_ProductAggregate $productAggregate, Sales_Model_Invoice $invoice, Sales_Model_Contract $contract)
 {
     $filter = new Timetracker_Model_TimesheetFilter(array(), 'AND');
     $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $invoice->getId())));
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' TS Filter: ' . print_r($filter->toArray(), true));
     }
     $timesheets = Timetracker_Controller_Timesheet::getInstance()->search($filter);
     $timesheets->setTimezone(Tinebase_Core::getUserTimezone());
     foreach ($timesheets as $timesheet) {
         if ($timesheet->last_modified_time && $timesheet->last_modified_time->isLater($invoice->creation_time)) {
             return true;
         }
     }
     return false;
 }