mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-12-06 17:52:16 +00:00
Skip time entries that already exist when importing
Re-importing the same data duplicated all time entries, because only clients, projects, tasks, tags and users were matched with existing records. Time entries are now matched by member, start, end, project, task and description. Matches are counted, so identical time entries within one import are still kept. Fixes #894
This commit is contained in:
committed by
Constantin Graf
parent
7fd9f36d69
commit
a166f8ef44
@@ -41,6 +41,7 @@ class ImportResource extends BaseResource
|
||||
* },
|
||||
* time_entries: array{
|
||||
* created: int,
|
||||
* skipped: int,
|
||||
* },
|
||||
* tags: array{
|
||||
* created: int,
|
||||
|
||||
@@ -203,6 +203,9 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
$member,
|
||||
$this->organization
|
||||
);
|
||||
if ($this->skipIfAlreadyExists($timeEntry)) {
|
||||
continue;
|
||||
}
|
||||
$timeEntry->save();
|
||||
$this->timeEntriesCreated++;
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
);
|
||||
|
||||
@@ -167,6 +167,9 @@ class GenericTimeEntriesImporter extends DefaultImporter
|
||||
$member,
|
||||
$this->organization
|
||||
);
|
||||
if ($this->skipIfAlreadyExists($timeEntry)) {
|
||||
continue;
|
||||
}
|
||||
$timeEntry->save();
|
||||
$this->timeEntriesCreated++;
|
||||
}
|
||||
|
||||
@@ -149,6 +149,9 @@ class HarvestTimeEntriesImporter extends DefaultImporter
|
||||
$member,
|
||||
$this->organization
|
||||
);
|
||||
if ($this->skipIfAlreadyExists($timeEntry)) {
|
||||
continue;
|
||||
}
|
||||
$timeEntry->save();
|
||||
$this->timeEntriesCreated++;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -337,6 +337,9 @@ class SolidtimeImporter extends DefaultImporter
|
||||
$member,
|
||||
$this->organization
|
||||
);
|
||||
if ($this->skipIfAlreadyExists($timeEntry)) {
|
||||
continue;
|
||||
}
|
||||
$timeEntry->save();
|
||||
$this->timeEntriesCreated++;
|
||||
}
|
||||
|
||||
@@ -151,6 +151,9 @@ class TogglTimeEntriesImporter extends DefaultImporter
|
||||
$member,
|
||||
$this->organization
|
||||
);
|
||||
if ($this->skipIfAlreadyExists($timeEntry)) {
|
||||
continue;
|
||||
}
|
||||
$timeEntry->save();
|
||||
$this->timeEntriesCreated++;
|
||||
}
|
||||
|
||||
123
app/Service/Import/TimeEntryDeduplicator.php
Normal file
123
app/Service/Import/TimeEntryDeduplicator.php
Normal file
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Import;
|
||||
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Support\Carbon;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Detects imported time entries that already exist in the organization, so importing the same data twice does not
|
||||
* duplicate time entries.
|
||||
*
|
||||
* Matches are counted: if the organization already contains a time entry N times, the first N equal time entries of
|
||||
* 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 UTC month of their start, so only the months an import touches are
|
||||
* queried. A month is always loaded before the first time entry of that 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 month ("Y-m")
|
||||
*
|
||||
* @var array<string, array<string, int>>
|
||||
*/
|
||||
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<string, int>
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<template
|
||||
v-if="item.report.time_entries.skipped > 0"
|
||||
>, {{ item.report.time_entries.skipped }} existing time entries
|
||||
skipped</template
|
||||
>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="item.status === 'failed' && item.error_message"
|
||||
|
||||
@@ -73,7 +73,9 @@ const ImportResource = z
|
||||
clients: z.object({ created: z.number().int() }).passthrough(),
|
||||
projects: z.object({ created: z.number().int() }).passthrough(),
|
||||
tasks: z.object({ created: z.number().int() }).passthrough(),
|
||||
time_entries: z.object({ created: z.number().int() }).passthrough(),
|
||||
time_entries: z
|
||||
.object({ created: z.number().int(), skipped: z.number().int() })
|
||||
.passthrough(),
|
||||
tags: z.object({ created: z.number().int() }).passthrough(),
|
||||
users: z.object({ created: z.number().int() }).passthrough(),
|
||||
})
|
||||
|
||||
@@ -177,7 +177,7 @@ class ImportServiceTest extends TestCase
|
||||
'clients' => ['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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
$timeEntry1 = $timeEntries->firstWhere('description', '');
|
||||
$this->assertNotNull($timeEntry1);
|
||||
$this->assertSame('', $timeEntry1->description);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
196
tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php
Normal file
196
tests/Unit/Service/Import/TimeEntryDeduplicatorTest.php
Normal file
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Service\Import;
|
||||
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\Import\TimeEntryDeduplicator;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use PHPUnit\Framework\Attributes\CoversClass;
|
||||
use Tests\TestCase;
|
||||
|
||||
#[CoversClass(TimeEntryDeduplicator::class)]
|
||||
class TimeEntryDeduplicatorTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Organization $organization;
|
||||
|
||||
private Member $member;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->organization = Organization::factory()->create();
|
||||
$this->member = Member::factory()->forOrganization($this->organization)->create();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user