72 lines
2.1 KiB
PHP
72 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\InvoiceStatus;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
// InvoiceSettings used for number generation
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
|
|
class Invoice extends Model
|
|
{
|
|
use HasFactory, SoftDeletes;
|
|
|
|
protected $fillable = [
|
|
'client_id', 'invoice_number', 'title', 'description',
|
|
'subtotal', 'tax_rate', 'tax_amount', 'total', 'currency',
|
|
'status', 'issue_date', 'due_date', 'paid_date', 'notes',
|
|
'bank_name', 'bank_account', 'bank_holder', 'branch_name',
|
|
'signature_image',
|
|
];
|
|
|
|
protected $casts = [
|
|
'status' => InvoiceStatus::class,
|
|
'issue_date' => 'date',
|
|
'due_date' => 'date',
|
|
'paid_date' => 'date',
|
|
'subtotal' => 'decimal:2',
|
|
'tax_rate' => 'decimal:2',
|
|
'tax_amount' => 'decimal:2',
|
|
'total' => 'decimal:2',
|
|
];
|
|
|
|
public function client(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Client::class);
|
|
}
|
|
|
|
public function items(): HasMany
|
|
{
|
|
return $this->hasMany(InvoiceItem::class);
|
|
}
|
|
|
|
public function recalculate(): void
|
|
{
|
|
// Total of all items (what the creator receives)
|
|
$this->subtotal = $this->items->sum('total');
|
|
|
|
// Tax is calculated only on taxable items, but paid by the client on top
|
|
$taxableSubtotal = $this->items->where('is_taxable', true)->sum('total');
|
|
$this->tax_amount = round((float) $taxableSubtotal * ($this->tax_rate / 100), 2);
|
|
|
|
// Grand total = subtotal (creator's fee, pre-tax — tax is borne by client separately)
|
|
$this->total = $this->subtotal;
|
|
$this->save();
|
|
}
|
|
|
|
public function getFormattedTotalAttribute(): string
|
|
{
|
|
return 'Rp ' . number_format((float) $this->total, 0, ',', '.');
|
|
}
|
|
|
|
public static function generateNumber(): string
|
|
{
|
|
return InvoiceSettings::generateNumber();
|
|
}
|
|
}
|