diff --git a/app/Http/Resources/V1/Import/ImportResource.php b/app/Http/Resources/V1/Import/ImportResource.php index e5928861..b42c8911 100644 --- a/app/Http/Resources/V1/Import/ImportResource.php +++ b/app/Http/Resources/V1/Import/ImportResource.php @@ -41,6 +41,7 @@ class ImportResource extends BaseResource * }, * time_entries: array{ * created: int, + * skipped: int, * }, * tags: array{ * created: int, diff --git a/app/Service/Import/Importers/ClockifyTimeEntriesImporter.php b/app/Service/Import/Importers/ClockifyTimeEntriesImporter.php index 62b78fa5..19197290 100644 --- a/app/Service/Import/Importers/ClockifyTimeEntriesImporter.php +++ b/app/Service/Import/Importers/ClockifyTimeEntriesImporter.php @@ -203,6 +203,9 @@ class ClockifyTimeEntriesImporter extends DefaultImporter $member, $this->organization ); + if ($this->skipIfAlreadyExists($timeEntry)) { + continue; + } $timeEntry->save(); $this->timeEntriesCreated++; } diff --git a/app/Service/Import/Importers/DefaultImporter.php b/app/Service/Import/Importers/DefaultImporter.php index 35d08751..799b2c70 100644 --- a/app/Service/Import/Importers/DefaultImporter.php +++ b/app/Service/Import/Importers/DefaultImporter.php @@ -12,10 +12,12 @@ use App\Models\Project; use App\Models\ProjectMember; use App\Models\Tag; use App\Models\Task; +use App\Models\TimeEntry; use App\Models\User; use App\Service\BillableRateService; use App\Service\ColorService; use App\Service\Import\ImportDatabaseHelper; +use App\Service\Import\TimeEntryDeduplicator; use App\Service\TimezoneService; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\Validator; @@ -60,6 +62,10 @@ abstract class DefaultImporter implements ImporterContract protected int $timeEntriesCreated; + protected int $timeEntriesSkipped; + + protected TimeEntryDeduplicator $timeEntryDeduplicator; + protected ColorService $colorService; protected TimezoneService $timezoneService; @@ -205,6 +211,8 @@ abstract class DefaultImporter implements ImporterContract ], ]); $this->timeEntriesCreated = 0; + $this->timeEntriesSkipped = 0; + $this->timeEntryDeduplicator = new TimeEntryDeduplicator($organization->getKey()); $this->colorService = app(ColorService::class); $this->timezoneService = app(TimezoneService::class); } @@ -266,6 +274,21 @@ abstract class DefaultImporter implements ImporterContract } } + /** + * Returns true if an equal time entry already exists in the organization, for example because the same data was + * imported before. The time entry is counted as skipped and should not be saved. + */ + protected function skipIfAlreadyExists(TimeEntry $timeEntry): bool + { + if ($this->timeEntryDeduplicator->claimExisting($timeEntry)) { + $this->timeEntriesSkipped++; + + return true; + } + + return false; + } + #[Override] public function getReport(): ReportDto { @@ -274,6 +297,7 @@ abstract class DefaultImporter implements ImporterContract projectsCreated: $this->projectImportHelper->getCreatedCount(), tasksCreated: $this->taskImportHelper->getCreatedCount(), timeEntriesCreated: $this->timeEntriesCreated, + timeEntriesSkipped: $this->timeEntriesSkipped, tagsCreated: $this->tagImportHelper->getCreatedCount(), usersCreated: $this->userImportHelper->getCreatedCount(), ); diff --git a/app/Service/Import/Importers/GenericTimeEntriesImporter.php b/app/Service/Import/Importers/GenericTimeEntriesImporter.php index 16ac35ad..30df589d 100644 --- a/app/Service/Import/Importers/GenericTimeEntriesImporter.php +++ b/app/Service/Import/Importers/GenericTimeEntriesImporter.php @@ -167,6 +167,9 @@ class GenericTimeEntriesImporter extends DefaultImporter $member, $this->organization ); + if ($this->skipIfAlreadyExists($timeEntry)) { + continue; + } $timeEntry->save(); $this->timeEntriesCreated++; } diff --git a/app/Service/Import/Importers/HarvestTimeEntriesImporter.php b/app/Service/Import/Importers/HarvestTimeEntriesImporter.php index df708c44..b7a988c4 100644 --- a/app/Service/Import/Importers/HarvestTimeEntriesImporter.php +++ b/app/Service/Import/Importers/HarvestTimeEntriesImporter.php @@ -149,6 +149,9 @@ class HarvestTimeEntriesImporter extends DefaultImporter $member, $this->organization ); + if ($this->skipIfAlreadyExists($timeEntry)) { + continue; + } $timeEntry->save(); $this->timeEntriesCreated++; } diff --git a/app/Service/Import/Importers/ReportDto.php b/app/Service/Import/Importers/ReportDto.php index b3896eff..710ebd30 100644 --- a/app/Service/Import/Importers/ReportDto.php +++ b/app/Service/Import/Importers/ReportDto.php @@ -14,16 +14,19 @@ class ReportDto public int $timeEntriesCreated; + public int $timeEntriesSkipped; + public int $tagsCreated; public int $usersCreated; - public function __construct(int $clientsCreated, int $projectsCreated, int $tasksCreated, int $timeEntriesCreated, int $tagsCreated, int $usersCreated) + public function __construct(int $clientsCreated, int $projectsCreated, int $tasksCreated, int $timeEntriesCreated, int $timeEntriesSkipped, int $tagsCreated, int $usersCreated) { $this->clientsCreated = $clientsCreated; $this->projectsCreated = $projectsCreated; $this->tasksCreated = $tasksCreated; $this->timeEntriesCreated = $timeEntriesCreated; + $this->timeEntriesSkipped = $timeEntriesSkipped; $this->tagsCreated = $tagsCreated; $this->usersCreated = $usersCreated; } @@ -47,6 +50,7 @@ class ReportDto * }, * time_entries: array{ * created: int, + * skipped: int, * }, * tags: array{ * created: int, @@ -70,6 +74,7 @@ class ReportDto ], 'time_entries' => [ 'created' => $this->timeEntriesCreated, + 'skipped' => $this->timeEntriesSkipped, ], 'tags' => [ 'created' => $this->tagsCreated, diff --git a/app/Service/Import/Importers/SolidtimeImporter.php b/app/Service/Import/Importers/SolidtimeImporter.php index 102bf0e7..4fceac86 100644 --- a/app/Service/Import/Importers/SolidtimeImporter.php +++ b/app/Service/Import/Importers/SolidtimeImporter.php @@ -337,6 +337,9 @@ class SolidtimeImporter extends DefaultImporter $member, $this->organization ); + if ($this->skipIfAlreadyExists($timeEntry)) { + continue; + } $timeEntry->save(); $this->timeEntriesCreated++; } diff --git a/app/Service/Import/Importers/TogglTimeEntriesImporter.php b/app/Service/Import/Importers/TogglTimeEntriesImporter.php index 2784b509..f74fe6c7 100644 --- a/app/Service/Import/Importers/TogglTimeEntriesImporter.php +++ b/app/Service/Import/Importers/TogglTimeEntriesImporter.php @@ -151,6 +151,9 @@ class TogglTimeEntriesImporter extends DefaultImporter $member, $this->organization ); + if ($this->skipIfAlreadyExists($timeEntry)) { + continue; + } $timeEntry->save(); $this->timeEntriesCreated++; } diff --git a/app/Service/Import/TimeEntryDeduplicator.php b/app/Service/Import/TimeEntryDeduplicator.php new file mode 100644 index 00000000..7b908a81 --- /dev/null +++ b/app/Service/Import/TimeEntryDeduplicator.php @@ -0,0 +1,123 @@ +> + */ + private array $existingCountsByMonth = []; + + public function __construct(private readonly string $organizationId) {} + + /** + * Returns true if an equal time entry already exists in the organization and was not matched by an earlier + * time entry of this import. The match is consumed, so the caller should skip creating the time entry. + */ + public function claimExisting(TimeEntry $timeEntry): bool + { + // Note: The raw attributes contain the timestamps exactly as they will be stored (UTC, "Y-m-d H:i:s"). Reading + // them directly is also much faster than going through the datetime casts. + $attributes = $timeEntry->getAttributes(); + $start = $attributes['start'] ?? null; + $end = $attributes['end'] ?? null; + if (! is_string($start) || ! is_string($end)) { + return false; + } + + $month = substr($start, 0, 7); + if (! isset($this->existingCountsByMonth[$month])) { + $this->existingCountsByMonth[$month] = $this->loadMonth($month); + } + + $fingerprint = $this->getFingerprint( + $timeEntry->member_id, + $start, + $end, + $timeEntry->project_id, + $timeEntry->task_id, + $timeEntry->description + ); + + $remaining = $this->existingCountsByMonth[$month][$fingerprint] ?? 0; + if ($remaining === 0) { + return false; + } + $this->existingCountsByMonth[$month][$fingerprint] = $remaining - 1; + + return true; + } + + /** + * @param string $month Month in the format "Y-m" + * @return array + */ + private function loadMonth(string $month): array + { + $monthStart = Carbon::createFromFormat('Y-m-d H:i:s', $month.'-01 00:00:00', 'UTC'); + if ($monthStart === null) { + throw new RuntimeException('Invalid month'); + } + $monthEnd = $monthStart->copy()->addMonth(); + + $counts = []; + // The query builder (without models) returns the timestamps exactly as stored, so they can be compared with + // the raw attributes of the imported time entries. + $rows = TimeEntry::query() + ->where('organization_id', '=', $this->organizationId) + ->where('start', '>=', $monthStart->format(self::DATE_FORMAT)) + ->where('start', '<', $monthEnd->format(self::DATE_FORMAT)) + ->whereNotNull('end') + ->toBase() + ->select(['member_id', 'start', 'end', 'project_id', 'task_id', 'description']) + ->get(); + + foreach ($rows as $row) { + /** @var object{member_id: string, start: string, end: string, project_id: string|null, task_id: string|null, description: string} $row */ + $fingerprint = $this->getFingerprint( + $row->member_id, + $row->start, + $row->end, + $row->project_id, + $row->task_id, + $row->description + ); + $counts[$fingerprint] = ($counts[$fingerprint] ?? 0) + 1; + } + + return $counts; + } + + private function getFingerprint(string $memberId, string $start, string $end, ?string $projectId, ?string $taskId, string $description): string + { + $json = json_encode([$memberId, $start, $end, $projectId, $taskId, $description]); + if ($json === false) { + throw new RuntimeException('Failed to encode time entry fingerprint'); + } + + return md5($json); + } +} diff --git a/resources/js/Components/Import/ImportWizard.vue b/resources/js/Components/Import/ImportWizard.vue index dcf38969..f61d7764 100644 --- a/resources/js/Components/Import/ImportWizard.vue +++ b/resources/js/Components/Import/ImportWizard.vue @@ -186,7 +186,12 @@ function formatReport(report: ImportReport | null): string { ([count, singular, plural]) => `${count.toLocaleString()} ${count === 1 ? singular : plural}` ); - return created.length > 0 ? `Created ${created.join(', ')}` : 'Nothing new to create'; + const skipped = report.time_entries.skipped; + const summary = created.length > 0 ? `Created ${created.join(', ')}` : 'Nothing new to create'; + if (skipped > 0) { + return `${summary}. Skipped ${skipped.toLocaleString()} existing ${skipped === 1 ? 'time entry' : 'time entries'}`; + } + return summary; } function importDescription(item: Import): string { diff --git a/resources/js/Pages/Teams/Partials/ImportData.vue b/resources/js/Pages/Teams/Partials/ImportData.vue index aa620b4c..5c02ca0d 100644 --- a/resources/js/Pages/Teams/Partials/ImportData.vue +++ b/resources/js/Pages/Teams/Partials/ImportData.vue @@ -105,7 +105,11 @@ function statusLabel(item: Import): string { {{ item.report.time_entries.created }} time entries, {{ item.report.projects.created }} projects, {{ item.report.clients.created }} clients, - {{ item.report.tasks.created }} tasks created + {{ item.report.tasks.created }} tasks created
['created' => 1], 'projects' => ['created' => 2], 'tasks' => ['created' => 1], - 'time_entries' => ['created' => 2], + 'time_entries' => ['created' => 2, 'skipped' => 0], 'tags' => ['created' => 2], 'users' => ['created' => 1], ], $import->report); diff --git a/tests/Unit/Service/Import/Importers/ClockifyTimeEntriesImporterTest.php b/tests/Unit/Service/Import/Importers/ClockifyTimeEntriesImporterTest.php index 73aad4db..e766547e 100644 --- a/tests/Unit/Service/Import/Importers/ClockifyTimeEntriesImporterTest.php +++ b/tests/Unit/Service/Import/Importers/ClockifyTimeEntriesImporterTest.php @@ -60,7 +60,7 @@ class ClockifyTimeEntriesImporterTest extends ImporterTestAbstract // Assert $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(false, true); - $this->checkTimeEntries($testScenario, false, true); + $this->checkTimeEntries($testScenario, true); $this->assertSame(2, $report->timeEntriesCreated); $this->assertSame(2, $report->tagsCreated); $this->assertSame(1, $report->tasksCreated); @@ -94,7 +94,7 @@ class ClockifyTimeEntriesImporterTest extends ImporterTestAbstract $this->assertSame(1, $report->clientsCreated); } - public function test_import_of_test_file_twice_succeeds(): void + public function test_import_of_test_file_twice_skips_existing_time_entries(): void { // Arrange $organization = Organization::factory()->create(); @@ -112,8 +112,9 @@ class ClockifyTimeEntriesImporterTest extends ImporterTestAbstract // Assert $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); - $this->checkTimeEntries($testScenario, true); - $this->assertSame(2, $report->timeEntriesCreated); + $this->checkTimeEntries($testScenario); + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(2, $report->timeEntriesSkipped); $this->assertSame(0, $report->tagsCreated); $this->assertSame(0, $report->tasksCreated); $this->assertSame(0, $report->usersCreated); diff --git a/tests/Unit/Service/Import/Importers/GenericTimeEntriesImporterTest.php b/tests/Unit/Service/Import/Importers/GenericTimeEntriesImporterTest.php index 98efc4dc..e0be1e06 100644 --- a/tests/Unit/Service/Import/Importers/GenericTimeEntriesImporterTest.php +++ b/tests/Unit/Service/Import/Importers/GenericTimeEntriesImporterTest.php @@ -44,7 +44,7 @@ class GenericTimeEntriesImporterTest extends ImporterTestAbstract $this->assertSame(1, $report->clientsCreated); } - public function test_import_of_test_file_twice_succeeds(): void + public function test_import_of_test_file_twice_skips_existing_time_entries(): void { // Arrange $organization = Organization::factory()->create(); @@ -62,8 +62,9 @@ class GenericTimeEntriesImporterTest extends ImporterTestAbstract // Assert $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); - $this->checkTimeEntries($testScenario, true); - $this->assertSame(2, $report->timeEntriesCreated); + $this->checkTimeEntries($testScenario); + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(2, $report->timeEntriesSkipped); $this->assertSame(0, $report->tagsCreated); $this->assertSame(0, $report->tasksCreated); $this->assertSame(0, $report->usersCreated); diff --git a/tests/Unit/Service/Import/Importers/HarvestTimeEntriesImporterTest.php b/tests/Unit/Service/Import/Importers/HarvestTimeEntriesImporterTest.php index 2291e3db..3c405bf0 100644 --- a/tests/Unit/Service/Import/Importers/HarvestTimeEntriesImporterTest.php +++ b/tests/Unit/Service/Import/Importers/HarvestTimeEntriesImporterTest.php @@ -106,6 +106,52 @@ class HarvestTimeEntriesImporterTest extends ImporterTestAbstract $this->assertSame(1, $report->clientsCreated); } + public function test_import_of_test_file_twice_skips_existing_time_entries(): void + { + // Arrange + $organization = Organization::factory()->create(); + $timezone = 'Europe/Vienna'; + $importer = new HarvestTimeEntriesImporter; + $importer->init($organization); + $data = Storage::disk('testfiles')->get('harvest_time_entries_import_test_1.csv'); + $importer->importData($data, $timezone); + $importer = new HarvestTimeEntriesImporter; + $importer->init($organization); + + // Act + $importer->importData($data, $timezone); + $report = $importer->getReport(); + + // Assert + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(2, $report->timeEntriesSkipped); + $this->assertSame(2, TimeEntry::query()->count()); + } + + public function test_import_skips_existing_time_entries_with_fractional_hours(): void + { + // Arrange + $organization = Organization::factory()->create(); + $timezone = 'Europe/Vienna'; + $importer = new HarvestTimeEntriesImporter; + $importer->init($organization); + // Note: 1.33 hours are 4788.000000000001 seconds as float + $data = "Date,Client,Project,Project Code,Task,Notes,Hours,Billable?,Invoiced?,Approved?,First Name,Last Name,Roles,Employee?,Billable Rate,Billable Amount,Cost Rate,Cost Amount,Currency,External Reference URL\n". + '2024-03-04,,Project without Client,,,"","1,33",No,No,No,Peter,Tester,,Yes,"100,0","133,0","0,0","0,0",Euro - EUR,'; + $importer->importData($data, $timezone); + $importer = new HarvestTimeEntriesImporter; + $importer->init($organization); + + // Act + $importer->importData($data, $timezone); + $report = $importer->getReport(); + + // Assert + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(1, $report->timeEntriesSkipped); + $this->assertSame(1, TimeEntry::query()->count()); + } + public function test_import_fails_if_hours_are_negative(): void { // Arrange diff --git a/tests/Unit/Service/Import/Importers/ImporterTestAbstract.php b/tests/Unit/Service/Import/Importers/ImporterTestAbstract.php index e03082f2..a1670193 100644 --- a/tests/Unit/Service/Import/Importers/ImporterTestAbstract.php +++ b/tests/Unit/Service/Import/Importers/ImporterTestAbstract.php @@ -176,14 +176,10 @@ class ImporterTestAbstract extends TestCase /** * @param object{user1: User, project1: Project, project2: Project, tag1: Tag, tag2: Tag} $testScenario */ - protected function checkTimeEntries(object $testScenario, bool $secondRun = false, bool $billableDefault = false): void + protected function checkTimeEntries(object $testScenario, bool $billableDefault = false): void { $timeEntries = TimeEntry::all(); - if ($secondRun) { - $this->assertCount(4, $timeEntries); - } else { - $this->assertCount(2, $timeEntries); - } + $this->assertCount(2, $timeEntries); $timeEntry1 = $timeEntries->firstWhere('description', ''); $this->assertNotNull($timeEntry1); $this->assertSame('', $timeEntry1->description); diff --git a/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php b/tests/Unit/Service/Import/Importers/SolidtimeImporterTest.php index 2b4d3526..398a53d9 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(25, $queryLog); + $this->assertCount(26, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true); $this->checkTimeEntries($testScenario); $this->assertSame(2, $report->timeEntriesCreated); @@ -254,7 +254,7 @@ class SolidtimeImporterTest extends ImporterTestAbstract $this->assertNull(TimeEntry::query()->where('description', 'Still running')->first()); } - public function test_import_of_test_file_twice_succeeds(): void + public function test_import_of_test_file_twice_skips_existing_time_entries(): void { // Arrange $zipPath = $this->createTestZip('solidtime_import_test_1'); @@ -279,10 +279,11 @@ class SolidtimeImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(13, $queryLog); + $this->assertCount(12, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true); - $this->checkTimeEntries($testScenario, true); - $this->assertSame(2, $report->timeEntriesCreated); + $this->checkTimeEntries($testScenario); + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(2, $report->timeEntriesSkipped); $this->assertSame(0, $report->tagsCreated); $this->assertSame(0, $report->tasksCreated); $this->assertSame(0, $report->usersCreated); diff --git a/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php b/tests/Unit/Service/Import/Importers/TogglTimeEntriesImporterTest.php index 03825c07..6ef9f008 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(22, $queryLog); + $this->assertCount(23, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); $this->checkTimeEntries($testScenario); $this->assertSame(2, $report->timeEntriesCreated); @@ -84,7 +84,7 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract $this->assertSame(1, $report->clientsCreated); } - public function test_import_of_test_file_twice_succeeds(): void + public function test_import_of_test_file_twice_skips_existing_time_entries(): void { // Arrange $organization = Organization::factory()->create(); @@ -108,10 +108,11 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract $queryLog = DB::getQueryLog(); // Assert - $this->assertCount(14, $queryLog); + $this->assertCount(13, $queryLog); $testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(); - $this->checkTimeEntries($testScenario, true); - $this->assertSame(2, $report->timeEntriesCreated); + $this->checkTimeEntries($testScenario); + $this->assertSame(0, $report->timeEntriesCreated); + $this->assertSame(2, $report->timeEntriesSkipped); $this->assertSame(0, $report->tagsCreated); $this->assertSame(0, $report->tasksCreated); $this->assertSame(0, $report->usersCreated); diff --git a/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php b/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php new file mode 100644 index 00000000..ce63ab40 --- /dev/null +++ b/tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php @@ -0,0 +1,196 @@ +organization = Organization::factory()->create(); + $this->member = Member::factory()->forOrganization($this->organization)->create(); + } + + /** + * @param array $attributes + */ + private function makeTimeEntry(string $start = '2024-03-04 09:00:00', int $duration = 3600, array $attributes = []): TimeEntry + { + return TimeEntry::factory() + ->forMember($this->member) + ->startWithDuration(Carbon::parse($start, 'UTC'), $duration) + ->make(array_merge(['description' => 'Working hard'], $attributes)); + } + + public function test_claims_existing_equal_time_entry_only_once(): void + { + // Arrange + $this->makeTimeEntry()->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $first = $deduplicator->claimExisting($this->makeTimeEntry()); + $second = $deduplicator->claimExisting($this->makeTimeEntry()); + + // Assert + $this->assertTrue($first); + $this->assertFalse($second); + } + + public function test_claims_each_existing_duplicate_once(): void + { + // Arrange + $this->makeTimeEntry()->save(); + $this->makeTimeEntry()->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $results = [ + $deduplicator->claimExisting($this->makeTimeEntry()), + $deduplicator->claimExisting($this->makeTimeEntry()), + $deduplicator->claimExisting($this->makeTimeEntry()), + ]; + + // Assert + $this->assertSame([true, true, false], $results); + } + + public function test_does_not_count_time_entries_created_after_the_month_was_loaded(): void + { + // Arrange + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $first = $deduplicator->claimExisting($this->makeTimeEntry()); + $this->makeTimeEntry()->save(); + $second = $deduplicator->claimExisting($this->makeTimeEntry()); + + // Assert + $this->assertFalse($first); + $this->assertFalse($second); + } + + public function test_does_not_claim_time_entry_that_differs_in_one_compared_field(): void + { + // Arrange + $project = Project::factory()->forOrganization($this->organization)->create(); + $otherMember = Member::factory()->forOrganization($this->organization)->create(); + $this->makeTimeEntry()->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $results = [ + 'description' => $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['description' => 'Other'])), + 'start' => $deduplicator->claimExisting($this->makeTimeEntry('2024-03-04 09:00:01', 3599)), + 'end' => $deduplicator->claimExisting($this->makeTimeEntry(duration: 3601)), + 'project' => $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['project_id' => $project->getKey()])), + 'member' => $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $otherMember->getKey()])), + ]; + + // Assert + $this->assertSame([ + 'description' => false, + 'start' => false, + 'end' => false, + 'project' => false, + 'member' => false, + ], $results); + } + + public function test_ignores_fields_that_can_change_after_an_export(): void + { + // Arrange + $this->makeTimeEntry(attributes: ['billable' => false, 'tags' => []])->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $result = $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['billable' => true, 'tags' => ['tag']])); + + // Assert + $this->assertTrue($result); + } + + public function test_does_not_claim_time_entry_of_other_organization(): void + { + // Arrange + $otherOrganization = Organization::factory()->create(); + $this->makeTimeEntry(attributes: ['organization_id' => $otherOrganization->getKey()])->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $result = $deduplicator->claimExisting($this->makeTimeEntry()); + + // Assert + $this->assertFalse($result); + } + + public function test_matches_time_entries_at_month_boundaries(): void + { + // Arrange + $this->makeTimeEntry('2024-03-31 23:59:59')->save(); + $this->makeTimeEntry('2024-04-01 00:00:00')->save(); + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + $results = [ + $deduplicator->claimExisting($this->makeTimeEntry('2024-04-01 00:00:00')), + $deduplicator->claimExisting($this->makeTimeEntry('2024-03-31 23:59:59')), + $deduplicator->claimExisting($this->makeTimeEntry('2024-04-01 00:00:00')), + ]; + + // Assert + $this->assertSame([true, true, false], $results); + } + + public function test_never_claims_running_time_entry(): void + { + // Arrange + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + $timeEntry = $this->makeTimeEntry(); + $timeEntry->end = null; + + // Act + $result = $deduplicator->claimExisting($timeEntry); + + // Assert + $this->assertFalse($result); + } + + public function test_loads_each_month_only_once(): void + { + // Arrange + $deduplicator = new TimeEntryDeduplicator($this->organization->getKey()); + + // Act + DB::enableQueryLog(); + DB::flushQueryLog(); + $deduplicator->claimExisting($this->makeTimeEntry('2024-03-04 09:00:00')); + $deduplicator->claimExisting($this->makeTimeEntry('2024-03-20 09:00:00')); + $deduplicator->claimExisting($this->makeTimeEntry('2024-04-01 09:00:00')); + $deduplicator->claimExisting($this->makeTimeEntry('2024-03-05 09:00:00')); + $queryLog = DB::getQueryLog(); + + // Assert + $this->assertCount(2, $queryLog); + } +}