66 lines
1.9 KiB
PHP
66 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\InvoiceStatus;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
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',
|
|
];
|
|
|
|
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
|
|
{
|
|
$this->subtotal = $this->items->sum('total');
|
|
$this->tax_amount = round($this->subtotal * ($this->tax_rate / 100), 2);
|
|
$this->total = $this->subtotal + $this->tax_amount;
|
|
$this->save();
|
|
}
|
|
|
|
public function getFormattedTotalAttribute(): string
|
|
{
|
|
return 'Rp ' . number_format((float) $this->total, 0, ',', '.');
|
|
}
|
|
|
|
public static function generateNumber(): string
|
|
{
|
|
$prefix = 'INV-' . now()->format('Ym');
|
|
$last = static::where('invoice_number', 'like', $prefix . '%')->count();
|
|
return $prefix . '-' . str_pad((string) ($last + 1), 3, '0', STR_PAD_LEFT);
|
|
}
|
|
}
|