Example #1
0
 /**
 	Generate an Invoice from this WorkOrder
 	@param $iv Invoice to Add to
 	@return Invoice
 */
 function toInvoice($iv = null)
 {
     // Add Invoice Items
     $w = null;
     switch ($this['kind']) {
         case 'Monthly':
         case 'Quarterly':
         case 'Yearly':
             $w = array('woi.kind = ? ' => array('Subscription'), 'woi.status = ?' => array('Active'));
             break;
         default:
             $w = array('woi.status in (?)' => array('Active', 'Complete'));
             break;
     }
     $woi_list = $this->getWorkOrderItems($w);
     if (empty($woi_list) || !is_array($woi_list)) {
         throw new Exception('No WorkOrder Items to Generate Invoice');
     }
     // Add to Existing Invoice or Create a New one
     if (!empty($iv)) {
         if ($iv instanceof Invoice) {
             // All Good
         } elseif (is_numeric($iv)) {
             $iv = new Invoice($iv);
         }
     } else {
         $iv = new Invoice();
         $iv['auth_user_id'] = $this['auth_user_id'];
         $iv['contact_id'] = $this['contact_id'];
         $iv['note'] = $this['note'];
         $iv->save();
     }
     // Add Items
     $ivi_c = 0;
     foreach ($woi_list as $woi) {
         $ivi = new InvoiceItem();
         // array();
         $ivi['workorder_item_id'] = $woi['id'];
         $ivi['kind'] = $woi['kind'];
         $ivi['quantity'] = $woi['a_quantity'];
         $ivi['rate'] = $woi['a_rate'];
         $ivi['unit'] = $woi['a_unit'];
         $ivi['tax_rate'] = $woi['a_tax_rate'];
         $ivi['name'] = $woi['name'];
         $ivi['note'] = $woi['note'];
         $iv->addInvoiceItem($ivi);
         $ivi_c++;
         // If Complete then Mark as Billed
         // @todo needs to come from a workflow type list
         // @todo Handle WorkOrder Kind/Status too
         if ($woi['status'] == 'Complete') {
             $woi['status'] = 'Billed';
             $woi->save();
         }
     }
     $iv->save();
     // Close Single Job Work Orders
     if ($this['kind'] == 'Single') {
         $this['status'] = 'Closed';
         // Base_Diff::note($this,'Closed & converted to Invoice');
     }
     $this->save();
     // Add History
     $msg = sprintf('Invoice #%d created from Work Order #%d with %d items', $iv['id'], $this['id'], $ivi_c);
     // Base_Diff::note($this,$msg);
     // Base_Diff::note($iv,$msg);
     // $this->_d->commit();
     return $iv;
 }