feat: person identity matching with detection, confirmation and audit trail

Implements enterprise-grade identity resolution (detect → suggest → confirm)
for Person ↔ User linking. Matches are detected automatically on person
creation and user account creation, then surfaced to organisers for explicit
confirmation or dismissal. No silent auto-linking.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-10 12:50:25 +02:00
parent 239fe57a11
commit 4b182b449a
20 changed files with 1463 additions and 2 deletions

View File

@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum IdentityMatchConfidence: string
{
case EXACT = 'exact';
case FUZZY = 'fuzzy';
}

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum IdentityMatchMethod: string
{
case EMAIL = 'email';
case PHONE = 'phone';
case MANUAL = 'manual';
}

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum IdentityMatchStatus: string
{
case PENDING = 'pending';
case CONFIRMED = 'confirmed';
case DISMISSED = 'dismissed';
}

View File

@@ -11,17 +11,22 @@ use App\Http\Resources\Api\V1\PersonCollection;
use App\Http\Resources\Api\V1\PersonResource;
use App\Models\Event;
use App\Models\Person;
use App\Services\PersonIdentityService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
final class PersonController extends Controller
{
public function __construct(
private readonly PersonIdentityService $identityService,
) {}
public function index(Request $request, Event $event): PersonCollection
{
Gate::authorize('viewAny', [Person::class, $event]);
$query = $event->persons()->with('crowdType');
$query = $event->persons()->with(['crowdType', 'pendingIdentityMatch.matchedUser']);
if ($request->filled('crowd_type_id')) {
$query->where('crowd_type_id', $request->input('crowd_type_id'));
@@ -72,6 +77,8 @@ final class PersonController extends Controller
$person = $event->persons()->create($request->validated());
$this->identityService->detectMatchForPerson($person);
return $this->created(new PersonResource($person->fresh()->load('crowdType')));
}

View File

@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\BulkConfirmIdentityMatchesRequest;
use App\Http\Resources\Api\V1\PersonIdentityMatchResource;
use App\Models\Organisation;
use App\Models\Person;
use App\Models\PersonIdentityMatch;
use App\Services\PersonIdentityService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Gate;
final class PersonIdentityMatchController extends Controller
{
public function __construct(
private readonly PersonIdentityService $identityService,
) {}
public function index(Request $request, Organisation $organisation): AnonymousResourceCollection
{
Gate::authorize('viewAny', [PersonIdentityMatch::class, $organisation]);
$eventIds = $organisation->events()->pluck('id');
$matches = PersonIdentityMatch::pending()
->whereHas('person', fn ($q) => $q->whereIn('event_id', $eventIds))
->with(['person.crowdType', 'person.event', 'matchedUser'])
->orderBy('created_at', 'desc')
->paginate(25);
return PersonIdentityMatchResource::collection($matches);
}
public function showForPerson(Organisation $organisation, Person $person): PersonIdentityMatchResource
{
Gate::authorize('view', [$person, $person->event]);
$match = $person->pendingIdentityMatch()
->with('matchedUser')
->firstOrFail();
return new PersonIdentityMatchResource($match);
}
public function confirm(Request $request, Organisation $organisation, PersonIdentityMatch $personIdentityMatch): JsonResponse
{
Gate::authorize('confirm', $personIdentityMatch);
try {
$this->identityService->confirmMatch($personIdentityMatch, $request->user());
} catch (\DomainException $e) {
return $this->error($e->getMessage(), 422);
}
$personIdentityMatch->refresh()->load(['person.crowdType', 'person.event', 'matchedUser', 'resolvedBy']);
return $this->success(new PersonIdentityMatchResource($personIdentityMatch));
}
public function dismiss(Request $request, Organisation $organisation, PersonIdentityMatch $personIdentityMatch): JsonResponse
{
Gate::authorize('dismiss', $personIdentityMatch);
try {
$this->identityService->dismissMatch($personIdentityMatch, $request->user());
} catch (\DomainException $e) {
return $this->error($e->getMessage(), 422);
}
$personIdentityMatch->refresh()->load(['person.crowdType', 'person.event', 'matchedUser', 'resolvedBy']);
return $this->success(new PersonIdentityMatchResource($personIdentityMatch));
}
public function bulkConfirm(BulkConfirmIdentityMatchesRequest $request, Organisation $organisation): JsonResponse
{
Gate::authorize('bulkConfirm', [PersonIdentityMatch::class, $organisation]);
$matches = PersonIdentityMatch::whereIn('id', $request->validated('match_ids'))
->with('person')
->get()
->keyBy('id');
$confirmed = 0;
$errors = [];
foreach ($request->validated('match_ids') as $matchId) {
$match = $matches->get($matchId);
if ($match === null) {
$errors[] = ['match_id' => $matchId, 'error' => 'Match not found.'];
continue;
}
$response = Gate::inspect('update', [$match->person, $match->person->event]);
if ($response->denied()) {
$errors[] = ['match_id' => $matchId, 'error' => 'Unauthorized.'];
continue;
}
try {
$this->identityService->confirmMatch($match, $request->user());
$confirmed++;
} catch (\DomainException $e) {
$errors[] = ['match_id' => $matchId, 'error' => $e->getMessage()];
}
}
return response()->json([
'confirmed' => $confirmed,
'errors' => $errors,
]);
}
}

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\V1;
use Illuminate\Foundation\Http\FormRequest;
final class BulkConfirmIdentityMatchesRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'match_ids' => ['required', 'array', 'min:1', 'max:100'],
'match_ids.*' => ['required', 'string', 'exists:person_identity_matches,id'],
];
}
}

View File

@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api\V1;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
final class PersonIdentityMatchResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'person' => [
'id' => $this->person->id,
'name' => $this->person->name,
'email' => $this->person->email,
'crowd_type' => $this->whenLoaded('person', fn () =>
$this->person->crowdType?->name
),
'event' => $this->whenLoaded('person', fn () => [
'id' => $this->person->event_id,
'name' => $this->person->event?->name,
]),
],
'matched_user' => [
'id' => $this->matchedUser->id,
'name' => $this->matchedUser->name,
'email' => $this->matchedUser->email,
],
'matched_on' => $this->matched_on->value,
'confidence' => $this->confidence->value,
'status' => $this->status->value,
'resolved_by' => $this->when($this->resolvedBy, fn () => [
'id' => $this->resolvedBy->id,
'name' => $this->resolvedBy->name,
]),
'resolved_at' => $this->resolved_at?->toISOString(),
'created_at' => $this->created_at->toISOString(),
];
}
}

View File

@@ -24,6 +24,23 @@ final class PersonResource extends JsonResource
'created_at' => $this->created_at->toIso8601String(),
'crowd_type' => new CrowdTypeResource($this->whenLoaded('crowdType')),
'company' => new CompanyResource($this->whenLoaded('company')),
'pending_identity_match' => $this->when(
$this->relationLoaded('pendingIdentityMatch') && $this->pendingIdentityMatch,
function () {
$match = $this->pendingIdentityMatch;
return [
'match_id' => $match->id,
'matched_user' => [
'id' => $match->matchedUser->id,
'name' => $match->matchedUser->name,
'email' => $match->matchedUser->email,
],
'matched_on' => $match->matched_on->value,
'confidence' => $match->confidence->value,
];
}
),
'tags' => $this->when(
$this->user_id && $this->relationLoaded('user'),
function () {

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Models;
use App\Enums\IdentityMatchStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -11,6 +12,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
final class Person extends Model
@@ -74,6 +76,17 @@ final class Person extends Model
return $this->hasMany(ShiftAssignment::class);
}
public function identityMatches(): HasMany
{
return $this->hasMany(PersonIdentityMatch::class);
}
public function pendingIdentityMatch(): HasOne
{
return $this->hasOne(PersonIdentityMatch::class)
->where('status', IdentityMatchStatus::PENDING);
}
public function scopeApproved(Builder $query): Builder
{
return $query->where('status', 'approved');

View File

@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\IdentityMatchConfidence;
use App\Enums\IdentityMatchMethod;
use App\Enums\IdentityMatchStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class PersonIdentityMatch extends Model
{
use HasFactory;
use HasUlids;
public const UPDATED_AT = null;
protected $fillable = [
'person_id',
'matched_user_id',
'matched_on',
'confidence',
'status',
'resolved_by_user_id',
'resolved_at',
];
protected function casts(): array
{
return [
'matched_on' => IdentityMatchMethod::class,
'confidence' => IdentityMatchConfidence::class,
'status' => IdentityMatchStatus::class,
'resolved_at' => 'datetime',
];
}
public function person(): BelongsTo
{
return $this->belongsTo(Person::class);
}
public function matchedUser(): BelongsTo
{
return $this->belongsTo(User::class, 'matched_user_id');
}
public function resolvedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'resolved_by_user_id');
}
public function scopePending(Builder $query): Builder
{
return $query->where('status', IdentityMatchStatus::PENDING);
}
public function scopeConfirmed(Builder $query): Builder
{
return $query->where('status', IdentityMatchStatus::CONFIRMED);
}
public function scopeDismissed(Builder $query): Builder
{
return $query->where('status', IdentityMatchStatus::DISMISSED);
}
}

View File

@@ -64,6 +64,11 @@ final class User extends Authenticatable
return $this->hasMany(UserInvitation::class, 'invited_by_user_id');
}
public function identityMatches(): HasMany
{
return $this->hasMany(PersonIdentityMatch::class, 'matched_user_id');
}
public function organisationTags(): HasMany
{
return $this->hasMany(UserOrganisationTag::class);

View File

@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace App\Policies;
use App\Models\Organisation;
use App\Models\PersonIdentityMatch;
use App\Models\User;
final class PersonIdentityMatchPolicy
{
public function viewAny(User $user, Organisation $organisation): bool
{
return $user->hasRole('super_admin')
|| $organisation->users()->where('user_id', $user->id)->exists();
}
public function view(User $user, PersonIdentityMatch $match): bool
{
$match->loadMissing('person.event.organisation');
$person = $match->person;
return $user->hasRole('super_admin')
|| $person->event->organisation->users()->where('user_id', $user->id)->exists();
}
public function confirm(User $user, PersonIdentityMatch $match): bool
{
return $this->canManageMatch($user, $match);
}
public function dismiss(User $user, PersonIdentityMatch $match): bool
{
return $this->canManageMatch($user, $match);
}
public function bulkConfirm(User $user, Organisation $organisation): bool
{
return $user->hasRole('super_admin')
|| $organisation->users()->where('user_id', $user->id)->exists();
}
private function canManageMatch(User $user, PersonIdentityMatch $match): bool
{
$match->loadMissing('person.event.organisation');
$event = $match->person->event;
if ($user->hasRole('super_admin')) {
return true;
}
$isOrgAdmin = $event->organisation->users()
->where('user_id', $user->id)
->wherePivot('role', 'org_admin')
->exists();
if ($isOrgAdmin) {
return true;
}
return $event->users()
->where('user_id', $user->id)
->wherePivot('role', 'event_manager')
->exists();
}
}

View File

@@ -81,6 +81,8 @@ final class InvitationService
'password' => $password,
'email_verified_at' => now(),
]);
app(PersonIdentityService::class)->detectMatchesForUser($user);
}
$organisation = $invitation->organisation;

View File

@@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Enums\IdentityMatchConfidence;
use App\Enums\IdentityMatchMethod;
use App\Enums\IdentityMatchStatus;
use App\Models\Person;
use App\Models\PersonIdentityMatch;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final class PersonIdentityService
{
/**
* Detect if a person's email matches an existing user account.
* Called after a person is created. Does NOT auto-link.
*/
public function detectMatchForPerson(Person $person): ?PersonIdentityMatch
{
// Guard 1: Person already linked to a user
if ($person->user_id !== null) {
return null;
}
// Guard 2: Person has no email
if ($person->email === null || trim($person->email) === '') {
return null;
}
// Guard 3: Person is soft-deleted
if ($person->trashed()) {
return null;
}
// Guard 4: Find user with matching normalised email.
// StorePersonRequest validates 'email' as required + email format but does not
// enforce lowercase. User emails are also not guaranteed lowercase. We use
// LOWER() on both sides as a safety net for case-insensitive matching.
$normalised = strtolower(trim($person->email));
$user = User::whereRaw('LOWER(email) = ?', [$normalised])->first();
if ($user === null) {
return null;
}
// Guard 5: User already has a person record in the same event
// (would violate UNIQUE(event_id, user_id) WHERE user_id IS NOT NULL)
$alreadyLinkedInEvent = Person::where('event_id', $person->event_id)
->where('user_id', $user->id)
->exists();
if ($alreadyLinkedInEvent) {
return null;
}
// Guard 6: Match record already exists — return existing (idempotent)
$existing = PersonIdentityMatch::where('person_id', $person->id)
->where('matched_user_id', $user->id)
->first();
if ($existing !== null) {
return $existing;
}
$match = PersonIdentityMatch::create([
'person_id' => $person->id,
'matched_user_id' => $user->id,
'matched_on' => IdentityMatchMethod::EMAIL,
'confidence' => IdentityMatchConfidence::EXACT,
'status' => IdentityMatchStatus::PENDING,
]);
$activityLogger = activity('identity')
->performedOn($person)
->withProperties([
'matched_user_id' => $user->id,
'matched_on' => IdentityMatchMethod::EMAIL->value,
'confidence' => IdentityMatchConfidence::EXACT->value,
]);
if (auth()->user()) {
$activityLogger->causedBy(auth()->user());
}
$activityLogger->log('person.identity.match_detected');
return $match;
}
/**
* Detect all unlinked persons matching a user's email.
* Called after a user account is created. Creates pending matches.
* Returns the number of matches created.
*/
public function detectMatchesForUser(User $user): int
{
// 1. Fetch all matching unlinked persons
// Person uses SoftDeletes, so trashed records are automatically excluded by Eloquent.
$normalised = strtolower(trim($user->email));
$persons = Person::whereNull('user_id')
->whereRaw('LOWER(email) = ?', [$normalised])
->get();
if ($persons->isEmpty()) {
return 0;
}
// 2. Batch-check which events already have this user linked (no N+1)
$alreadyLinkedEventIds = Person::where('user_id', $user->id)
->whereIn('event_id', $persons->pluck('event_id'))
->pluck('event_id')
->toArray();
// 3. Batch-check existing match records (no N+1)
$existingMatchPersonIds = PersonIdentityMatch::where('matched_user_id', $user->id)
->whereIn('person_id', $persons->pluck('id'))
->pluck('person_id')
->toArray();
// 4. Filter — no queries inside this loop
$toCreate = $persons
->reject(fn (Person $p) => in_array($p->event_id, $alreadyLinkedEventIds))
->reject(fn (Person $p) => in_array($p->id, $existingMatchPersonIds));
// 5. Create matches
foreach ($toCreate as $person) {
PersonIdentityMatch::create([
'person_id' => $person->id,
'matched_user_id' => $user->id,
'matched_on' => IdentityMatchMethod::EMAIL,
'confidence' => IdentityMatchConfidence::EXACT,
'status' => IdentityMatchStatus::PENDING,
]);
$activityLogger = activity('identity')
->performedOn($person)
->withProperties([
'matched_user_id' => $user->id,
'matched_on' => IdentityMatchMethod::EMAIL->value,
'confidence' => IdentityMatchConfidence::EXACT->value,
]);
if (auth()->user()) {
$activityLogger->causedBy(auth()->user());
}
$activityLogger->log('person.identity.match_detected');
}
return $toCreate->count();
}
/**
* Confirm a match: link the person to the matched user.
*
* @throws \DomainException if match is not pending or would violate uniqueness
*/
public function confirmMatch(PersonIdentityMatch $match, User $resolvedBy): void
{
if ($match->status !== IdentityMatchStatus::PENDING) {
throw new \DomainException('Match is not pending and cannot be confirmed.');
}
// Safety check: no duplicate user_id in the same event
$person = $match->person;
$conflict = Person::where('event_id', $person->event_id)
->where('user_id', $match->matched_user_id)
->exists();
if ($conflict) {
throw new \DomainException('User already has a person record in this event.');
}
DB::transaction(function () use ($match, $person, $resolvedBy): void {
$match->update([
'status' => IdentityMatchStatus::CONFIRMED,
'resolved_by_user_id' => $resolvedBy->id,
'resolved_at' => now(),
]);
$person->update([
'user_id' => $match->matched_user_id,
]);
});
activity('identity')
->causedBy($resolvedBy)
->performedOn($person)
->withProperties([
'match_id' => $match->id,
'old' => ['user_id' => null],
'new' => ['user_id' => $match->matched_user_id],
])
->log('person.identity.match_confirmed');
}
/**
* Dismiss a match: mark as dismissed so it's not shown again.
*
* @throws \DomainException if match is not pending
*/
public function dismissMatch(PersonIdentityMatch $match, User $resolvedBy): void
{
if ($match->status !== IdentityMatchStatus::PENDING) {
throw new \DomainException('Match is not pending and cannot be dismissed.');
}
$match->update([
'status' => IdentityMatchStatus::DISMISSED,
'resolved_by_user_id' => $resolvedBy->id,
'resolved_at' => now(),
]);
activity('identity')
->causedBy($resolvedBy)
->performedOn($match->person)
->withProperties(['match_id' => $match->id])
->log('person.identity.match_dismissed');
}
}