Files
Verde-Web/app/Services/Scan/ScanService.php
admin 8643057c81 feat(backend): complete Module 11 (scanning + collection logs)
collection_logs table. ScanService validates code state (active only;
used = duplicate, expired = expired, unassigned/allocated = invalid),
geo proximity (≤200m from DOP via ST_Distance_Sphere), then atomically
transitions code -> Used and writes a CollectionLog. Scans inside a
trip context bump trip_stop.total_scans + emit qr_scanned timeline event.
Bulk scan endpoint processes each scan independently for offline sync.
Triggers QrBalanceLow when household active count drops below threshold.

155 feature tests passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 02:53:25 +08:00

129 lines
4.3 KiB
PHP

<?php
namespace App\Services\Scan;
use App\Models\CollectionLog;
use App\Models\DropOffPoint;
use App\Models\QrCode;
use App\Models\Trip;
use App\Models\TripStop;
use App\Models\User;
use App\Services\Qr\QrAllocator;
use App\Services\Trip\TripExecutor;
use App\States\QrCode\Active;
use App\States\QrCode\Used;
use Illuminate\Support\Facades\DB;
use MatanYadaev\EloquentSpatial\Objects\Point;
class ScanService
{
public const MAX_DISTANCE_METERS = 200;
public function __construct(
private readonly TripExecutor $tripExecutor,
private readonly QrAllocator $qrAllocator,
) {}
/**
* Validate + record a scan. Returns ScanResult with status and optional
* CollectionLog. Transitions code unassigned -> won't happen (rejected).
* Active -> Used. Writes timeline event when trip context provided.
*/
public function scan(
string $serial,
DropOffPoint $dropOff,
User $scanner,
float $lat,
float $lng,
?Trip $trip = null,
?TripStop $tripStop = null,
?int $weightKg = null,
?string $wasteType = null,
?string $photoPath = null,
?string $notes = null,
?\DateTimeInterface $scannedAt = null,
): ScanResult {
$code = QrCode::where('serial', $serial)->first();
$when = $scannedAt ?? now();
if (! $code) {
return ScanResult::reject('not_found');
}
$statusName = (string) $code->status;
if ($statusName === Used::$name) {
return ScanResult::reject('duplicate', $code, CollectionLog::STATUS_DUPLICATE);
}
if ($statusName !== Active::$name) {
return ScanResult::reject('invalid_state:'.$statusName, $code, CollectionLog::STATUS_INVALID);
}
if ($code->expires_at && $code->expires_at->isPast()) {
return ScanResult::reject('expired', $code, CollectionLog::STATUS_EXPIRED);
}
// Geo proximity check
if ($dropOff->coordinates) {
$row = DB::selectOne(
'SELECT ST_Distance_Sphere(coordinates, ST_SRID(POINT(?, ?), 4326)) AS m FROM drop_off_points WHERE id = ?',
[$lng, $lat, $dropOff->id],
);
$distance = (float) ($row->m ?? 999999);
if ($distance > self::MAX_DISTANCE_METERS) {
return ScanResult::reject('out_of_range:'.(int) $distance.'m', $code, CollectionLog::STATUS_INVALID);
}
}
return DB::transaction(function () use (
$code, $dropOff, $scanner, $lat, $lng, $trip, $tripStop,
$weightKg, $wasteType, $photoPath, $notes, $when,
) {
$code->status->transitionTo(Used::class);
$code->forceFill([
'used_at' => $when,
'used_at_drop_off_id' => $dropOff->id,
'scanned_by_user_id' => $scanner->id,
])->save();
$log = CollectionLog::create([
'qr_code_id' => $code->id,
'household_id' => $code->assigned_to_household_id,
'drop_off_point_id' => $dropOff->id,
'scanned_by_user_id' => $scanner->id,
'trip_id' => $trip?->id,
'trip_stop_id' => $tripStop?->id,
'scanned_at' => $when,
'coordinates_at_scan' => new Point($lat, $lng, 4326),
'weight_kg' => $weightKg,
'waste_type' => $wasteType,
'photo_path' => $photoPath,
'notes' => $notes,
'verification_status' => CollectionLog::STATUS_VALID,
]);
if ($tripStop) {
$tripStop->increment('total_scans');
}
if ($trip) {
$this->tripExecutor->log(
$trip,
\App\Models\TripTimelineEvent::TYPE_QR_SCANNED,
$scanner,
$lat, $lng,
relatedType: CollectionLog::class,
relatedId: $log->id,
metadata: ['serial' => $code->serial],
);
}
// Notify if household balance is low after this scan
if ($code->household) {
$this->qrAllocator->notifyBalanceIfLow($code->household);
}
return ScanResult::accepted($code->fresh(), $log);
});
}
}