osb/app/Models/Invoice.php
2018-06-19 22:31:49 +10:00

88 lines
1.6 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
protected $table = 'ab_invoice';
protected $dates = ['due_date'];
protected $with = ['items.taxes','account.country.currency','paymentitems'];
protected $appends = [
'date_due',
'due',
'invoice_id_url',
'total',
];
protected $visible = [
'date_due',
'due',
'id',
'invoice_id_url',
'total',
];
private $_total = 0;
public function account()
{
return $this->belongsTo(\App\User::class);
}
public function items()
{
return $this->hasMany(InvoiceItem::class);
}
public function paymentitems()
{
return $this->hasMany(PaymentItem::class);
}
public function getDueAttribute()
{
return sprintf('%3.'.$this->currency()->rounding.'f',$this->total - $this->paid);
}
public function getDateDueAttribute()
{
return $this->due_date->format('Y-m-d');
}
public function getInvoiceIdAttribute()
{
return sprintf('%02s-%04s-%04s',$this->site_id,$this->account_id,$this->id);
}
public function getInvoiceIdUrlAttribute()
{
return sprintf('<a href="/u/invoice/view/%s">%s</a>',$this->id,$this->invoice_id);
}
public function getPaidAttribute()
{
return $this->currency()->round($this->paymentitems->sum('alloc_amt'));
}
public function getTotalAttribute()
{
if (! $this->_total)
{
foreach ($this->items as $o)
{
if ($o->active)
$this->_total += $this->currency()->round($o->total);
}
}
return sprintf('%3.'.$this->currency()->rounding.'f',$this->_total);
}
public function currency()
{
return $this->account->country->currency;
}
}