Updated charge, Invoice improvements and other minor fixes

This commit is contained in:
Deon George
2013-09-06 15:39:56 +10:00
parent 2322a802de
commit ab3735914b
52 changed files with 748 additions and 560 deletions

View File

@@ -12,155 +12,6 @@
class Controller_Task_Invoice extends Controller_Task {
public $auto_render = FALSE;
/**
* Email a customers a reminder of their upcoming invoices that are due.
*/
public function action_remind_due() {
$action = array();
$key = 'remind_due';
$days = ORM::factory('Invoice')->config('REMIND_DUE');
foreach (ORM::factory('Invoice')->list_due(time()+86400*$days) as $io) {
// @todo Use another option to supress reminders
// If we have already sent a reminder, we'll skip to the next one.
if (($io->remind($key) AND (is_null($x=$this->request->param('id')) OR $x != 'again')) OR ($io->account->invoice_delivery != 1))
continue;
// Send our email
$et = Email_Template::instance('task_invoice_'.$key);
$et->to = array('account'=>array($io->account_id));
$et->variables = array(
'DUE'=>$io->due(TRUE),
'DUE_DATE'=>$io->display('due_date'),
'FIRST_NAME'=>$io->account->first_name,
'INV_NUM'=>$io->refnum(),
'INV_URL'=>URL::site(URL::link('user','invoice/view/'.$io->id),'http'),
'SITE_NAME'=>Company::instance()->name(),
);
// @todo Record email log id if possible.
if ($et->send()) {
$io->set_remind($key,time());
array_push($action,(string)$io);
}
}
$this->response->body(_('Due Reminders Sent: ').join('|',$action));
}
/**
* Generate our services invoices, based on the service next invoice date
*
* @param int ID Service ID to generate invoice for (optional) - multiple services colon separated
*/
public function action_services() {
// Used to only process X invoices in a row.
$max = ($x=Kohana::$config->load('debug')->invoice) ? $x : ORM::factory('Invoice')->config('GEN_INV_MAX');
// Our service next billing dates that need to be updated if this is successful.
$snd = array();
// Our charges that need to be updated if this is successful.
$chgs = array();
// If we are invoicing a specific service
$sid = is_null($this->request->param('id')) ? NULL : explode(':',$this->request->param('id'));
// Sort our service by account_id, then we can generate 1 invoice.
$svs = ORM::factory('Service')->list_invoicesoon()->as_array();
Sort::MAsort($svs,'account_id,date_next_invoice');
$aid = $due = $io = NULL;
$max_count = 0;
foreach ($svs as $so) {
// If we are generating an invoice for a service, skip to that service.
if (! is_null($sid) AND ! in_array($so->id,$sid))
continue;
// Close off invoice, and start a new one.
if (is_null($io) OR (! is_null($aid) AND $aid != $so->account_id) OR (! is_null($due) AND $due != $io->min_due($so->date_next_invoice))) {
// Close this invoice.
if (is_object($io)) {
// Save our invoice.
if (! $io->save())
throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));
}
// If we have issued the max number of invoices this round, finish.
if ($max AND (++$max_count > $max))
break;
// Start a new invoice.
$io = ORM::factory('Invoice');
$io->due_date = $due = $io->min_due($so->date_next_invoice);
$io->account_id = $aid = $so->account_id;
$io->status = TRUE;
}
$pdata = Period::details($so->recur_schedule,$so->product->price_recurr_weekday,$so->date_next_invoice,TRUE);
$iio = $io->add_item();
$iio->service_id = $so->id;
$iio->product_id = $so->product_id;
$iio->quantity = $pdata['prorata'];
$iio->item_type = 0; // Service Billing
$iio->discount_amt = NULL; // @todo
$iio->price_base = $so->price();
$iio->recurring_schedule = $so->recur_schedule;
$iio->date_start = $pdata['start_time'];
$iio->date_stop = $pdata['end_time'];
// Our service next billing date, if this invoice generation is successful.
$snd[$so->id] = $pdata['end_time']+86400;
// Check if there are any charges
$c = ORM::factory('Charge')
->where('service_id','=',$so->id)
->where('status','=',0)
->where('sweep_type','=',6); // @todo This needs to be dynamic, not "6"
foreach ($c->find_all() as $co) {
$iio = $io->add_item();
$iio->service_id = $co->service_id;
$iio->product_id = $co->product_id;
$iio->charge_id = $co->id;
$iio->quantity = $co->quantity;
$iio->item_type = 5; // @todo This probably should not be hard coded as "5".
$iio->discount_amt = NULL; // @todo
$iio->price_base = $co->amount;
$iio->date_start = $co->date_orig;
$iio->date_stop = $co->date_orig; // @todo
// @todo Temp
// We'll mark any charges as temporarily processed, although they should be set to status=1 later.
$co->status=2;
$co->save();
array_push($chgs,$co->id);
}
}
// Save our invoice.
if ($io AND ! $io->saved() AND ! $io->save()) {
print_r($io->items());
throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));
}
// Update our service next billing dates.
// @todo Catch any update errors
foreach ($snd as $sid=>$date) {
$so = ORM::factory('Service',$sid);
$so->date_next_invoice = $date;
$so->save();
}
// Update any processed charges as such
// @todo Catch any update errors
foreach ($chgs as $cid) {
$co = ORM::factory('Charge',$cid);
$co->status=1;
$co->save();
}
$this->response->body(_('Services Invoiced: ').join('|',array_keys($snd)));
}
public function action_send() {
// Used to only process X invoices in a row.
$max = ORM::factory('Invoice')->config('EMAIL_INV_MAX');

View File

@@ -67,7 +67,7 @@ class Controller_User_Invoice extends Controller_Invoice {
->set('o',$io);
if ($io->due() AND ! $io->cart_exists())
$output .= View::factory('/invoice/user/view/pay')
$output .= View::factory('invoice/user/view/pay')
->set('mid',$io->mid())
->set('o',$io);

View File

@@ -1,16 +0,0 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This interface ensures that all invoice processing objects have the right methods
*
* @package Invoice
* @category Interface
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
interface Invoicable {
// Render the line item for an invoice
public function invoice_line();
}
?>

View File

@@ -13,8 +13,26 @@ class Invoice {
// This invoice Object
private $io;
private $_methods = array(
'min_due',
'save',
'saved',
);
// Enable passing calls to ORM::Invoice()
public function __call($method,array $args) {
if (in_array($method,$this->_methods))
return call_user_func_array(array($this->io,$method),$args);
else
throw HTTP_Exception::factory(501,'Unknown/unauthorised method :method',array(':method'=>$method));
}
public function __construct(Model_Invoice $io=NULL) {
$this->io = is_null($io) ? ORM::factory('Invoice') : $io;
// Set our invoice as valid
if (is_null($io))
$this->io->status = 1;
}
public static function instance(Model_Invoice $io=NULL) {
@@ -27,6 +45,19 @@ class Invoice {
* @param $so Model_Servie
*/
public function add_service(Model_Service $so) {
if ($this->io->loaded())
throw HTTP_Exception::factory(501,'Cannot use add service :service to an existing invoice :invoice ',array(':service'=>$so->id,':invoice'=>$this->io->id));
if (! $this->io->account_id)
$this->io->account_id = $so->account_id;
else if ($this->io->account_id != $so->account_id)
throw HTTP_Exception::factory(501,'Cannot add service :service to invoice - it is for a different account',array(':service'=>$so->id));
// Set the invoice due date
if (! $this->io->due_date OR $this->io->due_date > $this->io->min_due($so->date_next_invoice))
$this->io->due_date = $this->io->min_due($so->date_next_invoice);
$pdata = Period::details($so->recur_schedule,$so->product->price_recurr_day,$so->invoiced_to()+86400,FALSE,$so->product->price_recurr_strict);
$iio = ORM::factory('Invoice_Item');
@@ -39,13 +70,14 @@ class Invoice {
$iio->date_stop = $pdata['end_time'];
// Service Billing
$iio->item_type = StaticList_ItemType::index('MAIN');
$iio->item_type = 0;
$this->io->add_item($iio);
// Check if there are any charges
$c = ORM::factory('Charge')
->where('service_id','=',$so->id)
->where('void','is',NULL)
->where('processed','is',NULL);
foreach ($c->find_all() as $co) {
@@ -57,9 +89,7 @@ class Invoice {
$iio->price_base = $co->amount;
$iio->date_start = $co->date_orig;
$iio->date_stop = $co->date_orig;
// @todo This should be $co->item_type;
$iio->item_type = StaticList_ItemType::index('EXCESS');
$iio->item_type = $co->type;
$this->io->add_item($iio);
}
@@ -67,12 +97,13 @@ class Invoice {
return $this;
}
public function render($type,$section) {
public function render($type,$section,$args=array()) {
switch ($type) {
case 'html':
switch ($section) {
case 'body':
return View::factory('invoice/user/view/body')
->set('show_id',(isset($args['noid']) AND $args['noid']) ? FALSE : TRUE)
->set('o',$this->io);
break;

View File

@@ -38,8 +38,9 @@ class Model_Invoice extends ORM_OSB implements Cartable {
);
// Items belonging to an invoice
private $invoice_items = array();
private $invoice_items_unsorted = TRUE;
protected $_sub_items_load = array(
'invoice_item'=>'service_id,item_type',
);
/** INTERFACE REQUIREMENTS **/
public function cart_item() {
@@ -53,32 +54,21 @@ class Model_Invoice extends ORM_OSB implements Cartable {
return count(Cart::instance()->get($this->mid(),$this->id));
}
/**
* Intercept our object load, so that we can load our subitems
*/
protected function _load_values(array $values) {
parent::_load_values($values);
if ($this->_loaded)
$this->invoice_items = $this->invoice_item->find_all()->as_array();
return $this;
}
/**
* Add an item to an invoice
*/
public function add_item(Model_Invoice_Item $iio=NULL) {
// @todo This is the old calling of this function, which should be removed
if (is_null($iio)) {
$c = count($this->invoice_items);
$c = count($this->_sub_items);
$this->invoice_items[$c] = ORM::factory('Invoice_Item');
$this->_sub_items[$c] = ORM::factory('Invoice_Item');
return $this->invoice_items[$c];
return $this->_sub_items[$c];
}
array_push($this->invoice_items,$iio);
array_push($this->_sub_items,$iio);
$this->_sub_items_sorted = FALSE;
}
/**
@@ -86,7 +76,7 @@ class Model_Invoice extends ORM_OSB implements Cartable {
*
* @param $period Return an Array of items for that period
*/
public function items_periods($period=NULL) {
public function items_periods($period=FALSE) {
$result = array();
foreach ($this->items() as $ito) {
@@ -94,15 +84,60 @@ class Model_Invoice extends ORM_OSB implements Cartable {
if ($ito->item_type != 0)
continue;
if (is_null($period) AND ! in_array($ito->recurring_schedule,$result))
if ($period === FALSE AND ! in_array($ito->recurring_schedule,$result))
array_push($result,$ito->recurring_schedule);
elseif ($ito->recurring_schedule == $period)
array_push($result,$ito);
elseif ($ito->recurring_schedule == $period) {
// If we have this service already, we'll skip
if (! Object::in_array('service_id',$ito->service_id,$result))
array_push($result,$ito);
}
}
return $result;
}
/**
* Return the item titles that are on an invoice
*
* @param $title Return an Array of items for that title
*/
public function items_titles($title=NULL,$period=NULL) {
$result = array();
foreach ($this->items() as $ito) {
if ($ito->service_id) {
if (is_null($title) AND ! in_array($ito->title(),$result) AND (is_null($period) OR ($period == $ito->recurring_schedule)))
array_push($result,$ito->title());
elseif (($ito->title() == $title AND (is_null($period) OR ($period == $ito->recurring_schedule))) OR is_null($ito->recurring_schedule))
array_push($result,$ito);
} else {
throw HTTP_Exception::factory(501,'Not handled non-services');
}
}
return $result;
}
/**
* Return the service items on an invoice relating to an invoice_item
* IE: item_type == 0
*/
public function service_items(Model_Invoice_Item $o) {
$result = array();
// At the moment, we only return items pertaining to a service
if (! $o->service_id)
return $result;
foreach ($this->items() as $iio)
if ($iio->item_type == 0 AND $iio->service_id == $o->service_id)
array_push($result,$iio);
return $result;
}
/**
* Return the extra items on an invoice relating to an invoice_item
* IE: item_type != 0
@@ -195,7 +230,7 @@ class Model_Invoice extends ORM_OSB implements Cartable {
public function items($type='ALL') {
$result = array();
foreach ($this->invoice_items as $ito) {
foreach ($this->_sub_items as $ito) {
$return = FALSE;
switch ($type) {
@@ -429,9 +464,11 @@ class Model_Invoice extends ORM_OSB implements Cartable {
// Our items will be clobbered once we save the object, so we need to save it here.
$items = $this->items();
// If this is a new invoice, we'll need to do more work
$new = ! $this->loaded();
// Save the invoice
if ($this->changed())
parent::save($validation);
parent::save($validation);
// Need to save the associated items and their taxes
if ($this->loaded()) {
@@ -453,6 +490,27 @@ class Model_Invoice extends ORM_OSB implements Cartable {
throw new Kohana_Exception('Problem saving invoice_item for invoice :invoice - Failed save()',array(':invoice'=>$this->id));
}
// If this is a new invoice, we'll need to update some other items
if ($new) {
// Update next invoice date
if ($iio->item_type == 0) {
$iio->service->date_next_invoice = $iio->date_stop+86400;
// @todo Mark invoice as cancelled and write a memo, then...
if (! $iio->service->save())
throw new Kohana_Exception('Problem saving service :service for invoice_item :invoice_item - Failed save()',array(':invoice_item'=>$iio->id,':service'=>$iio->service_id));
}
// Update charge iteme
if ($iio->charge_id) {
$iio->charge->processed = 1;
// @todo Mark invoice as cancelled and write a memo, then...
if (! $iio->charge->save())
throw new Kohana_Exception('Problem saving charge :charge for invoice_item :invoice_item - Failed save()',array(':invoice_item'=>$iio->id,':charge'=>$iio->charge_id));
}
}
// @todo Need to save discount information
}

View File

@@ -12,7 +12,7 @@
* Column Definitions:
* + item_type: 0=MAIN Service Item,2=?,3=?,4=Connection/Setup,5=Excess Service Item,6=Change Service,126=Payment Fee,127=Late Fee
*/
class Model_Invoice_Item extends ORM_OSB implements Invoicable {
class Model_Invoice_Item extends ORM_OSB {
// Relationships
protected $_belongs_to = array(
'product'=>array(),
@@ -38,11 +38,21 @@ class Model_Invoice_Item extends ORM_OSB implements Invoicable {
),
);
// Items belonging to an invoice
private $subitems = array();
private $subitems_loaded = FALSE;
// Items belonging to an invoice item
protected $_sub_items_load = array(
'invoice_item_tax'=>FALSE,
);
/**
* The title for invoice items
*/
public function title() {
if ($this->product_id AND $this->service_id)
return $this->product_id ? sprintf('%s: %s',$this->product->title(),$this->service->name()) : $this->service->name;
else
return 'Unknown Item';
}
/** INTERFACE REQUIREMENTS **/
public function invoice_line() {
if ($this->charge_id)
return $this->charge->description.' '.$this->period();
@@ -52,23 +62,6 @@ class Model_Invoice_Item extends ORM_OSB implements Invoicable {
throw HTTP_Exception::factory(501,'Unable to render invoice item :id',array(':id'=>$this->id));
}
public function __construct($id = NULL) {
// Load our model.
parent::__construct($id);
return $this->load_sub_items();
}
private function load_sub_items() {
// Load our sub items
if (! $this->subitems_loaded AND $this->loaded()) {
$this->subitems['tax'] = $this->invoice_item_tax->find_all()->as_array();
$this->subitems_loaded = TRUE;
}
return $this;
}
// Display a transaction number
public function trannum() {
return sprintf('%03s-%06s',$this->item_type,$this->id);
@@ -125,7 +118,7 @@ class Model_Invoice_Item extends ORM_OSB implements Invoicable {
}
public function total($format=FALSE) {
$result = Currency::round($this->subtotal()+$this->tax()-$this->discount());
$result = $this->void ? 0 : Currency::round($this->subtotal()+$this->tax()-$this->discount());
return $format ? Currency::display($result) : $result;
}
@@ -205,9 +198,9 @@ class Model_Invoice_Item extends ORM_OSB implements Invoicable {
if ($this->saved()) {
$iito = ORM::factory('Invoice_Item_Tax');
if ($this->subitems_loaded) {
if ($this->_sub_items) {
foreach (array('tax') as $i)
foreach ($this->subitems[$i] as $io)
foreach ($this->_sub_items[$i] as $io)
if ($io->changed())
$io->save();

View File

@@ -0,0 +1,64 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* Generate customer invoices for services
*
* @package Invoice
* @category Tasks
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Task_Invoice_Service extends Minion_Task {
protected $_options = array(
'days'=>1, // Days in advance to generate for
'id'=>NULL, // Service invoice to generate for
);
protected function _execute(array $params) {
// Used to only process X invoices in a row.
$max = ($x=Kohana::$config->load('debug')->invoice) ? $x : ORM::factory('Invoice')->config('GEN_INV_MAX');
// Sort our service by account_id, then we can generate 1 invoice.
$svs = ORM::factory('Service')->list_invoicesoon($params['days'])->as_array();
Sort::MAsort($svs,'account_id');
$sids = $params['id'] ? explode(':',$params['id']) : array();
$aid = $io = NULL;
$max_count = 0;
$action = array();
foreach ($svs as $so) {
// If we are generating an invoice for a service, skip to that service.
if ($sids AND ! in_array($so->id,$sids))
continue;
// Close off invoice, and start a new one, if this is for a different account.
if (is_null($io) OR (! is_null($aid) AND $aid != $so->account_id)) {
// Close and save this invoice.
if (is_object($io) AND ! $io->save())
throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));
// If we have issued the max number of invoices this round, finish.
if ($max AND (++$max_count > $max))
break;
// Start a new invoice.
$io = Invoice::instance();
$aid = $so->account_id;
}
$io->add_service($so);
// Record what we have updated.
array_push($action,$so->id);
}
// Save our invoice.
if ($io AND ! $io->saved() AND ! $io->save())
throw new Kohana_Exception('Failed to save invoice :invoice for service :service',array(':invoice'=>$io->id,':service'=>$so->id));
return _('Services Invoiced: ').join('|',$action);
}
}
?>