diff --git a/app/Service/Import/TimeEntryDeduplicator.php b/app/Service/Import/TimeEntryDeduplicator.php index 0c612a79..5e6e4fff 100644 --- a/app/Service/Import/TimeEntryDeduplicator.php +++ b/app/Service/Import/TimeEntryDeduplicator.php @@ -4,8 +4,10 @@ declare(strict_types=1); namespace App\Service\Import; +use App\Models\Member; use App\Models\TimeEntry; use Illuminate\Support\Carbon; +use Illuminate\Support\Str; use RuntimeException; /** @@ -16,22 +18,41 @@ use RuntimeException; * an import are skipped and every further one is created. Re-importing the same data therefore creates nothing, * while identical time entries within one import are still kept. * - * Existing time entries are loaded lazily per member and UTC month of their start, so only the members and months an - * import touches are queried (backed by the (member_id, start) index). A member month is always loaded before the - * first time entry of that member month is created by the import, so time entries created by the import itself are - * never counted as existing. + * Members are compared by the email of their user, since the importers map users by email: members of the source + * that share an email (for example a placeholder and the real user it was created for) are merged into one member + * on import. Their existing time entries therefore have to be matched together, otherwise re-importing the data + * would create the time entries of all but one of these members again. + * + * Existing time entries are loaded lazily per member group (members with the same email) and UTC month of their + * start, so only the members and months an import touches are queried (backed by the (member_id, start) index). A + * group month is always loaded before the first time entry of that group month is created by the import, so time + * entries created by the import itself are never counted as existing. */ class TimeEntryDeduplicator { private const string DATE_FORMAT = 'Y-m-d H:i:s'; /** - * Remaining number of existing time entries per fingerprint, grouped by member and month ("|Y-m") + * Remaining number of existing time entries per fingerprint, grouped by member group and month ("|Y-m") * * @var array> */ private array $existingCounts = []; + /** + * Group key (lower case email of the user) per member ID of the organization, loaded on first use + * + * @var array|null + */ + private ?array $groupByMember = null; + + /** + * Member IDs per group key + * + * @var array> + */ + private array $membersByGroup = []; + public function __construct(private readonly string $organizationId) {} /** @@ -50,11 +71,11 @@ class TimeEntryDeduplicator return false; } - $memberId = $timeEntry->member_id; + $group = $this->getGroup($timeEntry->member_id); $month = substr($start, 0, 7); - $bucket = $memberId.'|'.$month; + $bucket = $group.'|'.$month; if (! isset($this->existingCounts[$bucket])) { - $this->existingCounts[$bucket] = $this->loadMemberMonth($memberId, $month); + $this->existingCounts[$bucket] = $this->loadGroupMonth($this->membersByGroup[$group], $month); } $fingerprint = $this->getFingerprint( @@ -76,10 +97,44 @@ class TimeEntryDeduplicator } /** + * Returns the group key of the member, members of the organization with the same email share a group + */ + private function getGroup(string $memberId): string + { + if ($this->groupByMember === null) { + $this->groupByMember = []; + $members = Member::query() + ->where('members.organization_id', '=', $this->organizationId) + ->join('users', 'users.id', '=', 'members.user_id') + ->toBase() + ->select(['members.id', 'users.email']) + ->get(); + foreach ($members as $member) { + /** @var object{id: string, email: string} $member */ + $group = 'email:'.Str::lower($member->email); + $this->groupByMember[$member->id] = $group; + $this->membersByGroup[$group][] = $member->id; + } + } + + if (! isset($this->groupByMember[$memberId])) { + // Note: This is a member the import created after the groups were loaded. The importers only create a + // member if no user with its email is in the organization yet, so it can not share a group with an + // existing member and has no existing time entries. + $group = 'member:'.$memberId; + $this->groupByMember[$memberId] = $group; + $this->membersByGroup[$group] = [$memberId]; + } + + return $this->groupByMember[$memberId]; + } + + /** + * @param list $memberIds * @param string $month Month in the format "Y-m" * @return array */ - private function loadMemberMonth(string $memberId, string $month): array + private function loadGroupMonth(array $memberIds, string $month): array { $monthStart = Carbon::createFromFormat('Y-m-d H:i:s', $month.'-01 00:00:00', 'UTC'); if ($monthStart === null) { @@ -92,7 +147,7 @@ class TimeEntryDeduplicator // raw attributes of the imported time entries. The cursor avoids holding all rows in memory at once. $rows = TimeEntry::query() ->where('organization_id', '=', $this->organizationId) - ->where('member_id', '=', $memberId) + ->whereIn('member_id', $memberIds) ->where('start', '>=', $monthStart->format(self::DATE_FORMAT)) ->where('start', '<', $monthEnd->format(self::DATE_FORMAT)) ->whereNotNull('end') diff --git a/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php b/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php index 398a53d9..204e6537 100644 --- a/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php +++ b/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php @@ -95,7 +95,7 @@ class SolidtimeImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(26, $queryLog); + $this->assertCount(27, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true); $this->checkTimeEntries($testScenario); $this->assertSame(2, $report->timeEntriesCreated); @@ -279,7 +279,7 @@ class SolidtimeImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(12, $queryLog); + $this->assertCount(13, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true); $this->checkTimeEntries($testScenario); $this->assertSame(0, $report->timeEntriesCreated); diff --git a/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php b/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php index 6ef9f008..5e9e8098 100644 --- a/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php +++ b/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php @@ -42,7 +42,7 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(23, $queryLog); + $this->assertCount(24, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); $this->checkTimeEntries($testScenario); $this->assertSame(2, $report->timeEntriesCreated); @@ -108,7 +108,7 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(13, $queryLog); + $this->assertCount(14, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); $this->checkTimeEntries($testScenario); $this->assertSame(0, $report->timeEntriesCreated); diff --git a/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php b/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php index 4c48b91c..5405e8e2 100644 --- a/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php +++ b/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php @@ -9,6 +9,7 @@ use App\Models\Member; use App\Models\Organization; use App\Models\Project; use App\Models\TimeEntry; +use App\Models\User; use App\Service\Import\TimeEntryDeduplicator; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Carbon; @@ -197,7 +198,8 @@ class TimeEntryDeduplicatorTest extends TestCase $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(3, $queryLog); + // One query for the member groups and one per member month + $this->assertCount(4, $queryLog); } public function test_only_loads_time_entries_of_the_member(): void @@ -216,4 +218,28 @@ class TimeEntryDeduplicatorTest extends TestCase // Assert $this->assertSame([false, true], $results); } + + public function test_matches_time_entries_of_members_with_the_same_email(): void + { + // Arrange + // The importers map users by email, so both members are merged into one member when the data is imported + $placeholder = User::factory()->placeholder()->create(['email' => 'peter@example.com']); + $placeholderMember = Member::factory()->forUser($placeholder)->forOrganization($this->organization)->create(); + $user = User::factory()->create(['email' => 'Peter@example.com']); + $userMember = Member::factory()->forUser($user)->forOrganization($this->organization)->create(); + $this->makeTimeEntry(attributes: ['member_id' => $placeholderMember->getKey(), 'user_id' => $placeholder->getKey()])->save(); + $this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey(), 'user_id' => $user->getKey()])->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $results = [ + $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])), + $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])), + $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])), + $deduplicator->claimExisting($this->makeTimeEntry()), + ]; + + // Assert + $this->assertSame([true, true, false, false], $results); + } }