Files
Verde-Web/app/Models/User.php
admin 58a7d3680a feat(backend): hardening sprint — docs, schedulers, validation, email + pickup
1. API docs via dedoc/scramble at /docs/api (scoped to api/v1).
   Linked from the admin sidebar Settings group.

2. Scheduled commands registered in routes/console.php:
   - reports:aggregate (02:00) — daily/weekly/monthly aggregations
   - qr:expire (02:30) — flips past-due allocated/active codes to expired
   - trucks:prune-locations (03:00) — drops history older than retention
     window (default 7 days, config('verde.location_retention_days'))
   All idempotent + withoutOverlapping. --dry flags on qr:expire and
   trucks:prune-locations for safe inspection.

3. Trip double-booking validation: AdminTripController::store rejects
   new trips when the team or truck already has a non-cancelled trip on
   the same date. override_conflicts: true bypasses for emergencies.
   Cancelled trips don't block rebooking.

4a. Email verification: User implements MustVerifyEmail.
    VerifyEmailNotification overrides verificationUrl() for our
    namespaced route. Register sends the link automatically (best
    effort, won't block signup). POST /auth/email/resend (auth) +
    GET /auth/email/verify/{id}/{hash} (signed URL).

4b. Password change while logged in: POST /me/password validates
    current_password, requires the new password to differ, revokes
    every other active token on success — current session stays.

5a. PickupImminent notification: when TripStop -> arrived,
    TripExecutor::notifyAssignedHouseholds() finds households whose
    assigned_drop_off_point_id matches and sends DB + SMS.

5b. Auto-geofence on truck location: TruckTracker::record() now
    auto-fires TripExecutor::arriveAtDumpsite() when an in-progress
    trip's truck pings inside its dumpsite boundary. The executor's
    status guard prevents duplicate timeline events if the driver also
    presses arrive-dumpsite manually.

190 feature tests passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 17:13:00 +08:00

167 lines
4.5 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasApiTokens, HasFactory, HasRoles, LogsActivity, Notifiable, SoftDeletes;
public const ROLE_ADMIN = 'admin';
public const ROLE_RESIDENT = 'resident';
public const ROLE_DRIVER = 'driver';
public const ROLE_HELPER = 'helper';
public const ROLE_SCANNER = 'scanner';
public const ROLE_STORE_PARTNER = 'store_partner';
public const STATUS_ACTIVE = 'active';
public const STATUS_SUSPENDED = 'suspended';
public const STATUS_PENDING = 'pending';
protected $fillable = [
'uuid',
'email',
'phone',
'password',
'role',
'status',
'first_name',
'middle_name',
'last_name',
'avatar_path',
'preferred_language',
'fcm_token',
];
protected $hidden = [
'password',
'remember_token',
];
protected static function booted(): void
{
static::creating(function (self $user): void {
if (empty($user->uuid)) {
$user->uuid = (string) Str::uuid();
}
});
}
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'phone_verified_at' => 'datetime',
'last_login_at' => 'datetime',
'password' => 'hashed',
];
}
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logOnly(['email', 'phone', 'role', 'status', 'first_name', 'last_name'])
->logOnlyDirty()
->dontSubmitEmptyLogs();
}
public function getFullNameAttribute(): string
{
return trim(implode(' ', array_filter([
$this->first_name,
$this->middle_name,
$this->last_name,
])));
}
public function sendEmailVerificationNotification(): void
{
$this->notify(new \App\Notifications\VerifyEmailNotification());
}
public function headedHousehold(): HasOne
{
return $this->hasOne(Household::class, 'head_user_id');
}
public function householdMemberships()
{
return $this->hasMany(HouseholdMember::class);
}
public function residentProfile(): HasOne
{
return $this->hasOne(ResidentProfile::class);
}
public function driverProfile(): HasOne
{
return $this->hasOne(DriverProfile::class);
}
public function helperProfile(): HasOne
{
return $this->hasOne(HelperProfile::class);
}
public function scannerProfile(): HasOne
{
return $this->hasOne(ScannerProfile::class);
}
public function storePartnerProfile(): HasOne
{
return $this->hasOne(StorePartnerProfile::class);
}
/**
* Resolve the role-specific profile relation name. Admins have no profile.
*/
public function profileRelation(): ?string
{
return match ($this->role) {
self::ROLE_RESIDENT => 'residentProfile',
self::ROLE_DRIVER => 'driverProfile',
self::ROLE_HELPER => 'helperProfile',
self::ROLE_SCANNER => 'scannerProfile',
self::ROLE_STORE_PARTNER => 'storePartnerProfile',
default => null,
};
}
/**
* Map of role => profile FQCN. Used for create-on-register.
*/
public static function profileModelForRole(string $role): ?string
{
return match ($role) {
self::ROLE_RESIDENT => ResidentProfile::class,
self::ROLE_DRIVER => DriverProfile::class,
self::ROLE_HELPER => HelperProfile::class,
self::ROLE_SCANNER => ScannerProfile::class,
self::ROLE_STORE_PARTNER => StorePartnerProfile::class,
default => null,
};
}
public function profile(): ?Model
{
$relation = $this->profileRelation();
return $relation ? $this->{$relation} : null;
}
}