Files
Verde-Web/app/Models/CollectionTeam.php

110 lines
3.2 KiB
PHP

<?php
namespace App\Models;
use App\Tenancy\HasTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class CollectionTeam extends Model
{
use HasFactory, HasTenant, SoftDeletes;
public const STATUS_ACTIVE = 'active';
public const STATUS_INACTIVE = 'inactive';
public const STATUS_STANDBY = 'standby';
protected $fillable = [
'uuid', 'tenant_id', 'name', 'area_id', 'driver_id', 'scanner_id', 'truck_id',
'status', 'notes', 'helper_count',
];
public function getRouteKeyName(): string
{
return 'uuid';
}
protected static function booted(): void
{
static::creating(function (self $t): void {
if (empty($t->uuid)) {
$t->uuid = (string) Str::uuid();
}
});
}
public function area(): BelongsTo
{
return $this->belongsTo(ServiceArea::class, 'area_id');
}
public function driver(): BelongsTo
{
return $this->belongsTo(User::class, 'driver_id');
}
public function scanner(): BelongsTo
{
return $this->belongsTo(User::class, 'scanner_id');
}
public function truck(): BelongsTo
{
return $this->belongsTo(Truck::class, 'truck_id');
}
public function members(): HasMany
{
return $this->hasMany(TeamMember::class, 'team_id');
}
public function helpers(): HasMany
{
return $this->members()->where('role_in_team', TeamMember::ROLE_HELPER);
}
public function trips(): HasMany
{
return $this->hasMany(Trip::class, 'team_id');
}
public function currentTrip(): \Illuminate\Database\Eloquent\Relations\HasOne
{
return $this->hasOne(Trip::class, 'team_id')
->whereIn('status', [Trip::STATUS_IN_PROGRESS, Trip::STATUS_AT_DUMPSITE]);
}
public function collectionLogs(): \Illuminate\Database\Eloquent\Relations\HasManyThrough
{
return $this->hasManyThrough(CollectionLog::class, Trip::class, 'team_id', 'trip_id');
}
public function getIsFullAttribute(): bool
{
// A team is considered "Full" if it has a Driver, a Scanner,
// and the number of helpers matches or exceeds the desired helper_count.
$hasCore = $this->driver_id && $this->scanner_id;
$helpersMet = $this->helpers()->count() >= ($this->helper_count ?: 2);
return $hasCore && $helpersMet;
}
public function getPerformanceStats(): array
{
$today = now()->startOfDay();
$week = now()->startOfWeek();
return [
'current_trip_qr' => $this->currentTrip?->collectionLogs()->count() ?? 0,
'current_trip_kg' => (int) ($this->currentTrip?->total_load_kg ?? 0),
'daily_qr' => $this->collectionLogs()->where('scanned_at', '>=', $today)->count(),
'weekly_qr' => $this->collectionLogs()->where('scanned_at', '>=', $week)->count(),
'total_qr' => $this->collectionLogs()->count(),
];
}
}