Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app-modules/identity/src/User/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Carbon;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

Expand All @@ -34,6 +35,8 @@
* @property string $username
* @property string $email
* @property bool $is_donator
* @property Carbon $created_at
* @property Carbon $updated_at
*/
#[ObservedBy(UserObserver::class)]
final class User extends Authenticatable implements FilamentUser, HasMedia, HasName, HasTenants
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,19 @@ private function createIdentity(DiscordMessageDTO $dto, int $tenantId): External

private function resolveOrCreateUser(DiscordMessageDTO $dto): User
{
$existing = User::query()->where('username', $dto->authorUsername)->first();
$conflictingIds = ExternalIdentity::query()
->where('provider', IdentityProvider::Discord)
->where('external_account_id', '!=', $dto->authorDiscordId)
->where('model_type', (new User)->getMorphClass())
->pluck('model_id')
->all();

$existing = User::query()
->whereIn('username', [$dto->authorUsername, $dto->authorUsername.'#0'])
->when($conflictingIds !== [], fn ($q) => $q->whereNotIn('id', $conflictingIds))
->orderByRaw('CASE WHEN username = ? THEN 0 ELSE 1 END', [$dto->authorUsername])
->first();
Comment thread
gvieira18 marked this conversation as resolved.

if ($existing instanceof User) {
return $existing;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,17 @@
use He4rt\Identity\ExternalIdentity\Enums\IdentityProvider;
use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity;
use He4rt\Identity\User\Models\User;
use He4rt\IntegrationDiscord\ETL\DTOs\ConnectedAccountDTO;
use He4rt\IntegrationDiscord\ETL\DTOs\DiscordProfileDTO;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;

final class ImportDiscordProfileAction
{
public function handle(DiscordProfileDTO $dto, int $tenantId): ExternalIdentity
{
$user = User::query()->where('username', $dto->username)->first();

if (!$user instanceof User) {
$name = User::query()->where('name', $dto->name)->exists()
? $dto->username
: $dto->name;

$user = User::query()->create([
'id' => Uuid::uuid4()->toString(),
'username' => $dto->username,
'name' => $name,
'is_donator' => false,
]);
}

$user = $this->resolveUser($dto, $tenantId);
$user->tenants()->syncWithoutDetaching([$tenantId]);

$discordIdentity = ExternalIdentity::query()->updateOrCreate(
Expand All @@ -52,24 +40,109 @@ public function handle(DiscordProfileDTO $dto, int $tenantId): ExternalIdentity
);

foreach ($dto->connectedAccounts as $account) {
ExternalIdentity::query()->updateOrCreate(
[
'provider' => $account->provider,
'external_account_id' => $account->externalAccountId,
'tenant_id' => $tenantId,
],
[
'model_type' => (new User)->getMorphClass(),
'model_id' => $user->id,
'type' => $account->provider->getType(),
'credentials_type' => CredentialsType::OAuth2,
'credentials' => ClientAccessManager::make(),
'connected_at' => $dto->joinedAt ? Date::parse($dto->joinedAt) : null,
'metadata' => $account->metadata,
]
);
$this->upsertConnectedAccount($account, $user, $tenantId, $dto);
}

return $discordIdentity;
}

private function resolveUser(DiscordProfileDTO $dto, int $tenantId): User
{
$identity = ExternalIdentity::query()
->where('provider', IdentityProvider::Discord)
->where('external_account_id', $dto->discordId)
->where('tenant_id', $tenantId)
->first();

if ($identity instanceof ExternalIdentity) {
$owner = $identity->user;
if ($owner instanceof User) {
return $this->syncUserAttributes($owner, $dto);
}
}

$user = User::query()->where('username', $dto->username)->first();
if ($user instanceof User) {
return $user;
}

$name = User::query()->where('name', $dto->name)->exists()
? $dto->username
: $dto->name;

return User::query()->create([
'id' => Uuid::uuid7(),
'username' => $dto->username,
'name' => $name,
'is_donator' => false,
]);
Comment thread
gvieira18 marked this conversation as resolved.
}

private function syncUserAttributes(User $user, DiscordProfileDTO $dto): User
{
$changes = [];

$usernameChanged = $user->username !== $dto->username
&& !User::query()
->where('username', $dto->username)
->where('id', '!=', $user->id)
->exists();

if ($usernameChanged) {
$changes['username'] = $dto->username;
}

if ($user->name === $user->username && $dto->name !== $dto->username) {
$changes['name'] = $dto->name;
}

if ($changes !== []) {
$user->update($changes);
}

return $user;
}

private function upsertConnectedAccount(
ConnectedAccountDTO $account,
User $user,
int $tenantId,
DiscordProfileDTO $dto,
): void {
$existing = ExternalIdentity::query()
->where('provider', $account->provider)
->where('external_account_id', $account->externalAccountId)
->where('tenant_id', $tenantId)
->first();

if ($existing instanceof ExternalIdentity && (string) $existing->model_id !== (string) $user->id) {
Log::warning('discord-profile-import skipped connected account: belongs to other user', [
'discord_id' => $dto->discordId,
'discord_username' => $dto->username,
'provider' => $account->provider->value,
'external_account_id' => $account->externalAccountId,
'owner_user_id' => $existing->model_id,
'tried_user_id' => $user->id,
]);

return;
}

ExternalIdentity::query()->updateOrCreate(
[
'provider' => $account->provider,
'external_account_id' => $account->externalAccountId,
'tenant_id' => $tenantId,
],
[
'model_type' => (new User)->getMorphClass(),
'model_id' => $user->id,
'type' => $account->provider->getType(),
'credentials_type' => CredentialsType::OAuth2,
'credentials' => ClientAccessManager::make(),
'connected_at' => $dto->joinedAt ? Date::parse($dto->joinedAt) : null,
'metadata' => $account->metadata,
],
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

declare(strict_types=1);

namespace He4rt\IntegrationDiscord\ETL\Actions;

use He4rt\Identity\ExternalIdentity\Models\ExternalIdentity;
use He4rt\Identity\User\Models\User;
use Illuminate\Support\Facades\DB;

final class MergeDuplicateDiscordUserAction
{
/**
* Move all identities and FKs from $newUser to $oldUser, then delete $newUser.
* Updates $oldUser->username to $targetUsername (current Discord handle).
*
* @return array{moved_identities: int, moved_fks: array<string, int>}
*/
public function handle(User $oldUser, User $newUser, string $targetUsername): array
{
return DB::transaction(function () use ($oldUser, $newUser, $targetUsername): array {
$movedIdentities = ExternalIdentity::query()
->where('model_id', $newUser->id)
->update(['model_id' => $oldUser->id]);

ExternalIdentity::query()
->where('connected_by', $newUser->id)
->update(['connected_by' => $oldUser->id]);

$fkMoves = $this->reassignFkRelations($oldUser, $newUser);

$this->mergeOneToOneRelations($oldUser, $newUser);

$this->mergePivotTable('tenant_users', 'tenant_id', $oldUser, $newUser);

$newUser->delete();

if ($oldUser->username !== $targetUsername) {
$taken = User::query()
->where('username', $targetUsername)
->where('id', '!=', $oldUser->id)
->exists();

if (!$taken) {
$oldUser->update(['username' => $targetUsername]);
}
}

return [
'moved_identities' => $movedIdentities,
'moved_fks' => $fkMoves,
];
});
}

/**
* @return array<string, int>
*/
private function reassignFkRelations(User $old, User $new): array
{
$simpleUserIdTables = [
'characters',
'events_talks',
'event_submission_speakers',
'events_attendees',
'meeting_participants',
];

$stats = [];

foreach ($simpleUserIdTables as $table) {
$stats[$table] = DB::table($table)
->where('user_id', $new->id)
->update(['user_id' => $old->id]);
}
Comment thread
gvieira18 marked this conversation as resolved.

$stats['meetings'] = DB::table('meetings')
->where('admin_id', $new->id)
->update(['admin_id' => $old->id]);

$stats['tenants'] = DB::table('tenants')
->where('owner_id', $new->id)
->update(['owner_id' => $old->id]);

$stats['feedbacks_target'] = DB::table('feedbacks')
->where('target_id', $new->id)
->update(['target_id' => $old->id]);

$stats['feedbacks_sender'] = DB::table('feedbacks')
->where('sender_id', $new->id)
->update(['sender_id' => $old->id]);

$stats['feedback_reviews'] = DB::table('feedback_reviews')
->where('staff_id', $new->id)
->update(['staff_id' => $old->id]);

return $stats;
}

private function mergeOneToOneRelations(User $old, User $new): void
{
foreach (['user_address', 'user_information'] as $table) {
$oldHas = DB::table($table)->where('user_id', $old->id)->exists();
$newHas = DB::table($table)->where('user_id', $new->id)->exists();

if ($oldHas && $newHas) {
DB::table($table)->where('user_id', $new->id)->delete();
} elseif ($newHas) {
DB::table($table)->where('user_id', $new->id)->update(['user_id' => $old->id]);
}
}
}

private function mergePivotTable(string $table, string $otherKey, User $old, User $new): void
{
$oldKeys = DB::table($table)
->where('user_id', $old->id)
->pluck($otherKey)
->all();

if ($oldKeys !== []) {
DB::table($table)
->where('user_id', $new->id)
->whereIn($otherKey, $oldKeys)
->delete();
}

DB::table($table)
->where('user_id', $new->id)
->update(['user_id' => $old->id]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ public function handle(
}
}

foreach (array_chunk($dtos, 100) as $dtoBatch) {
foreach (array_chunk($dtos, 250) as $dtoBatch) {
if ($limit !== null && $stats['messages'] >= $limit) {
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public function handle(ImportDiscordProfileAction $action): int
$profileSection->clear();
$this->renderBox($profileSection, $profileTitle, $profileCurrent, $totalProfiles);

foreach (array_chunk($profiles, 100) as $batch) {
foreach (array_chunk($profiles, 250) as $batch) {
DB::transaction(function () use (
$batch, $action, $tenantId, $chunkName,
&$stats, &$errorSamples, &$profileCurrent, $totalProfiles,
Expand Down
Loading