Added filled gaps to time entry aggregation; Moved aggregation to service

This commit is contained in:
Constantin Graf
2024-05-21 17:31:45 +02:00
parent efd3fef0c5
commit 2a8ab12017
30 changed files with 1017 additions and 218 deletions

View File

@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum TimeEntryAggregationType: string
{
case Day = 'day';
case Week = 'week';
case Month = 'month';
case Year = 'year';
case User = 'user';
case Project = 'project';
case Task = 'task';
case Client = 'client';
case Billable = 'billable';
public function toInterval(): ?TimeEntryAggregationTypeInterval
{
return match ($this) {
TimeEntryAggregationType::Day => TimeEntryAggregationTypeInterval::Day,
TimeEntryAggregationType::Week => TimeEntryAggregationTypeInterval::Week,
TimeEntryAggregationType::Month => TimeEntryAggregationTypeInterval::Month,
TimeEntryAggregationType::Year => TimeEntryAggregationTypeInterval::Year,
default => null
};
}
}

View File

@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Enums;
enum TimeEntryAggregationTypeInterval: string
{
case Day = 'day';
case Week = 'week';
case Month = 'month';
case Year = 'year';
}

View File

@@ -16,6 +16,19 @@ enum Weekday: string
case Saturday = 'saturday';
case Sunday = 'sunday';
public function toEndOfWeek(): self
{
return match ($this) {
Weekday::Monday => Weekday::Sunday,
Weekday::Tuesday => Weekday::Monday,
Weekday::Wednesday => Weekday::Tuesday,
Weekday::Thursday => Weekday::Wednesday,
Weekday::Friday => Weekday::Thursday,
Weekday::Saturday => Weekday::Friday,
Weekday::Sunday => Weekday::Saturday,
};
}
public function carbonWeekDay(): int
{
return match ($this) {

View File

@@ -48,7 +48,7 @@ class ProjectController extends Controller
->whereBelongsTo($organization, 'organization');
if (! $canViewAllProjects) {
$projectsQuery->visibleByUser($user);
$projectsQuery->visibleByEmployee($user);
}
$projects = $projectsQuery->paginate(config('app.pagination_per_page_default'));
@@ -131,7 +131,7 @@ class ProjectController extends Controller
}
DB::transaction(function () use (&$project) {
$project->members()->each(function (ProjectMember $member) {
$project->members->each(function (ProjectMember $member) {
$member->delete();
});

View File

@@ -51,7 +51,7 @@ class TaskController extends Controller
}
if (! $canViewAllTasks) {
$query->visibleByUser($user);
$query->visibleByEmployee($user);
}
$tasks = $query->paginate(config('app.pagination_per_page_default'));

View File

@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Enums\Weekday;
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
use App\Exceptions\Api\TimeEntryStillRunningApiException;
use App\Http\Requests\V1\TimeEntry\TimeEntryAggregateRequest;
@@ -17,13 +16,12 @@ use App\Http\Resources\V1\TimeEntry\TimeEntryResource;
use App\Models\Member;
use App\Models\Organization;
use App\Models\TimeEntry;
use App\Service\TimeEntryAggregationService;
use App\Service\TimeEntryFilter;
use App\Service\TimezoneService;
use Carbon\CarbonTimeZone;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
@@ -82,7 +80,7 @@ class TimeEntryController extends Controller
$timeEntries = $timeEntriesQuery->get();
if ($timeEntries->count() === $limit && $request->has('only_full_dates') && (bool) $request->get('only_full_dates') === true) {
if ($timeEntries->count() === $limit && $request->getOnlyFullDates()) {
$user = $this->user();
$timezone = app(TimezoneService::class)->getTimezoneFromUser($user);
$lastDate = null;
@@ -126,16 +124,18 @@ class TimeEntryController extends Controller
*
* @return array{
* data: array{
* grouped_type: string|null,
* grouped_data: null|array<array{
* type: string,
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: string|null,
* grouped_data: null|array<array{
* type: string,
* key: string|null,
* seconds: int,
* cost: int
* cost: int,
* grouped_type: null,
* grouped_data: null
* }>
* }>,
* seconds: int,
@@ -145,7 +145,7 @@ class TimeEntryController extends Controller
*
* @throws AuthorizationException
*/
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request): array
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request, TimeEntryAggregationService $aggregationService): array
{
/** @var Member|null $member */
$member = $request->has('member_id') ? Member::query()->findOrFail($request->get('member_id')) : null;
@@ -173,132 +173,25 @@ class TimeEntryController extends Controller
$user = $this->user();
/** @var string|null $group1Type */
$group1Type = $request->get('group');
/** @var string|null $group2Type */
$group2Type = $request->get('sub_group');
$group1Type = $request->getGroup();
$group2Type = $request->getSubGroup();
$group1Select = null;
$group2Select = null;
$groupBy = null;
if ($group1Type !== null) {
$group1Select = $this->getGroupByQuery($group1Type, $user->timezone, $user->week_start);
$groupBy = ['group_1'];
if ($group2Type !== null) {
$group2Select = $this->getGroupByQuery($group2Type, $user->timezone, $user->week_start);
$groupBy = ['group_1', 'group_2'];
}
}
$timeEntriesQuery->selectRaw(
($group1Select !== null ? $group1Select.' as group_1,' : '').
($group2Select !== null ? $group2Select.' as group_2,' : '').
' round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate,'.
' round(
sum(
extract(epoch from (coalesce("end", now()) - start)) * (coalesce(billable_rate, 0)::float/60/60)
)
) as cost'
$aggregatedData = $aggregationService->getAggregatedTimeEntries(
$timeEntriesQuery,
$group1Type,
$group2Type,
$user->timezone,
$user->week_start,
$request->getFillGapsInTimeGroups(),
$request->getStart(),
$request->getEnd()
);
if ($groupBy !== null) {
$timeEntriesQuery->groupBy($groupBy);
}
$timeEntriesAggregates = $timeEntriesQuery->get();
if ($group1Select !== null) {
$groupedAggregates = $timeEntriesAggregates->groupBy($group2Select !== null ? ['group_1', 'group_2'] : ['group_1']);
$group1Response = [];
$group1ResponseSum = 0;
$group1ResponseCost = 0;
foreach ($groupedAggregates as $group1 => $group1Aggregates) {
/** @var string $group1 */
$group2Response = [];
if ($group2Select !== null) {
$group2ResponseSum = 0;
$group2ResponseCost = 0;
foreach ($group1Aggregates as $group2 => $aggregate) {
/** @var string $group2 */
/** @var Collection<int, object{aggregate: int, cost: int}> $aggregate */
/** @var string $group2Type */
$group2Response[] = [
'type' => $group2Type,
'key' => $group2 === '' ? null : (string) $group2,
'seconds' => (int) $aggregate->get(0)->aggregate,
'cost' => (int) $aggregate->get(0)->cost,
];
$group2ResponseSum += (int) $aggregate->get(0)->aggregate;
$group2ResponseCost += (int) $aggregate->get(0)->cost;
}
} else {
/** @var Collection<int, object{aggregate: int, cost: int}> $group1Aggregates */
$group2ResponseSum = (int) $group1Aggregates->get(0)->aggregate;
$group2ResponseCost = (int) $group1Aggregates->get(0)->cost;
$group2Response = null;
}
/** @var string $group1Type */
$group1Response[] = [
'type' => $group1Type,
'key' => $group1 === '' ? null : (string) $group1,
'seconds' => $group2ResponseSum,
'cost' => $group2ResponseCost,
'grouped_data' => $group2Response,
];
$group1ResponseSum += $group2ResponseSum;
$group1ResponseCost += $group2ResponseCost;
}
} else {
$group1Response = null;
/** @var Collection<int, object{aggregate: int, cost: int}> $timeEntriesAggregates */
$group1ResponseSum = (int) $timeEntriesAggregates->get(0)->aggregate;
$group1ResponseCost = (int) $timeEntriesAggregates->get(0)->cost;
}
return [
'data' => [
'grouped_data' => $group1Response,
'seconds' => $group1ResponseSum,
'cost' => $group1ResponseCost,
],
'data' => $aggregatedData,
];
}
private function getGroupByQuery(string $group, string $timezone, Weekday $startOfWeek): string
{
$timezoneShift = app(TimezoneService::class)->getShiftFromUtc(new CarbonTimeZone($timezone));
if ($timezoneShift > 0) {
$dateWithTimeZone = 'start + INTERVAL \''.$timezoneShift.' second\'';
} elseif ($timezoneShift < 0) {
$dateWithTimeZone = 'start - INTERVAL \''.abs($timezoneShift).' second\'';
} else {
$dateWithTimeZone = 'start';
}
$startOfWeek = Carbon::now()->setTimezone($timezone)->startOfWeek($startOfWeek->carbonWeekDay())->utc()->toDateTimeString();
if ($group === 'day') {
return 'date('.$dateWithTimeZone.')';
} elseif ($group === 'week') {
return "to_char(date_bin('7 days', ".$dateWithTimeZone.", timestamp '".$startOfWeek."'), 'YYYY-MM-DD HH24:MI:SS')";
} elseif ($group === 'month') {
return 'to_char('.$dateWithTimeZone.', \'YYYY-MM\')';
} elseif ($group === 'year') {
return 'to_char('.$dateWithTimeZone.', \'YYYY\')';
} elseif ($group === 'user') {
return 'user_id';
} elseif ($group === 'project') {
return 'project_id';
} elseif ($group === 'task') {
return 'task_id';
} elseif ($group === 'client') {
return 'client_id';
} elseif ($group === 'billable') {
return 'billable';
}
throw new \LogicException('Invalid group');
}
/**
* Create time entry
*

View File

@@ -6,9 +6,9 @@ namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

View File

@@ -33,7 +33,7 @@ class TaskIndexRequest extends FormRequest
$builder = $builder->whereBelongsTo($this->organization, 'organization');
if (! app(PermissionStore::class)->has($this->organization, 'tasks:view:all')) {
$builder = $builder->visibleByUser(Auth::user());
$builder = $builder->visibleByEmployee(Auth::user());
}
return $builder;

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Http\Requests\V1\TimeEntry;
use App\Enums\TimeEntryAggregationType;
use App\Models\Member;
use App\Models\Organization;
use App\Models\Project;
@@ -13,7 +14,8 @@ use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
use Illuminate\Validation\Rule;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
/**
@@ -24,7 +26,7 @@ class TimeEntryAggregateRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array<string, array<string|ValidationRule>>
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
*/
public function rules(): array
{
@@ -32,12 +34,12 @@ class TimeEntryAggregateRequest extends FormRequest
'group' => [
'nullable',
'required_with:group_2',
'in:day,week,month,year,user,project,task,client,billable',
Rule::enum(TimeEntryAggregationType::class),
],
'sub_group' => [
'nullable',
'in:day,week,month,year,user,project,task,client,billable',
Rule::enum(TimeEntryAggregationType::class),
],
// Filter by member ID
'member_id' => [
@@ -81,7 +83,7 @@ class TimeEntryAggregateRequest extends FormRequest
'uuid',
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
return $builder->visibleByUser(Auth::user());
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter by tag IDs, tag IDs are AND combined
@@ -106,8 +108,7 @@ class TimeEntryAggregateRequest extends FormRequest
'string',
'uuid',
new ExistsEloquent(Task::class, null, function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->visibleByUser(Auth::user());
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
@@ -133,6 +134,35 @@ class TimeEntryAggregateRequest extends FormRequest
'string',
'in:true,false',
],
'fill_gaps_in_time_groups' => [
'string',
'in:true,false',
],
];
}
public function getGroup(): ?TimeEntryAggregationType
{
return $this->get('group') !== null ? TimeEntryAggregationType::from($this->get('group')) : null;
}
public function getSubGroup(): ?TimeEntryAggregationType
{
return $this->get('sub_group') !== null ? TimeEntryAggregationType::from($this->get('sub_group')) : null;
}
public function getFillGapsInTimeGroups(): bool
{
return $this->has('fill_gaps_in_time_groups') && $this->get('fill_gaps_in_time_groups') === 'true';
}
public function getStart(): ?Carbon
{
return $this->get('after') !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->get('after'), 'UTC') : null;
}
public function getEnd(): ?Carbon
{
return $this->get('before') !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->get('before'), 'UTC') : null;
}
}

View File

@@ -12,7 +12,6 @@ use App\Models\Task;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
/**
@@ -60,7 +59,7 @@ class TimeEntryIndexRequest extends FormRequest
'uuid',
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
/** @var Builder<Project> $builder */
return $builder->visibleByUser(Auth::user());
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter by tag IDs, tag IDs are AND combined
@@ -86,7 +85,7 @@ class TimeEntryIndexRequest extends FormRequest
'uuid',
new ExistsEloquent(Task::class, null, function (Builder $builder): Builder {
/** @var Builder<Task> $builder */
return $builder->visibleByUser(Auth::user());
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
@@ -125,4 +124,9 @@ class TimeEntryIndexRequest extends FormRequest
],
];
}
public function getOnlyFullDates(): bool
{
return $this->input('only_full_dates', 'false') === 'true';
}
}

View File

@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Http\Resources\V1;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
abstract class BaseResource extends JsonResource
{

View File

@@ -25,7 +25,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property-read Collection<int, Task> $tasks
* @property-read Collection<int, ProjectMember> $members
*
* @method Builder<Project> visibleByUser(User $user)
* @method Builder<Project> visibleByEmployee(User $user)
* @method static ProjectFactory factory()
*/
class Project extends Model
@@ -64,7 +64,7 @@ class Project extends Model
*/
public function members(): HasMany
{
return $this->hasMany(ProjectMember::class);
return $this->hasMany(ProjectMember::class, 'project_id');
}
/**
@@ -86,7 +86,7 @@ class Project extends Model
/**
* @param Builder<Project> $builder
*/
public function scopeVisibleByUser(Builder $builder, User $user): void
public function scopeVisibleByEmployee(Builder $builder, User $user): void
{
$builder->where(function (Builder $builder) use ($user): Builder {
return $builder->where('is_public', '=', true)

View File

@@ -69,11 +69,11 @@ class Task extends Model
* @param Builder<Task> $builder
* @return Builder<Task>
*/
public function scopeVisibleByUser(Builder $builder, User $user): Builder
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
{
return $builder->whereHas('project', function (Builder $builder) use ($user): Builder {
/** @var Builder<Project> $builder */
return $builder->visibleByUser($user);
return $builder->visibleByEmployee($user);
});
}
}

View File

@@ -10,9 +10,9 @@ use App\Models\Project;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

View File

@@ -36,6 +36,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "clients.json" can not be opened');
}
$clients = json_decode($clientsFileContent);
if ($clients === null) {
throw new ImportException('File "clients.json" is empty');
}
if (! file_exists($temporaryDirectory->path('projects.json'))) {
throw new ImportException('File "projects.json" missing in ZIP');
}
@@ -44,6 +47,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "projects.json" can not be opened');
}
$projects = json_decode($projectsFileContent);
if ($projects === null) {
throw new ImportException('File "projects.json" is empty');
}
if (! file_exists($temporaryDirectory->path('tags.json'))) {
throw new ImportException('File "tags.json" missing in ZIP');
}
@@ -52,6 +58,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "tags.json" can not be opened');
}
$tags = json_decode($tagsFileContent);
if ($tags === null) {
throw new ImportException('File "tags.json" is empty');
}
if (! file_exists($temporaryDirectory->path('workspace_users.json'))) {
throw new ImportException('File "workspace_users.json" missing in ZIP');
}
@@ -60,6 +69,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "workspace_users.json" can not be opened');
}
$workspaceUsers = json_decode($workspaceUsersFileContent);
if ($workspaceUsers === null) {
throw new ImportException('File "workspace_users.json" is empty');
}
foreach ($clients as $client) {
$this->clientImportHelper->getKey([
'name' => $client->name,
@@ -117,6 +129,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "projects_users/'.$project->id.'.json" can not be opened');
}
$projectMembers = json_decode($projectMembersFileContent);
if ($projectMembers === null) {
throw new ImportException('File "projects_users/'.$project->id.'.json" is empty');
}
foreach ($projectMembers as $projectMember) {
$userId = $this->userImportHelper->getKeyByExternalIdentifier((string) $projectMember->user_id);
$this->projectMemberImportHelper->getKey([
@@ -138,6 +153,9 @@ class TogglDataImporter extends DefaultImporter
throw new ImportException('File "tasks/'.$projectIdExternal.'.json" can not be opened');
}
$tasks = json_decode($tasksFileContent);
if ($tasks === null) {
throw new ImportException('File "tasks/'.$projectIdExternal.'.json" is empty');
}
foreach ($tasks as $task) {
$projectId = $this->projectImportHelper->getKeyByExternalIdentifier((string) $projectIdExternal);

View File

@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Enums\TimeEntryAggregationType;
use App\Enums\TimeEntryAggregationTypeInterval;
use App\Enums\Weekday;
use App\Models\TimeEntry;
use Carbon\CarbonTimeZone;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class TimeEntryAggregationService
{
/**
* @param Builder<TimeEntry> $timeEntriesQuery
* @return array{
* grouped_type: string|null,
* grouped_data: null|array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: string|null,
* grouped_data: null|array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: null,
* grouped_data: null
* }>
* }>,
* seconds: int,
* cost: int
* }
*/
public function getAggregatedTimeEntries(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end): array
{
$fillGapsInTimeGroupsIsPossible = $fillGapsInTimeGroups && $start !== null && $end !== null;
$group1Select = null;
$group2Select = null;
$groupBy = null;
if ($group1Type !== null) {
$group1Select = $this->getGroupByQuery($group1Type, $timezone, $startOfWeek);
$groupBy = ['group_1'];
if ($group2Type !== null) {
$group2Select = $this->getGroupByQuery($group2Type, $timezone, $startOfWeek);
$groupBy = ['group_1', 'group_2'];
}
}
$timeEntriesQuery->selectRaw(
($group1Select !== null ? $group1Select.' as group_1,' : '').
($group2Select !== null ? $group2Select.' as group_2,' : '').
' round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate,'.
' round(
sum(
extract(epoch from (coalesce("end", now()) - start)) * (coalesce(billable_rate, 0)::float/60/60)
)
) as cost'
);
if ($groupBy !== null) {
$timeEntriesQuery->groupBy($groupBy);
}
$timeEntriesAggregates = $timeEntriesQuery->get();
if ($group1Select !== null) {
$groupedAggregates = $timeEntriesAggregates->groupBy($group2Select !== null ? ['group_1', 'group_2'] : ['group_1']);
$group1Response = [];
$group1ResponseSum = 0;
$group1ResponseCost = 0;
foreach ($groupedAggregates as $group1 => $group1Aggregates) {
/** @var string|int $group1 */
$group2Response = [];
if ($group2Select !== null) {
$group2ResponseSum = 0;
$group2ResponseCost = 0;
foreach ($group1Aggregates as $group2 => $aggregate) {
/** @var string|int $group2 */
/** @var Collection<int, object{aggregate: int, cost: int}> $aggregate */
$group2Response[] = [
'key' => $group2 === '' ? null : (string) $group2,
'seconds' => (int) $aggregate->get(0)->aggregate,
'cost' => (int) $aggregate->get(0)->cost,
'grouped_type' => null,
'grouped_data' => null,
];
$group2ResponseSum += (int) $aggregate->get(0)->aggregate;
$group2ResponseCost += (int) $aggregate->get(0)->cost;
}
} else {
/** @var Collection<int, object{aggregate: int, cost: int}> $group1Aggregates */
$group2ResponseSum = (int) $group1Aggregates->get(0)->aggregate;
$group2ResponseCost = (int) $group1Aggregates->get(0)->cost;
$group2Response = null;
}
$group1Response[] = [
'key' => $group1 === '' ? null : (string) $group1,
'seconds' => $group2ResponseSum,
'cost' => $group2ResponseCost,
'grouped_type' => $group2Type?->value,
'grouped_data' => $group2Response,
];
$group1ResponseSum += $group2ResponseSum;
$group1ResponseCost += $group2ResponseCost;
}
if ($fillGapsInTimeGroupsIsPossible) {
$group1Response = $this->fillGapsInTimeGroups($group1Response, $group1Type, $group2Type, $timezone, $startOfWeek, $start, $end);
}
} else {
$group1Response = null;
/** @var Collection<int, object{aggregate: int, cost: int}> $timeEntriesAggregates */
$group1ResponseSum = (int) $timeEntriesAggregates->get(0)->aggregate;
$group1ResponseCost = (int) $timeEntriesAggregates->get(0)->cost;
}
return [
'seconds' => $group1ResponseSum,
'cost' => $group1ResponseCost,
'grouped_type' => $group1Type?->value,
'grouped_data' => $group1Response,
];
}
/**
* @param array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: string|null,
* grouped_data: null|array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: null|mixed,
* grouped_data: null|mixed
* }>
* }> $data
* @return array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: string|null,
* grouped_data: null|array<array{
* key: string|null,
* seconds: int,
* cost: int,
* grouped_type: null|mixed,
* grouped_data: null|mixed
* }>
* }>
*/
public function fillGapsInTimeGroups(array $data, TimeEntryAggregationType $groupType, ?TimeEntryAggregationType $subGroupType, string $timezone, Weekday $startOfWeek, Carbon $start, Carbon $end): array
{
$interval = $groupType->toInterval();
if ($interval === null) {
foreach ($data as $key => $item) {
$data[$key]['grouped_data'] = $this->fillGapsInTimeGroups(
$item['grouped_data'],
$subGroupType,
null,
$timezone,
$startOfWeek,
$start,
$end
);
}
return $data;
} else {
$format = match ($interval) {
TimeEntryAggregationTypeInterval::Day => 'Y-m-d',
TimeEntryAggregationTypeInterval::Week => 'Y-m-d H:i:s',
TimeEntryAggregationTypeInterval::Month => 'Y-m',
TimeEntryAggregationTypeInterval::Year => 'Y',
};
$slots = $this->timeSlotsBetween($start, $end, $timezone, $startOfWeek, $interval, $format);
$filledData = [];
foreach ($slots as $slot) {
$foundDataSet = null;
foreach ($data as $item) {
if ($item['key'] === $slot) {
$foundDataSet = $item;
break;
}
}
if ($foundDataSet !== null) {
$filledData[] = [
'key' => $slot,
'seconds' => $foundDataSet['seconds'],
'cost' => $foundDataSet['cost'],
'grouped_type' => $subGroupType?->value,
'grouped_data' => $subGroupType === null
? null
: $this->fillGapsInTimeGroups(
$foundDataSet['grouped_data'],
$subGroupType,
null,
$timezone,
$startOfWeek,
$start,
$end
),
];
} else {
$filledData[] = [
'key' => $slot,
'seconds' => 0,
'cost' => 0,
'grouped_type' => $subGroupType?->value,
'grouped_data' => $subGroupType === null ? null : [],
];
}
}
return $filledData;
}
}
private function getGroupByQuery(TimeEntryAggregationType $group, string $timezone, Weekday $startOfWeek): string
{
$timezoneShift = app(TimezoneService::class)->getShiftFromUtc(new CarbonTimeZone($timezone));
if ($timezoneShift > 0) {
$dateWithTimeZone = 'start + INTERVAL \''.$timezoneShift.' second\'';
} elseif ($timezoneShift < 0) {
$dateWithTimeZone = 'start - INTERVAL \''.abs($timezoneShift).' second\'';
} else {
$dateWithTimeZone = 'start';
}
$startOfWeek = Carbon::now()->setTimezone($timezone)->startOfWeek($startOfWeek->carbonWeekDay())->utc()->toDateTimeString();
if ($group === TimeEntryAggregationType::Day) {
return 'date('.$dateWithTimeZone.')';
} elseif ($group === TimeEntryAggregationType::Week) {
return "to_char(date_bin('7 days', ".$dateWithTimeZone.", timestamp '".$startOfWeek."'), 'YYYY-MM-DD HH24:MI:SS')";
} elseif ($group === TimeEntryAggregationType::Month) {
return 'to_char('.$dateWithTimeZone.', \'YYYY-MM\')';
} elseif ($group === TimeEntryAggregationType::Year) {
return 'to_char('.$dateWithTimeZone.', \'YYYY\')';
} elseif ($group === TimeEntryAggregationType::User) {
return 'user_id';
} elseif ($group === TimeEntryAggregationType::Project) {
return 'project_id';
} elseif ($group === TimeEntryAggregationType::Task) {
return 'task_id';
} elseif ($group === TimeEntryAggregationType::Client) {
return 'client_id';
} elseif ($group === TimeEntryAggregationType::Billable) {
return 'billable';
}
}
/**
* @return Collection<int, string>
*/
public function timeSlotsBetween(Carbon $start, Carbon $end, string $timezone, Weekday $startOfWeek, TimeEntryAggregationTypeInterval $interval, string $format): Collection
{
if ($start->gt($end)) {
throw new \InvalidArgumentException('Start date must be before end date');
}
$slots = new Collection();
$current = $start->copy()->timezone($timezone);
if ($interval === TimeEntryAggregationTypeInterval::Day) {
$current->startOfDay();
} elseif ($interval === TimeEntryAggregationTypeInterval::Week) {
$current->startOfWeek($startOfWeek->carbonWeekDay())->utc();
} elseif ($interval === TimeEntryAggregationTypeInterval::Month) {
$current->startOfMonth();
} elseif ($interval === TimeEntryAggregationTypeInterval::Year) {
$current->startOfYear();
} else {
throw new \InvalidArgumentException('Invalid interval');
}
while ($current->lt($end)) {
$slots->push($current->format($format));
if ($interval === TimeEntryAggregationTypeInterval::Day) {
$current->addDay();
} elseif ($interval === TimeEntryAggregationTypeInterval::Week) {
$current->addWeek();
} elseif ($interval === TimeEntryAggregationTypeInterval::Month) {
$current->addMonth();
} elseif ($interval === TimeEntryAggregationTypeInterval::Year) {
$current->addYear();
}
}
return $slots;
}
}

View File

@@ -5,8 +5,8 @@ declare(strict_types=1);
namespace App\Service;
use App\Models\User;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
class TimezoneService