topnotch_website/app/Models/InvoiceReport.php

81 lines
2.0 KiB
PHP
Raw Normal View History

2024-11-29 12:39:20 -05:00
<?php
namespace App\Models;
2024-12-10 15:28:14 -08:00
use App\Enums\InvoiceStatus;
2024-11-29 12:39:20 -05:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
2024-12-02 12:21:01 -05:00
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
2024-11-29 12:39:20 -05:00
class InvoiceReport extends Model
{
use HasFactory;
protected $fillable = [
2024-12-02 12:21:01 -05:00
'internal_id',
2024-11-29 12:39:20 -05:00
'customer_id',
'date_start',
'date_end',
'filter_paid',
'subtotal',
'pst',
'gst',
2024-12-10 15:28:14 -08:00
];
protected $appends = [
2024-11-29 12:39:20 -05:00
'total',
'balance',
2024-11-29 12:39:20 -05:00
];
2024-12-10 15:28:14 -08:00
protected $casts = [
'date_start' => 'date',
'date_end' => 'date',
];
2024-12-02 12:21:01 -05:00
public static function boot(): void
{
parent::boot();
2024-12-10 15:28:14 -08:00
static::created(function (InvoiceReport $model) {
$model->attributes['internal_id'] = 'TNR'.str_pad($model->id, 4, '0', STR_PAD_LEFT);
$invoices = Invoice::whereBetween('date', [$model->date_start, $model->date_end])
->where('customer_id', $model->customer_id)
->when($model->filter_paid, function ($query) {
$query->where('status', InvoiceStatus::UNPAID)
->orWhere('status', InvoiceStatus::PARTIALLY_PAID);
2024-12-10 15:28:14 -08:00
});
$model->invoices()->sync($invoices->pluck('id')->toArray());
2024-12-10 15:28:14 -08:00
2024-12-02 12:21:01 -05:00
$model->save();
});
}
2024-12-10 15:28:14 -08:00
public function getTotalAttribute()
{
return $this->invoices()->sum('total');
}
public function getBalanceAttribute()
{
return $this->invoices->sum(fn (Invoice $invoice) => $invoice->remainingBalance());
}
2024-11-29 12:39:20 -05:00
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
2024-12-02 12:21:01 -05:00
public function invoices(): BelongsToMany
{
return $this->BelongsToMany(Invoice::class);
}
2024-12-10 15:28:14 -08:00
public function orders()
2024-12-02 12:21:01 -05:00
{
2024-12-10 15:28:14 -08:00
return $this->invoices()->with('orders')->get()->pluck('orders')->flatten()->unique('id');
2024-12-02 12:21:01 -05:00
}
2024-11-29 12:39:20 -05:00
}