110 lines
2.7 KiB
PHP
110 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
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;
|
|
use MatanYadaev\EloquentSpatial\Objects\Polygon;
|
|
use MatanYadaev\EloquentSpatial\Traits\HasSpatial;
|
|
|
|
class Tenant extends Model
|
|
{
|
|
use HasFactory, HasSpatial, SoftDeletes;
|
|
|
|
public const STATUS_ONBOARDING = 'onboarding';
|
|
|
|
public const STATUS_ACTIVE = 'active';
|
|
|
|
public const STATUS_SUSPENDED = 'suspended';
|
|
|
|
protected $fillable = [
|
|
'uuid', 'code', 'name', 'short_name',
|
|
'city_municipality_id',
|
|
'boundary_polygon',
|
|
'timezone', 'theme_color', 'logo_path',
|
|
'contact_email', 'contact_phone',
|
|
'status',
|
|
'qr_retail_price_centavos',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'boundary_polygon' => Polygon::class,
|
|
];
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (self $tenant): void {
|
|
if (empty($tenant->uuid)) {
|
|
$tenant->uuid = (string) Str::uuid();
|
|
}
|
|
if (empty($tenant->code) && ! empty($tenant->name)) {
|
|
$tenant->code = static::deriveCode($tenant->name);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* PSGC-derived tenant code. We use the city/municipality's `code`
|
|
* field when linked, otherwise slugify the name. Always uppercase.
|
|
*/
|
|
public static function deriveCode(string $name, ?CityMunicipality $city = null): string
|
|
{
|
|
if ($city?->code) {
|
|
return strtoupper($city->code);
|
|
}
|
|
|
|
return strtoupper(Str::slug($name));
|
|
}
|
|
|
|
public function cityMunicipality(): BelongsTo
|
|
{
|
|
return $this->belongsTo(CityMunicipality::class);
|
|
}
|
|
|
|
public function users(): HasMany
|
|
{
|
|
return $this->hasMany(User::class);
|
|
}
|
|
|
|
public function households(): HasMany
|
|
{
|
|
return $this->hasMany(Household::class);
|
|
}
|
|
|
|
public function trucks(): HasMany
|
|
{
|
|
return $this->hasMany(Truck::class);
|
|
}
|
|
|
|
public function isActive(): bool
|
|
{
|
|
return $this->status === self::STATUS_ACTIVE;
|
|
}
|
|
|
|
/**
|
|
* Effective area: the explicit boundary override if set, else the
|
|
* linked municipality. Used by geo lookups.
|
|
*/
|
|
public function effectiveBoundary(): ?Polygon
|
|
{
|
|
return $this->boundary_polygon;
|
|
}
|
|
|
|
public function getRouteKeyName(): string
|
|
{
|
|
return 'uuid';
|
|
}
|
|
|
|
public function getQrPriceAttribute(): float
|
|
{
|
|
return $this->qr_retail_price_centavos / 100;
|
|
}
|
|
}
|