<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class RepairOrder extends Model
{
use HasFactory;
protected $fillable = [
'order_number', 'user_id', 'car_id', 'admin_id', 'status',
'order_date', 'completion_date', 'problem_description',
'admin_notes', 'total_labor_cost', 'total_parts_cost', 'total_amount'
];
protected $casts = [
'order_date' => 'date',
'completion_date' => 'date',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function car()
{
return $this->belongsTo(Car::class);
}
public function admin()
{
return $this->belongsTo(User::class, 'admin_id');
}
public function services()
{
return $this->belongsToMany(Service::class, 'order_services')
->withPivot('quantity', 'price_at_time')
->withTimestamps();
}
public function parts()
{
return $this->belongsToMany(Part::class, 'order_parts')
->withPivot('quantity', 'price_at_time')
->withTimestamps();
}
// Обновление стоимости работ
public function updateLaborCost()
{
$total = $this->services->sum(function ($service) {
return $service->pivot->quantity * $service->pivot->price_at_time;
});
$this->total_labor_cost = $total;
$this->updateTotalAmount();
return $total;
}
// Обновление стоимости запчастей
public function updatePartsCost()
{
$total = $this->parts->sum(function ($part) {
return $part->pivot->quantity * $part->pivot->price_at_time;
});
$this->total_parts_cost = $total;
$this->updateTotalAmount();
return $total;
}
// Обновление общей стоимости
public function updateTotalAmount()
{
$this->total_amount = $this->total_labor_cost + $this->total_parts_cost;
$this->saveQuietly();
return $this->total_amount;
}
// Полный пересчёт
public function recalculateTotals()
{
$this->updateLaborCost();
$this->updatePartsCost();
return $this->total_amount;
}
// Проверки статусов
public function isPending()
{
return $this->status === 'pending';
}
public function isInProgress()
{
return $this->status === 'in_progress';
}
public function isCompleted()
{
return $this->status === 'completed';
}
public function isCancelled()
{
return $this->status === 'cancelled';
}
}