mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-12-06 17:52:16 +00:00
184 lines
7.2 KiB
PHP
184 lines
7.2 KiB
PHP
<?php
|
|
|
|
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;
|
|
|
|
/**
|
|
* 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.
|
|
*
|
|
* 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 group and month ("<group>|Y-m")
|
|
*
|
|
* @var array<string, array<string, int>>
|
|
*/
|
|
private array $existingCounts = [];
|
|
|
|
/**
|
|
* Group key (lower case email of the user) per member ID of the organization, loaded on first use
|
|
*
|
|
* @var array<string, string>|null
|
|
*/
|
|
private ?array $groupByMember = null;
|
|
|
|
/**
|
|
* Member IDs per group key
|
|
*
|
|
* @var array<string, list<string>>
|
|
*/
|
|
private array $membersByGroup = [];
|
|
|
|
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 values exactly as they will be stored (timestamps in UTC as
|
|
// "Y-m-d H:i:s", the type as its enum value). Reading them directly is also much faster than going through
|
|
// the casts.
|
|
$attributes = $timeEntry->getAttributes();
|
|
$start = $attributes['start'] ?? null;
|
|
$end = $attributes['end'] ?? null;
|
|
if (! is_string($start) || ! is_string($end)) {
|
|
return false;
|
|
}
|
|
|
|
$group = $this->getGroup($timeEntry->member_id);
|
|
$month = substr($start, 0, 7);
|
|
$bucket = $group.'|'.$month;
|
|
if (! isset($this->existingCounts[$bucket])) {
|
|
$this->existingCounts[$bucket] = $this->loadGroupMonth($this->membersByGroup[$group], $month);
|
|
}
|
|
|
|
$fingerprint = $this->getFingerprint(
|
|
$start,
|
|
$end,
|
|
$timeEntry->project_id,
|
|
$timeEntry->task_id,
|
|
$timeEntry->description,
|
|
(string) ($attributes['type'] ?? 'work')
|
|
);
|
|
|
|
$remaining = $this->existingCounts[$bucket][$fingerprint] ?? 0;
|
|
if ($remaining === 0) {
|
|
return false;
|
|
}
|
|
$this->existingCounts[$bucket][$fingerprint] = $remaining - 1;
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 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<string> $memberIds
|
|
* @param string $month Month in the format "Y-m"
|
|
* @return array<string, int>
|
|
*/
|
|
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) {
|
|
throw new RuntimeException('Invalid month');
|
|
}
|
|
$monthEnd = $monthStart->copy()->addMonth();
|
|
|
|
$counts = [];
|
|
// The query builder (without models) returns the values exactly as stored, so they can be compared with the
|
|
// 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)
|
|
->whereIn('member_id', $memberIds)
|
|
->where('start', '>=', $monthStart->format(self::DATE_FORMAT))
|
|
->where('start', '<', $monthEnd->format(self::DATE_FORMAT))
|
|
->whereNotNull('end')
|
|
->toBase()
|
|
->select(['start', 'end', 'project_id', 'task_id', 'description', 'type'])
|
|
->cursor();
|
|
|
|
foreach ($rows as $row) {
|
|
/** @var object{start: string, end: string, project_id: string|null, task_id: string|null, description: string, type: string} $row */
|
|
$fingerprint = $this->getFingerprint(
|
|
$row->start,
|
|
$row->end,
|
|
$row->project_id,
|
|
$row->task_id,
|
|
$row->description,
|
|
$row->type
|
|
);
|
|
$counts[$fingerprint] = ($counts[$fingerprint] ?? 0) + 1;
|
|
}
|
|
|
|
return $counts;
|
|
}
|
|
|
|
private function getFingerprint(string $start, string $end, ?string $projectId, ?string $taskId, string $description, string $type): string
|
|
{
|
|
$json = json_encode([$start, $end, $projectId, $taskId, $description, $type], JSON_INVALID_UTF8_SUBSTITUTE);
|
|
if ($json === false) {
|
|
throw new RuntimeException('Failed to encode time entry fingerprint');
|
|
}
|
|
|
|
return md5($json);
|
|
}
|
|
}
|