90 lines
2.2 KiB
PHP
90 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class Invoice extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'client_id',
|
|
'group_id',
|
|
'source_quote_id',
|
|
'invoice_number',
|
|
'status',
|
|
'invoice_date',
|
|
'due_date',
|
|
'currency',
|
|
'total_ht',
|
|
'total_tva',
|
|
'total_ttc',
|
|
'e_invoicing_channel_id',
|
|
'e_invoice_status',
|
|
];
|
|
|
|
protected static function booted()
|
|
{
|
|
static::creating(function ($invoice) {
|
|
// Auto-generate invoice number if not provided
|
|
if (empty($invoice->invoice_number)) {
|
|
$prefix = 'FAC-' . now()->format('Ym') . '-';
|
|
$lastInvoice = self::where('invoice_number', 'like', $prefix . '%')
|
|
->orderBy('invoice_number', 'desc')
|
|
->first();
|
|
|
|
if ($lastInvoice) {
|
|
$lastNumber = intval(substr($lastInvoice->invoice_number, -4));
|
|
$newNumber = $lastNumber + 1;
|
|
} else {
|
|
$newNumber = 1;
|
|
}
|
|
|
|
$invoice->invoice_number = $prefix . str_pad((string)$newNumber, 4, '0', STR_PAD_LEFT);
|
|
}
|
|
});
|
|
}
|
|
|
|
protected $casts = [
|
|
'invoice_date' => 'date',
|
|
'due_date' => 'date',
|
|
'total_ht' => 'decimal:2',
|
|
'total_tva' => 'decimal:2',
|
|
'total_ttc' => 'decimal:2',
|
|
];
|
|
|
|
public function client()
|
|
{
|
|
return $this->belongsTo(Client::class);
|
|
}
|
|
|
|
public function group()
|
|
{
|
|
return $this->belongsTo(ClientGroup::class, 'group_id');
|
|
}
|
|
|
|
public function lines()
|
|
{
|
|
return $this->hasMany(InvoiceLine::class);
|
|
}
|
|
|
|
public function sourceQuote()
|
|
{
|
|
return $this->belongsTo(Quote::class, 'source_quote_id');
|
|
}
|
|
|
|
public function eInvoicingChannel()
|
|
{
|
|
return $this->belongsTo(EInvoicingChannel::class);
|
|
}
|
|
|
|
public function history()
|
|
{
|
|
return $this->hasMany(DocumentStatusHistory::class, 'document_id')
|
|
->where('document_type', 'invoice')
|
|
->orderBy('changed_at', 'desc');
|
|
}
|
|
}
|