workshop_lara_nova/app/Models/RepairOrder.php
2025-03-22 10:19:15 +00:00

102 lines
2.6 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class RepairOrder extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'order_number',
'vehicle_id',
'priority',
'status',
'reported_at',
'assigned_at',
'started_at',
'completed_at',
'issue_description',
'diagnosis',
'resolution',
'mileage_at_repair',
'labor_hours',
'labor_cost',
'parts_cost',
'total_cost',
];
protected $casts = [
'reported_at' => 'datetime',
'assigned_at' => 'datetime',
'started_at' => 'datetime',
'completed_at' => 'datetime',
'labor_hours' => 'decimal:2',
'labor_cost' => 'decimal:2',
'parts_cost' => 'decimal:2',
'total_cost' => 'decimal:2',
];
public function vehicle(): BelongsTo
{
return $this->belongsTo(Vehicle::class);
}
public function technicians(): BelongsToMany
{
return $this->belongsToMany(Technician::class)
->withPivot('is_lead')
->withTimestamps();
}
public function parts(): BelongsToMany
{
return $this->belongsToMany(Part::class)
->withPivot('quantity_used', 'unit_cost')
->withTimestamps();
}
public function repairTasks(): HasMany
{
return $this->hasMany(RepairTask::class);
}
public function documents(): MorphMany
{
return $this->morphMany(Document::class, 'documentable');
}
public function getLeadTechnician()
{
return $this->technicians()->wherePivot('is_lead', true)->first();
}
public function calculateCosts()
{
// Calculate parts cost
$this->parts_cost = $this->parts()
->withPivot('quantity_used', 'unit_cost')
->get()
->sum(function ($part) {
return $part->pivot->quantity_used * $part->pivot->unit_cost;
});
// Calculate labor cost based on tasks
$this->labor_hours = $this->repairTasks()->sum('actual_hours');
$this->labor_cost = $this->labor_hours * config('workshop.hourly_rate', 85.00);
// Calculate total cost
$this->total_cost = $this->parts_cost + $this->labor_cost;
$this->save();
}
}