128 lines
2.9 KiB
PHP
128 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use App\Models\Concerns\HasAttachments;
|
|
|
|
class PettyCash extends Model
|
|
{
|
|
use HasFactory, SoftDeletes, HasAttachments;
|
|
|
|
protected $fillable = [
|
|
'tenant_id',
|
|
'project_id',
|
|
'currency_id',
|
|
'title',
|
|
'description',
|
|
'amount',
|
|
'original_amount',
|
|
'amount_usd',
|
|
'remaining',
|
|
'request_date',
|
|
'receipt_path',
|
|
'requested_by',
|
|
'approved_by',
|
|
'approval_date',
|
|
'approved_at',
|
|
'status',
|
|
];
|
|
|
|
protected $casts = [
|
|
'amount' => 'decimal:2',
|
|
'original_amount' => 'decimal:2',
|
|
'amount_usd' => 'decimal:2',
|
|
'remaining' => 'decimal:2',
|
|
'request_date' => 'date',
|
|
'approval_date' => 'datetime',
|
|
'approved_at' => 'datetime',
|
|
];
|
|
|
|
public function tenant()
|
|
{
|
|
return $this->belongsTo(Tenant::class);
|
|
}
|
|
|
|
public function project()
|
|
{
|
|
return $this->belongsTo(Project::class);
|
|
}
|
|
|
|
public function currency()
|
|
{
|
|
return $this->belongsTo(Currency::class);
|
|
}
|
|
|
|
public function requestedBy()
|
|
{
|
|
return $this->belongsTo(User::class, 'requested_by');
|
|
}
|
|
|
|
public function approvedBy()
|
|
{
|
|
return $this->belongsTo(User::class, 'approved_by');
|
|
}
|
|
|
|
public function expenses()
|
|
{
|
|
return $this->hasMany(Expense::class);
|
|
}
|
|
|
|
public function scopeByStatus($query, $status)
|
|
{
|
|
return $query->where('status', $status);
|
|
}
|
|
|
|
public function getStatusLabelAttribute()
|
|
{
|
|
return [
|
|
'pending' => __('pettyCash.pending'),
|
|
'approved' => __('pettyCash.approved'),
|
|
'rejected' => __('pettyCash.rejected'),
|
|
'settled' => __('pettyCash.settled'),
|
|
][$this->status] ?? $this->status;
|
|
}
|
|
|
|
/**
|
|
* Calculate remaining amount based on approved expenses.
|
|
*/
|
|
public function calculateRemaining(): float
|
|
{
|
|
$totalExpenses = $this->expenses()
|
|
->whereIn('status', ['approved', 'paid'])
|
|
->sum('amount');
|
|
|
|
return (float) $this->amount - (float) $totalExpenses;
|
|
}
|
|
|
|
/**
|
|
* Update the remaining amount.
|
|
*/
|
|
public function updateRemaining(): void
|
|
{
|
|
$this->remaining = $this->calculateRemaining();
|
|
$this->saveQuietly();
|
|
}
|
|
|
|
/**
|
|
* Get total approved expenses.
|
|
*/
|
|
public function getTotalExpensesAttribute(): float
|
|
{
|
|
return (float) $this->expenses()
|
|
->whereIn('status', ['approved', 'paid'])
|
|
->sum('amount');
|
|
}
|
|
|
|
/**
|
|
* Get utilization percentage.
|
|
*/
|
|
public function getUtilizationAttribute(): float
|
|
{
|
|
if ($this->amount <= 0) return 0;
|
|
return min(100, round(($this->total_expenses / (float) $this->amount) * 100, 1));
|
|
}
|
|
}
|