Open Source Billing

This commit is contained in:
Deon George
2013-10-10 13:44:53 +11:00
commit b02d70adf0
2344 changed files with 392978 additions and 0 deletions

View File

@@ -0,0 +1,237 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides payment capabilities.
*
* @package Payment
* @category Controllers/Admin
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Controller_Admin_Payment extends Controller_TemplateDefault_Admin {
protected $secure_actions = array(
'add'=>TRUE,
'addbulk'=>TRUE,
'list'=>TRUE,
'view'=>TRUE,
'ajaxlist'=>FALSE,
'autoitemlist'=>FALSE,
);
public function action_ajaxlist() {
$result = array();
if (isset($_REQUEST['term']) AND trim($_REQUEST['term'])) {
$result += ORM::factory('Account')->list_autocomplete($_REQUEST['term']);
$result += ORM::factory('Invoice')->list_autocomplete($_REQUEST['term'],'account_id');
}
$this->auto_render = FALSE;
$this->response->headers('Content-Type','application/json');
$this->response->body(json_encode(array_values($result)));
}
public function action_autoitemlist() {
// We are only available via an ajax call.
if (! Request::current()->is_ajax() OR ! isset($_REQUEST['key']) OR ! trim($_REQUEST['key']))
die();
$output = View::factory($this->viewpath().'/head');
$this->auto_render = FALSE;
$i = 0;
$list = array();
if (isset($_REQUEST['pid']))
foreach (ORM::factory('Payment',$_REQUEST['pid'])->items() as $pio) {
$output .= View::factory($this->viewpath().'/body')
->set('trc',$i++%2 ? 'odd' : 'even')
->set('pio',$pio)
->set('io',$pio->invoice);
// Remember the invoices we have listed
array_push($list,$pio->invoice_id);
}
foreach (ORM::factory('Account',$_REQUEST['key'])->invoices_due() as $io)
// Only list invoices not yet listed
if (! in_array($io->id,$list))
$output .= View::factory($this->viewpath().'/body')
->set('trc',$i++%2 ? 'odd' : 'even')
->set('pio',ORM::factory('Payment_Item'))
->set('io',$io);
// @todo Need the JS to add up the payment allocation before submission
$output .= View::factory($this->viewpath().'/foot')
->set('trc',$i++%2 ? 'odd' : 'even');
$this->response->body($output);
}
/**
* Show a list of invoices
*/
public function action_list() {
Block::add(array(
'title'=>_('Customer Payments'),
'body'=>Table::display(
ORM::factory('Payment')->find_all(),
25,
array(
'id'=>array('label'=>'ID','url'=>URL::link('admin','payment/view/')),
'date_payment'=>array('label'=>'Date'),
'account->accnum()'=>array('class'=>'right'),
'account->name()'=>array('label'=>'Account'),
'checkout->display("name")'=>array('label'=>'Method'),
'total_amt'=>array('label'=>'Total','class'=>'right'),
'balance(TRUE)'=>array('label'=>'Balance','class'=>'right'),
'invoicelist()'=>array('label'=>'Invoices'),
),
array(
'page'=>TRUE,
'type'=>'select',
'form'=>URL::link('admin','payment/view'),
)),
));
}
private function add_view($id=NULL,$output='') {
$po = ORM::factory('Payment',$id);
if ($_POST) {
// Update our invoice payment items
if (isset($_POST['payment_item']) AND count($_POST['payment_item']))
foreach ($_POST['payment_item'] as $k=>$v)
$po->add_item($k)->alloc_amt = is_numeric($v) ? $v : 0;
// Entry updated
if ($po->values($_POST)->check() AND $po->save())
SystemMessage::add(array(
'title'=>'Payment Recorded',
'type'=>'info',
'body'=>'Payment successfully recorded.',
));
}
$output .= Form::open();
$output .= View::factory('payment/admin/add_view')
->set('po',$po);;
$output .= Form::submit('submit','submit',array('class'=>'form_button'));
$output .= Form::close();
Style::add(array(
'type'=>'stdin',
'data'=>'.ui-autocomplete-loading { background: white url("'.URL::site('media/img/ui-anim_basic_16x16.gif').'") right center no-repeat; }'
));
Style::add(array(
'type'=>'file',
'data'=>'js/jquery.ui/css/smoothness/jquery-ui-1.8.16.custom.css',
));
Script::add(array(
'type'=>'file',
'data'=>'js/jquery-ui-1.8.16.custom.min.js',
));
Script::add(array('type'=>'stdin','data'=>'
$(document).ready(function() {
$("input[name=date_payment]").datepicker({
dateFormat: "@",
showOtherMonths: true,
selectOtherMonths: true,
showButtonPanel: true,
beforeShow: function(data) {
if (data.value)
data.value = data.value*1000;
},
onClose: function(data) {
$("input[name=date_payment]").val(data/1000);
}
});
$("input[name=account_id]").autocomplete({
source: "'.URL::link('admin','payment/ajaxlist',TRUE).'",
minLength: 2,
change: function(event,ui) {
// Send the request and update sub category dropdown
$.ajax({
type: "GET",
data: "key="+$(this).val(),
dataType: "html",
cache: false,
url: "'.URL::link('admin','payment/autoitemlist',TRUE).'",
timeout: 2000,
error: function(x) {
alert("Failed to submit");
},
success: function(data) {
$("div[id=items]").replaceWith(data);
}
});
}
});
});'
));
if ($po->loaded()) {
Script::add(array('type'=>'stdin','data'=>'
$(document).ready(function() {
$("div[id=items]").load("'.URL::link('admin','payment/autoitemlist',TRUE).'", {key: "'.$po->account_id.'", pid: "'.$po->id.'" });
});'
));
}
return $output;
}
public function action_add() {
Block::add(array(
'title'=>_('Add Payments Received'),
'body'=>$this->add_view(),
));
}
public function action_view() {
list($id,$output) = Table::page(__METHOD__);
Block::add(array(
'title'=>sprintf('%s: %s',_('View Payments Received'),$id),
'body'=>$this->add_view($id,$output),
));
}
public function action_addbulk() {
// @todo This needs to come from the DB.
$supported = array(
'ezypay'=>'Ezypay',
);
$output = '';
if ($_POST AND isset($_POST['payer'])) {
$c = sprintf('Payment_Bulk_%s',ucfirst($_POST['payer']));
$o = new $c();
if (! $_FILES) {
$output .= $o->form();
} else {
$output .= $o->process();
}
// We dont know what sort of payment type yet
} else {
$output .= Form::open();
$output .= Form::select('payer',$supported);
$output .= Form::submit('submit','submit',array('class'=>'form_button'));
$output .= Form::close();
}
Block::add(array(
'title'=>_('Bulk Payments Received'),
'body'=>$output,
));
}
}
?>

View File

@@ -0,0 +1,14 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides payment management
*
* @package Payment
* @category Controllers
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Controller_Payment extends Controller_TemplateDefault {
}
?>

View File

@@ -0,0 +1,41 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class provides User Payment functions
*
* @package Payment
* @category Controllers/User
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Controller_User_Payment extends Controller_TemplateDefault_User {
protected $secure_actions = array(
'list'=>TRUE,
);
/**
* Show a payments received
*/
public function action_list() {
Block::add(array(
'title'=>sprintf('%s: %s - %s',_('Payments Received For'),$this->ao->accnum(),$this->ao->name(TRUE)),
'body'=>Table::display(
$this->ao->payment->find_all(),
25,
array(
'id'=>array('label'=>'ID'),
'date_payment'=>array('label'=>'Date'),
'checkout->display("name")'=>array('label'=>'Method'),
'total_amt'=>array('label'=>'Total','class'=>'right'),
'balance(TRUE)'=>array('label'=>'Balance','class'=>'right'),
'invoicelist()'=>array('label'=>'Invoices'),
),
array(
'page'=>TRUE,
'type'=>'list',
)),
));
}
}
?>

View File

@@ -0,0 +1,265 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class supports OSB payments.
*
* @package Payment
* @category Models
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Model_Payment extends ORM_OSB {
// Relationships
protected $_has_many = array(
'payment_item'=>array('far_key'=>'id'),
'invoice'=>array('through'=>'payment_item'),
);
protected $_belongs_to = array(
'account'=>array(),
'checkout'=>array('foreign_key'=>'checkout_plugin_id'),
);
protected $_sorting = array(
'date_payment'=>'DESC'
);
protected $_display_filters = array(
'date_payment'=>array(
array('Config::date',array(':value')),
),
'total_amt'=>array(
array('Currency::display',array(':value')),
),
);
// Items belonging to an invoice
private $payment_items = array();
public function __construct($id = NULL) {
// Load our model.
parent::__construct($id);
// Load our sub items
if ($this->loaded())
$this->payment_items = $this->payment_item->find_all()->as_array();
}
/**
* Add an item to this payment
*
* @param $inv number, to allocate payment to an invoice
*/
public function add_item($invnum) {
// Find our id, if it exists
foreach ($this->payment_items as $pio)
if ($pio->invoice_id == $invnum)
return $pio;
// New Item
$c = count($this->payment_items);
$this->payment_items[$c] = ORM::factory('Payment_Item');
$this->payment_items[$c]->invoice_id = $invnum;
return $this->payment_items[$c];
}
/**
* Calculate the remaining balance available for this payment
*/
public function balance($format=FALSE) {
$result = $this->total();
foreach ($this->items('ALLOC') as $pio)
$result -= $pio->alloc_amt;
return $format ? Currency::display($result) : $result;
}
/**
* Find all items that are exportable.
*
* @param int $start List payments that were modified this many days ago
*/
public function export($start) {
return ORM::factory('Payment')
->where('date_payment','>=',time()-$start*86400)
->find_all();
}
/**
* Return a list of invoices that this payment is applied to
*/
public function invoices() {
$result = array();
foreach ($this->payment_items as $pio)
array_push($result,$pio->invoice);
return $result;
}
public function invoicelist() {
return join(',',$this->invoices());
}
/**
* Return a list of payment items for this payment.
* @param type [ALLOC|CREDIT|ALL]
* @see payment_items
*/
public function items($type='ALL') {
$result = array();
foreach ($this->payment_items as $pio) {
$return = FALSE;
switch ($type) {
case 'ALLOC':
if ($pio->alloc_amt > 0)
$return = TRUE;
break;
case 'CREDIT':
if ($pio->alloc_amt < 0)
$return = TRUE;
break;
case 'ALL':
default:
$return = TRUE;
break;
}
if ($return)
array_push($result,$pio);
}
return $result;
}
/**
* Show the total amount of a payment.
*/
public function total($format=FALSE) {
$result = $this->total_amt;
foreach ($this->items('CREDIT') as $pio)
$result += $pio->alloc_amt;
return $format ? Currency::display($result) : Currency::round($result);
}
/** LIST FUNCTIONS **/
public function list_unapplied() {
return array();
$pi = array();
// @todo database suffix needs to be dynamically calculated
foreach (DB::Query(Database::SELECT,
sprintf('SELECT A.id AS id,A.total_amt as total_amt FROM ab_%s A LEFT JOIN ab_%s B ON (A.site_id=B.site_id AND A.id=B.payment_id) WHERE (A.refund_status=0 OR A.refund_status IS NULL) GROUP BY A.id HAVING ROUND(SUM(IFNULL(B.alloc_amt,0)),2)!=A.total_amt ORDER BY account_id,payment_id','payment','payment_item'))
->execute() as $values) {
array_push($pi,$values['id']);
}
return $this->where('id','IN',$pi)->order_by('account_id')->find_all();
}
public function list_recent_table() {
// @todo This should be in a config file.
$css = '<style type="text/css">';
$css .= 'table.box-left { border: 1px solid #AAAACC; margin-right: auto; }';
$css .= 'tr.head { font-weight: bold; }';
$css .= 'td.head { font-weight: bold; }';
$css .= 'td.right { text-align: right; }';
$css .= 'tr.odd { background-color: #FCFCFE; }';
$css .= 'tr.even { background-color: #F6F6F8; }';
$css .= '</style>';
return $css.Table::display(
$this->limit(10)->find_all(),
25,
array(
'id'=>array('label'=>'ID'),
'date_payment'=>array('label'=>'Date'),
'checkout->display("name")'=>array('label'=>'Method'),
'total_amt'=>array('label'=>'Total','class'=>'right'),
'balance(TRUE)'=>array('label'=>'Balance','class'=>'right'),
'invoicelist()'=>array('label'=>'Invoices'),
),
array(
'type'=>'list',
));
}
public function save(Validation $validation = NULL) {
// Our items will be clobbered once we save the object, so we need to save it here.
$items = $this->items();
// @todo This should not be mandatory - or there should be a source for non-users (automatic postings)
$this->source_id = Auth::instance()->get_user() ? Auth::instance()->get_user()->id : 1;
$this->ip = Request::$client_ip;
// Make sure we dont over allocate
$t = 0;
$msg = '';
foreach ($items as $pio) {
// Only need to check items that ave actually changed.
if ($pio->changed()) {
$old_pio = ORM::factory('Payment_Item',$pio->id);
if (($it = $pio->invoice->due()+ORM::factory('Payment_Item',$pio->id)->alloc_amt-$pio->alloc_amt) < 0)
$msg .= ($msg ? ' ' : '').sprintf('Invoice %s over allocated by %3.2f.',$pio->invoice_id,$it);
}
$t += $pio->alloc_amt;
}
if ($t > (float)$this->total_amt)
$msg .= ($msg ? ' ' : '').sprintf('Payment over allocated by %3.2f.',$t-$this->total_amt);
if ($msg) {
SystemMessage::add(array(
'title'=>'Payment NOT Recorded',
'type'=>'warning',
'body'=>$msg,
));
return FALSE;
}
// Save the payment
parent::save($validation);
// Need to save the associated items and their taxes
if (! $this->changed() OR $this->saved()) {
foreach ($items as $pio) {
// Skip applying 0 payments to invoices.
if (Currency::round($pio->alloc_amt) == 0 AND ! $pio->loaded())
continue;
$pio->payment_id = $this->id;
if (! $pio->check()) {
// @todo Mark payment as cancelled and write a memo, then...
throw new Kohana_Exception('Problem saving payment_item for invoice :invoice - Failed check()',array(':invoice'=>$invoice->id));
}
$pio->save();
if (! $pio->saved()) {
// @todo Mark payment as cancelled and write a memo, then...
throw new Kohana_Exception('Problem saving payment_item for invoice :invoice - Failed save()',array(':invoice'=>$invoice->id));
}
}
} else {
throw new Kohana_Exception('Couldnt save payment for some reason?');
}
return TRUE;
}
}
?>

View File

@@ -0,0 +1,22 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class supports OSB exporting by rending the exportable items.
*
* @package Payment
* @category Models
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Model_Payment_Item extends ORM_OSB {
// Relationships
protected $_has_one = array(
'invoice'=>array('far_key'=>'invoice_id','foreign_key'=>'id'),
);
protected $_belongs_to = array(
'payment'=>array(),
);
}
?>

View File

@@ -0,0 +1,107 @@
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* This class is for processing Ezypay payments.
*
* @package Payment
* @category Helpers
* @author Deon George
* @copyright (c) 2009-2013 Open Source Billing
* @license http://dev.osbill.net/license.html
*/
class Payment_Bulk_Ezypay {
public function form() {
$result = '';
$result .= Form::open(NULL,array('enctype'=>'multipart/form-data'));
$result .= Form::hidden('payer',$_POST['payer']);
$result .= View::factory('payment/admin/addbulk/ezypay');
$result .= Form::submit('submit','submit',array('class'=>'form_button'));
$result .= Form::close();
return $result;
}
public function process() {
$payments = array();
// Process payment
$file = file_get_contents($_FILES['payment']['tmp_name']);
$file = preg_split("/[\r]?[\n]+/",$file);
$i = 0;
foreach ($file as $line) {
// Line 0 is our header
if ($i++ == 0 OR ! trim($line))
continue;
// Trim our whitespace on the end of the line.
$line = preg_replace("/\s+$/",'',$line);
$array = explode("\t",$line);
// Field 4 has our account reference
if (preg_match('/^'.Company::instance()->site(TRUE).'-/',$array[4]) AND $array[10] == 'Cleared') {
$aid = preg_replace('/^'.Company::instance()->site(TRUE).'-/','',$array[4]);
$po = ORM::factory('Payment');
$po->account_id = $aid;
$po->total_amt = $array[7];
$po->notes = $array[2].':'.$array[3];
$po->date_payment = strtotime(str_replace('/','-',$array[8]));
$payments[$array[3]] = $po;
}
}
$file = file_get_contents($_FILES['transaction']['tmp_name']);
$file = preg_split("/[\r]?[\n]+/",$file);
$i = 0;
foreach ($file as $line) {
// Line 0 is our header
if ($i++ == 0 OR ! trim($line))
continue;
// Trim our whitespace on the end of the line.
$line = preg_replace("/\s+$/",'',$line);
$array = explode("\t",$line);
// If we dont have a payment item for this fee, we'll continue.
if (! isset($payments[$array[3]]))
continue;
// Our commission fees
// @todo This should be in a config file
if (in_array($array[9],array(1,15)))
$payments[$array[3]]->fees_amt = (float)$array[7];
// @todo Hack - since the reports dont show how the payment was made.
// @todo Put this in a config file, in the mean time.
if ($array[7] == 1.05)
$payments[$array[3]]->checkout_plugin_id = 2;
else
$payments[$array[3]]->checkout_plugin_id = 4;
}
$result = '';
$result .= View::Factory('payment/admin/addbulk/ezypay/head');
$total = $fees = 0;
foreach ($payments as $po) {
$po->save();
$total += $po->total_amt;
$fees += $po->fees_amt;
$result .= View::Factory('payment/admin/addbulk/ezypay/body')
->set('o',$po);
}
$result .= View::Factory('payment/admin/addbulk/ezypay/foot')
->set('total',$total)
->set('fees',$fees);;
return $result;
}
}
?>

View File

@@ -0,0 +1,35 @@
<table width="100%" border="0">
<tr>
<td>
<table class="box-full">
<tr>
<td style="width: 25%;">Payment Date</td>
<td style="width: 75%;"><?php echo Form::input('date_payment',$po->date_payment); ?></td>
</tr>
<tr>
<td>Account</td>
<td><?php echo Form::input('account_id',$po->account_id); ?></td>
</tr>
<tr>
<td>Method</td>
<td><?php echo StaticList_Module::form('checkout_plugin_id','checkout',$po->checkout_plugin_id,'id','name',array('status'=>'=:1'),TRUE,array('class'=>'form_button'));?></td>
</tr>
<tr>
<td>Amount</td>
<td><?php echo Form::input('total_amt',$po->total()); ?></td>
</tr>
<tr>
<td>Fees</td>
<td><?php echo Form::input('fees_amt',$po->fees_amt); ?></td>
</tr>
<tr>
<td>Notes</td>
<td><?php echo Form::input('notes',$po->notes); ?></td>
</tr>
</table>
</td>
</tr>
<tr>
<td><div id='items'></div></td>
</tr>
</table>

View File

@@ -0,0 +1,13 @@
<table>
<tr>
<td colspan="2">Ezypay Payment</td>
</tr>
<tr>
<td>Payment File (BillDetails)</td>
<td><?php echo Form::file('payment'); ?></td>
</tr>
<tr>
<td>Transaction File (AddItems)</td>
<td><?php echo Form::file('transaction'); ?></td>
</tr>
</table>

View File

@@ -0,0 +1,7 @@
<tr>
<td><?php echo HTML::anchor(URL::link('admin','payment/view/'.$o->id),$o->display('id')); ?></td>
<td><?php echo $o->display('date_payment'); ?></td>
<td><?php echo $o->display('total_amt'); ?></td>
<td><?php echo $o->display('fees_amt'); ?></td>
<td><?php echo $o->display('notes'); ?></td>
</tr>

View File

@@ -0,0 +1,6 @@
<tr class="head">
<td colspan="2">&nbsp;</td>
<td><?php echo $total; ?></td>
<td><?php echo $fees; ?></td>
</tr>
</table>

View File

@@ -0,0 +1,8 @@
<table>
<tr class="head">
<td>Payment ID</td>
<td>Date Payment</td>
<td>Amount</td>
<td>Fees</td>
<td>Transaction ID</td>
</tr>

View File

@@ -0,0 +1,9 @@
<tr class="<?php echo $trc; ?>">
<td><?php echo HTML::anchor(URL::link('user','invoice/view/'.$io->id),$io->id()); ?></td>
<td><?php echo $io->display('date_orig'); ?></td>
<td><?php echo $io->display('due_date'); ?></td>
<td><?php echo $io->total(TRUE); ?></td>
<td><?php echo $io->payments_total(TRUE); ?></td>
<td><?php echo $io->due(TRUE); ?></td>
<td><?php echo Form::input('payment_item['.$io->id.']',$pio->alloc_amt); ?></td>
</tr>

View File

@@ -0,0 +1,7 @@
<tr class="<?php echo $trc; ?>">
<td colspan="5">&nbsp;</td>
<td class="head">Unapplied</td>
<td><?php echo Form::input('invoice_item[excess]','',array('disabled'=>'disabled')); ?></td>
</tr>
</table>
</div>

View File

@@ -0,0 +1,11 @@
<div id="items">
<table class="box-full">
<tr>
<td class="head">Invoice</td>
<td class="head">Date Issue</td>
<td class="head">Date Due</td>
<td class="head">Total</td>
<td class="head">Payments</td>
<td class="head">Due</td>
<td class="head">Alloc</td>
</tr>