mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-08-08 00:02:15 +01:00
add break time entries and simplified time tracker ui
This commit is contained in:
@@ -21,6 +21,7 @@ enum TimeEntryAggregationType: string
|
|||||||
case Billable = 'billable';
|
case Billable = 'billable';
|
||||||
case Description = 'description';
|
case Description = 'description';
|
||||||
case Tag = 'tag';
|
case Tag = 'tag';
|
||||||
|
case Type = 'type';
|
||||||
|
|
||||||
public static function fromInterval(TimeEntryAggregationTypeInterval $timeEntryAggregationTypeInterval): TimeEntryAggregationType
|
public static function fromInterval(TimeEntryAggregationTypeInterval $timeEntryAggregationTypeInterval): TimeEntryAggregationType
|
||||||
{
|
{
|
||||||
|
|||||||
15
app/Enums/TimeEntryType.php
Normal file
15
app/Enums/TimeEntryType.php
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Enums;
|
||||||
|
|
||||||
|
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||||
|
|
||||||
|
enum TimeEntryType: string
|
||||||
|
{
|
||||||
|
use LaravelEnumHelper;
|
||||||
|
|
||||||
|
case Work = 'work';
|
||||||
|
case Break = 'break';
|
||||||
|
}
|
||||||
@@ -78,6 +78,9 @@ class OrganizationController extends Controller
|
|||||||
if ($request->getPreventOverlappingTimeEntries() !== null) {
|
if ($request->getPreventOverlappingTimeEntries() !== null) {
|
||||||
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
|
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
|
||||||
}
|
}
|
||||||
|
if ($request->getBreaksEnabled() !== null) {
|
||||||
|
$organization->breaks_enabled = $request->getBreaksEnabled();
|
||||||
|
}
|
||||||
$hasBillableRate = $request->has('billable_rate');
|
$hasBillableRate = $request->has('billable_rate');
|
||||||
if ($hasBillableRate) {
|
if ($hasBillableRate) {
|
||||||
$oldBillableRate = $organization->billable_rate;
|
$oldBillableRate = $organization->billable_rate;
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ class ReportController extends Controller
|
|||||||
$filter->addEnd($properties->end);
|
$filter->addEnd($properties->end);
|
||||||
$filter->addActive($properties->active);
|
$filter->addActive($properties->active);
|
||||||
$filter->addBillable($properties->billable);
|
$filter->addBillable($properties->billable);
|
||||||
|
$filter->addType($properties->timeEntryType);
|
||||||
$filter->addMemberIdsFilter($properties->memberIds?->toArray());
|
$filter->addMemberIdsFilter($properties->memberIds?->toArray());
|
||||||
$filter->addProjectIdsFilter($properties->projectIds?->toArray());
|
$filter->addProjectIdsFilter($properties->projectIds?->toArray());
|
||||||
$filter->addTagIdsFilter($properties->tagIds?->toArray(), $properties->tagMatchType);
|
$filter->addTagIdsFilter($properties->tagIds?->toArray(), $properties->tagMatchType);
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ class ReportController extends Controller
|
|||||||
$properties->timezone = $timezone;
|
$properties->timezone = $timezone;
|
||||||
$properties->roundingType = $request->getPropertyRoundingType();
|
$properties->roundingType = $request->getPropertyRoundingType();
|
||||||
$properties->roundingMinutes = $request->getPropertyRoundingMinutes();
|
$properties->roundingMinutes = $request->getPropertyRoundingMinutes();
|
||||||
|
$properties->timeEntryType = $request->getPropertyTimeEntryType();
|
||||||
$report->properties = $properties;
|
$report->properties = $properties;
|
||||||
if ($isPublic) {
|
if ($isPublic) {
|
||||||
$report->share_secret = $reportService->generateSecret();
|
$report->share_secret = $reportService->generateSecret();
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace App\Http\Controllers\Api\V1;
|
|||||||
|
|
||||||
use App\Enums\ExportFormat;
|
use App\Enums\ExportFormat;
|
||||||
use App\Enums\Role;
|
use App\Enums\Role;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
||||||
use App\Exceptions\Api\OverlappingTimeEntryApiException;
|
use App\Exceptions\Api\OverlappingTimeEntryApiException;
|
||||||
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
||||||
@@ -209,6 +210,7 @@ class TimeEntryController extends Controller
|
|||||||
$filter->addTaskIdsFilter($request->input('task_ids'));
|
$filter->addTaskIdsFilter($request->input('task_ids'));
|
||||||
$filter->addClientIdsFilter($request->input('client_ids'));
|
$filter->addClientIdsFilter($request->input('client_ids'));
|
||||||
$filter->addBillableFilter($request->input('billable'));
|
$filter->addBillableFilter($request->input('billable'));
|
||||||
|
$filter->addTypeFilter($request->input('type'));
|
||||||
|
|
||||||
return $filter->get();
|
return $filter->get();
|
||||||
}
|
}
|
||||||
@@ -568,6 +570,7 @@ class TimeEntryController extends Controller
|
|||||||
$filter->addTaskIdsFilter($request->input('task_ids'));
|
$filter->addTaskIdsFilter($request->input('task_ids'));
|
||||||
$filter->addClientIdsFilter($request->input('client_ids'));
|
$filter->addClientIdsFilter($request->input('client_ids'));
|
||||||
$filter->addBillableFilter($request->input('billable'));
|
$filter->addBillableFilter($request->input('billable'));
|
||||||
|
$filter->addTypeFilter($request->input('type'));
|
||||||
|
|
||||||
return $filter->get();
|
return $filter->get();
|
||||||
}
|
}
|
||||||
@@ -759,6 +762,19 @@ class TimeEntryController extends Controller
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
// Changing time entries to Break entries is only allowed when breaks are enabled in the org settings
|
||||||
|
$resultingType = isset($changes['type']) ? TimeEntryType::from($changes['type']) : $timeEntry->type;
|
||||||
|
if ($resultingType === TimeEntryType::Break && $timeEntry->type !== TimeEntryType::Break && ! $organization->breaks_enabled) {
|
||||||
|
$error->push($id);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Break entries can not be billable, have tags or belong to a project/task (see TimeEntry::booted)
|
||||||
|
if ($resultingType === TimeEntryType::Break && ($project !== null || $task !== null || $request->boolean('changes.billable') || count($changes['tags'] ?? []) > 0)) {
|
||||||
|
$error->push($id);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$oldProject = $timeEntry->project;
|
$oldProject = $timeEntry->project;
|
||||||
$oldTask = $timeEntry->task;
|
$oldTask = $timeEntry->task;
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
|||||||
'prevent_overlapping_time_entries' => [
|
'prevent_overlapping_time_entries' => [
|
||||||
'boolean',
|
'boolean',
|
||||||
],
|
],
|
||||||
|
'breaks_enabled' => [
|
||||||
|
'boolean',
|
||||||
|
],
|
||||||
'number_format' => [
|
'number_format' => [
|
||||||
Rule::enum(NumberFormat::class),
|
Rule::enum(NumberFormat::class),
|
||||||
],
|
],
|
||||||
@@ -125,4 +128,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
|||||||
{
|
{
|
||||||
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
|
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getBreaksEnabled(): ?bool
|
||||||
|
{
|
||||||
|
return $this->has('breaks_enabled') ? $this->boolean('breaks_enabled') : null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use App\Enums\TagMatchType;
|
|||||||
use App\Enums\TimeEntryAggregationType;
|
use App\Enums\TimeEntryAggregationType;
|
||||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Enums\Weekday;
|
use App\Enums\Weekday;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
@@ -177,6 +178,12 @@ class ReportStoreRequest extends BaseFormRequest
|
|||||||
'numeric',
|
'numeric',
|
||||||
'integer',
|
'integer',
|
||||||
],
|
],
|
||||||
|
// Filter by time entry type
|
||||||
|
'properties.time_entry_type' => [
|
||||||
|
'nullable',
|
||||||
|
'string',
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,6 +247,15 @@ class ReportStoreRequest extends BaseFormRequest
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getPropertyTimeEntryType(): ?TimeEntryType
|
||||||
|
{
|
||||||
|
if (! $this->has('properties.time_entry_type') || $this->input('properties.time_entry_type') === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TimeEntryType::from($this->input('properties.time_entry_type'));
|
||||||
|
}
|
||||||
|
|
||||||
public function getPropertyGroup(): TimeEntryAggregationType
|
public function getPropertyGroup(): TimeEntryAggregationType
|
||||||
{
|
{
|
||||||
return TimeEntryAggregationType::from($this->input('properties.group'));
|
return TimeEntryAggregationType::from($this->input('properties.group'));
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use App\Enums\TagMatchType;
|
|||||||
use App\Enums\TimeEntryAggregationType;
|
use App\Enums\TimeEntryAggregationType;
|
||||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
@@ -183,6 +184,11 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
|||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
],
|
],
|
||||||
|
// Filter by time entry type
|
||||||
|
'type' => [
|
||||||
|
'string',
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
],
|
||||||
'fill_gaps_in_time_groups' => [
|
'fill_gaps_in_time_groups' => [
|
||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
|||||||
use App\Enums\TagMatchType;
|
use App\Enums\TagMatchType;
|
||||||
use App\Enums\TimeEntryAggregationType;
|
use App\Enums\TimeEntryAggregationType;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
@@ -169,6 +170,11 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
|||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
],
|
],
|
||||||
|
// Filter by time entry type
|
||||||
|
'type' => [
|
||||||
|
'string',
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
],
|
||||||
'fill_gaps_in_time_groups' => [
|
'fill_gaps_in_time_groups' => [
|
||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
|||||||
use App\Enums\ExportFormat;
|
use App\Enums\ExportFormat;
|
||||||
use App\Enums\TagMatchType;
|
use App\Enums\TagMatchType;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
@@ -155,6 +156,11 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
|||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
],
|
],
|
||||||
|
// Filter by time entry type
|
||||||
|
'type' => [
|
||||||
|
'string',
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
],
|
||||||
// Limit the number of returned time entries (default: 150)
|
// Limit the number of returned time entries (default: 150)
|
||||||
'limit' => [
|
'limit' => [
|
||||||
'integer',
|
'integer',
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
|||||||
|
|
||||||
use App\Enums\TagMatchType;
|
use App\Enums\TagMatchType;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Client;
|
use App\Models\Client;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
@@ -148,6 +149,11 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
|||||||
'string',
|
'string',
|
||||||
'in:true,false',
|
'in:true,false',
|
||||||
],
|
],
|
||||||
|
// Filter by time entry type
|
||||||
|
'type' => [
|
||||||
|
'string',
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
],
|
||||||
// Limit the number of returned time entries (default: 150)
|
// Limit the number of returned time entries (default: 150)
|
||||||
'limit' => [
|
'limit' => [
|
||||||
'integer',
|
'integer',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Http\Requests\V1\TimeEntry;
|
namespace App\Http\Requests\V1\TimeEntry;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
@@ -14,6 +15,7 @@ use App\Service\PermissionStore;
|
|||||||
use Illuminate\Contracts\Validation\ValidationRule;
|
use Illuminate\Contracts\Validation\ValidationRule;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +26,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
|||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* Get the validation rules that apply to the request.
|
||||||
*
|
*
|
||||||
* @return array<string, array<string|ValidationRule>>
|
* @return array<string, array<string|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||||
*/
|
*/
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
@@ -42,6 +44,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
|||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
'required_with:task_id',
|
'required_with:task_id',
|
||||||
|
'prohibited_if:type,break',
|
||||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Project> $builder */
|
/** @var Builder<Project> $builder */
|
||||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -60,6 +63,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
|||||||
'task_id' => [
|
'task_id' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
|
'prohibited_if:type,break',
|
||||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Task> $builder */
|
/** @var Builder<Task> $builder */
|
||||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -85,6 +89,16 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
|||||||
'billable' => [
|
'billable' => [
|
||||||
'required',
|
'required',
|
||||||
'boolean',
|
'boolean',
|
||||||
|
'declined_if:type,break',
|
||||||
|
],
|
||||||
|
// Type of the time entry (work time or a break)
|
||||||
|
'type' => [
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||||
|
if ($value === TimeEntryType::Break->value && ! $this->organization->breaks_enabled) {
|
||||||
|
$fail('Breaks are disabled for this organization.');
|
||||||
|
}
|
||||||
|
},
|
||||||
],
|
],
|
||||||
// Description of time entry
|
// Description of time entry
|
||||||
'description' => [
|
'description' => [
|
||||||
@@ -96,6 +110,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
|||||||
'tags' => [
|
'tags' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'array',
|
'array',
|
||||||
|
'prohibited_if:type,break',
|
||||||
],
|
],
|
||||||
'tags.*' => [
|
'tags.*' => [
|
||||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Http\Requests\V1\TimeEntry;
|
namespace App\Http\Requests\V1\TimeEntry;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
@@ -14,6 +15,7 @@ use App\Service\PermissionStore;
|
|||||||
use Illuminate\Contracts\Validation\ValidationRule;
|
use Illuminate\Contracts\Validation\ValidationRule;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,7 +26,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
|||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* 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
|
public function rules(): array
|
||||||
{
|
{
|
||||||
@@ -54,6 +56,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
|||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
'required_with:task_id',
|
'required_with:task_id',
|
||||||
|
'prohibited_if:changes.type,break',
|
||||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Project> $builder */
|
/** @var Builder<Project> $builder */
|
||||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -72,6 +75,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
|||||||
'changes.task_id' => [
|
'changes.task_id' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
|
'prohibited_if:changes.type,break',
|
||||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Task> $builder */
|
/** @var Builder<Task> $builder */
|
||||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -84,7 +88,13 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
|||||||
],
|
],
|
||||||
// Whether time entry is billable
|
// Whether time entry is billable
|
||||||
'changes.billable' => [
|
'changes.billable' => [
|
||||||
|
'sometimes',
|
||||||
'boolean',
|
'boolean',
|
||||||
|
'declined_if:changes.type,break',
|
||||||
|
],
|
||||||
|
// Type of the time entry (work time or a break)
|
||||||
|
'changes.type' => [
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
],
|
],
|
||||||
// Description of time entry
|
// Description of time entry
|
||||||
'changes.description' => [
|
'changes.description' => [
|
||||||
@@ -96,6 +106,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
|||||||
'changes.tags' => [
|
'changes.tags' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'array',
|
'array',
|
||||||
|
'prohibited_if:changes.type,break',
|
||||||
],
|
],
|
||||||
'changes.tags.*' => [
|
'changes.tags.*' => [
|
||||||
'string',
|
'string',
|
||||||
|
|||||||
@@ -4,16 +4,21 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Http\Requests\V1\TimeEntry;
|
namespace App\Http\Requests\V1\TimeEntry;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Http\Requests\V1\BaseFormRequest;
|
use App\Http\Requests\V1\BaseFormRequest;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
use App\Models\Tag;
|
use App\Models\Tag;
|
||||||
use App\Models\Task;
|
use App\Models\Task;
|
||||||
|
use App\Models\TimeEntry;
|
||||||
use App\Service\PermissionStore;
|
use App\Service\PermissionStore;
|
||||||
use Illuminate\Contracts\Validation\ValidationRule;
|
use Illuminate\Contracts\Validation\ValidationRule;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Validation\ConditionalRules;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\Rules\ProhibitedIf;
|
||||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,10 +29,19 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
|||||||
/**
|
/**
|
||||||
* Get the validation rules that apply to the request.
|
* Get the validation rules that apply to the request.
|
||||||
*
|
*
|
||||||
* @return array<string, array<string|ValidationRule>>
|
* @return array<string, array<string|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule|ProhibitedIf|ConditionalRules>>
|
||||||
*/
|
*/
|
||||||
public function rules(): array
|
public function rules(): array
|
||||||
{
|
{
|
||||||
|
// Break restrictions need to apply based on the type the entry will have after the
|
||||||
|
// update, not only when the payload itself contains type=break.
|
||||||
|
$timeEntry = $this->route('timeEntry');
|
||||||
|
$timeEntry = $timeEntry instanceof TimeEntry ? $timeEntry : null;
|
||||||
|
$resultingType = $this->has('type')
|
||||||
|
? TimeEntryType::tryFrom((string) $this->input('type'))
|
||||||
|
: $timeEntry?->type;
|
||||||
|
$isBreak = $resultingType === TimeEntryType::Break;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
// ID of the organization member that the time entry should belong to
|
// ID of the organization member that the time entry should belong to
|
||||||
'member_id' => [
|
'member_id' => [
|
||||||
@@ -42,6 +56,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
|||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
'required_with:task_id',
|
'required_with:task_id',
|
||||||
|
Rule::prohibitedIf($isBreak),
|
||||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Project> $builder */
|
/** @var Builder<Project> $builder */
|
||||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -60,6 +75,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
|||||||
'task_id' => [
|
'task_id' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'string',
|
'string',
|
||||||
|
Rule::prohibitedIf($isBreak),
|
||||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||||
/** @var Builder<Task> $builder */
|
/** @var Builder<Task> $builder */
|
||||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||||
@@ -82,7 +98,22 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
|||||||
],
|
],
|
||||||
// Whether time entry is billable
|
// Whether time entry is billable
|
||||||
'billable' => [
|
'billable' => [
|
||||||
|
'sometimes',
|
||||||
'boolean',
|
'boolean',
|
||||||
|
Rule::when($isBreak, ['declined']),
|
||||||
|
],
|
||||||
|
// Type of the time entry (work time or a break)
|
||||||
|
'type' => [
|
||||||
|
Rule::enum(TimeEntryType::class),
|
||||||
|
function (string $attribute, mixed $value, \Closure $fail) use ($timeEntry): void {
|
||||||
|
// While breaks are disabled, entries that already are breaks may stay
|
||||||
|
// breaks, but converting a work entry to a break is not allowed.
|
||||||
|
if ($value === TimeEntryType::Break->value
|
||||||
|
&& ! $this->organization->breaks_enabled
|
||||||
|
&& $timeEntry?->type !== TimeEntryType::Break) {
|
||||||
|
$fail('Breaks are disabled for this organization.');
|
||||||
|
}
|
||||||
|
},
|
||||||
],
|
],
|
||||||
// Description of time entry
|
// Description of time entry
|
||||||
'description' => [
|
'description' => [
|
||||||
@@ -94,6 +125,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
|||||||
'tags' => [
|
'tags' => [
|
||||||
'nullable',
|
'nullable',
|
||||||
'array',
|
'array',
|
||||||
|
Rule::prohibitedIf($isBreak),
|
||||||
],
|
],
|
||||||
'tags.*' => [
|
'tags.*' => [
|
||||||
'string',
|
'string',
|
||||||
|
|||||||
@@ -57,6 +57,8 @@ class OrganizationResource extends BaseResource
|
|||||||
'employees_can_manage_tasks' => $this->resource->employees_can_manage_tasks,
|
'employees_can_manage_tasks' => $this->resource->employees_can_manage_tasks,
|
||||||
/** @var bool $prevent_overlapping_time_entries Prevent creating overlapping time entries (only new entries) */
|
/** @var bool $prevent_overlapping_time_entries Prevent creating overlapping time entries (only new entries) */
|
||||||
'prevent_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
|
'prevent_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
|
||||||
|
/** @var bool $breaks_enabled Whether members of the organization can track breaks */
|
||||||
|
'breaks_enabled' => $this->resource->breaks_enabled,
|
||||||
/** @var string $currency Currency code (ISO 4217) */
|
/** @var string $currency Currency code (ISO 4217) */
|
||||||
'currency' => $this->resource->currency,
|
'currency' => $this->resource->currency,
|
||||||
/** @var string $currency_symbol Currency symbol */
|
/** @var string $currency_symbol Currency symbol */
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ class DetailedReportResource extends BaseResource
|
|||||||
'member_ids' => $this->resource->properties->memberIds?->toArray(),
|
'member_ids' => $this->resource->properties->memberIds?->toArray(),
|
||||||
/** @var bool|null $billable Filter by billable status */
|
/** @var bool|null $billable Filter by billable status */
|
||||||
'billable' => $this->resource->properties->billable,
|
'billable' => $this->resource->properties->billable,
|
||||||
|
/** @var string|null $time_entry_type Filter by time entry type */
|
||||||
|
'time_entry_type' => $this->resource->properties->timeEntryType?->value,
|
||||||
/** @var array<string>|null $client_ids Filter by client IDs, client IDs are OR combined */
|
/** @var array<string>|null $client_ids Filter by client IDs, client IDs are OR combined */
|
||||||
'client_ids' => $this->resource->properties->clientIds?->toArray(),
|
'client_ids' => $this->resource->properties->clientIds?->toArray(),
|
||||||
/** @var array<string>|null $project_ids Filter by project IDs, project IDs are OR combined */
|
/** @var array<string>|null $project_ids Filter by project IDs, project IDs are OR combined */
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ class TimeEntryResource extends BaseResource
|
|||||||
'tags' => $this->resource->tags ?? [],
|
'tags' => $this->resource->tags ?? [],
|
||||||
/** @var bool $billable Whether time entry is billable */
|
/** @var bool $billable Whether time entry is billable */
|
||||||
'billable' => $this->resource->billable,
|
'billable' => $this->resource->billable,
|
||||||
|
/** @var string $type Type of the time entry (`work` time or a `break`) */
|
||||||
|
'type' => $this->resource->type->value,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
|||||||
* @property bool $employees_can_see_billable_rates
|
* @property bool $employees_can_see_billable_rates
|
||||||
* @property bool $employees_can_manage_tasks
|
* @property bool $employees_can_manage_tasks
|
||||||
* @property bool $prevent_overlapping_time_entries
|
* @property bool $prevent_overlapping_time_entries
|
||||||
|
* @property bool $breaks_enabled
|
||||||
* @property User $owner
|
* @property User $owner
|
||||||
* @property Carbon|null $created_at
|
* @property Carbon|null $created_at
|
||||||
* @property Carbon|null $updated_at
|
* @property Carbon|null $updated_at
|
||||||
@@ -70,6 +71,7 @@ class Organization extends Model implements AuditableContract
|
|||||||
'employees_can_see_billable_rates' => 'boolean',
|
'employees_can_see_billable_rates' => 'boolean',
|
||||||
'employees_can_manage_tasks' => 'boolean',
|
'employees_can_manage_tasks' => 'boolean',
|
||||||
'prevent_overlapping_time_entries' => 'boolean',
|
'prevent_overlapping_time_entries' => 'boolean',
|
||||||
|
'breaks_enabled' => 'boolean',
|
||||||
'number_format' => NumberFormat::class,
|
'number_format' => NumberFormat::class,
|
||||||
'currency_format' => CurrencyFormat::class,
|
'currency_format' => CurrencyFormat::class,
|
||||||
'date_format' => DateFormat::class,
|
'date_format' => DateFormat::class,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\Concerns\CustomAuditable;
|
use App\Models\Concerns\CustomAuditable;
|
||||||
use App\Models\Concerns\HasUuids;
|
use App\Models\Concerns\HasUuids;
|
||||||
use App\Service\BillableRateService;
|
use App\Service\BillableRateService;
|
||||||
@@ -28,6 +29,7 @@ use Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson;
|
|||||||
* @property Carbon|null $end
|
* @property Carbon|null $end
|
||||||
* @property int|null $billable_rate Billable rate per hour in cents
|
* @property int|null $billable_rate Billable rate per hour in cents
|
||||||
* @property bool $billable
|
* @property bool $billable
|
||||||
|
* @property TimeEntryType $type
|
||||||
* @property array<string> $tags
|
* @property array<string> $tags
|
||||||
* @property string $user_id
|
* @property string $user_id
|
||||||
* @property string $member_id
|
* @property string $member_id
|
||||||
@@ -71,12 +73,20 @@ class TimeEntry extends Model implements AuditableContract
|
|||||||
'start' => 'datetime',
|
'start' => 'datetime',
|
||||||
'end' => 'datetime',
|
'end' => 'datetime',
|
||||||
'billable' => 'bool',
|
'billable' => 'bool',
|
||||||
|
'type' => TimeEntryType::class,
|
||||||
'tags' => 'array',
|
'tags' => 'array',
|
||||||
'billable_rate' => 'int',
|
'billable_rate' => 'int',
|
||||||
'is_imported' => 'bool',
|
'is_imported' => 'bool',
|
||||||
'still_active_email_sent_at' => 'datetime',
|
'still_active_email_sent_at' => 'datetime',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array<string, string>
|
||||||
|
*/
|
||||||
|
protected $attributes = [
|
||||||
|
'type' => 'work',
|
||||||
|
];
|
||||||
|
|
||||||
public const array SELECT_COLUMNS = [
|
public const array SELECT_COLUMNS = [
|
||||||
'id',
|
'id',
|
||||||
'description',
|
'description',
|
||||||
@@ -84,6 +94,7 @@ class TimeEntry extends Model implements AuditableContract
|
|||||||
'end',
|
'end',
|
||||||
'billable_rate',
|
'billable_rate',
|
||||||
'billable',
|
'billable',
|
||||||
|
'type',
|
||||||
'user_id',
|
'user_id',
|
||||||
'organization_id',
|
'organization_id',
|
||||||
'project_id',
|
'project_id',
|
||||||
@@ -117,6 +128,21 @@ class TimeEntry extends Model implements AuditableContract
|
|||||||
'billable_rate',
|
'billable_rate',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
protected static function booted(): void
|
||||||
|
{
|
||||||
|
// Break entries can never be billable, have tags or belong to a project/task.
|
||||||
|
static::saving(function (TimeEntry $timeEntry): void {
|
||||||
|
if ($timeEntry->type === TimeEntryType::Break) {
|
||||||
|
$timeEntry->billable = false;
|
||||||
|
$timeEntry->billable_rate = null;
|
||||||
|
$timeEntry->project_id = null;
|
||||||
|
$timeEntry->task_id = null;
|
||||||
|
$timeEntry->client_id = null;
|
||||||
|
$timeEntry->tags = [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public function getBillableRateComputed(): ?int
|
public function getBillableRateComputed(): ?int
|
||||||
{
|
{
|
||||||
return app(BillableRateService::class)->getBillableRateForTimeEntry($this);
|
return app(BillableRateService::class)->getBillableRateForTimeEntry($this);
|
||||||
@@ -173,6 +199,16 @@ class TimeEntry extends Model implements AuditableContract
|
|||||||
$builder->whereJsonContains('tags', $tag->getKey());
|
$builder->whereJsonContains('tags', $tag->getKey());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only work entries — breaks do not count toward tracked/billable time.
|
||||||
|
*
|
||||||
|
* @param Builder<TimeEntry> $builder
|
||||||
|
*/
|
||||||
|
public function scopeWorkTime(Builder $builder): void
|
||||||
|
{
|
||||||
|
$builder->where('type', '=', TimeEntryType::Work);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return BelongsTo<User, $this>
|
* @return BelongsTo<User, $this>
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Service;
|
namespace App\Service;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Enums\Weekday;
|
use App\Enums\Weekday;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
@@ -154,6 +155,7 @@ class DashboardService
|
|||||||
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||||
->where('user_id', '=', $user->getKey())
|
->where('user_id', '=', $user->getKey())
|
||||||
->where('organization_id', '=', $organization->getKey())
|
->where('organization_id', '=', $organization->getKey())
|
||||||
|
->workTime()
|
||||||
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
||||||
->orderBy('date');
|
->orderBy('date');
|
||||||
|
|
||||||
@@ -195,6 +197,7 @@ class DashboardService
|
|||||||
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||||
->where('user_id', '=', $user->getKey())
|
->where('user_id', '=', $user->getKey())
|
||||||
->where('organization_id', '=', $organization->getKey())
|
->where('organization_id', '=', $organization->getKey())
|
||||||
|
->workTime()
|
||||||
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
||||||
->orderBy('date');
|
->orderBy('date');
|
||||||
|
|
||||||
@@ -222,7 +225,8 @@ class DashboardService
|
|||||||
$query = TimeEntry::query()
|
$query = TimeEntry::query()
|
||||||
->select(DB::raw('round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
->select(DB::raw('round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||||
->where('user_id', '=', $user->getKey())
|
->where('user_id', '=', $user->getKey())
|
||||||
->where('organization_id', '=', $organization->getKey());
|
->where('organization_id', '=', $organization->getKey())
|
||||||
|
->workTime();
|
||||||
|
|
||||||
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);
|
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);
|
||||||
/** @var Collection<int, object{aggregate: int}> $resultDb */
|
/** @var Collection<int, object{aggregate: int}> $resultDb */
|
||||||
@@ -290,6 +294,7 @@ class DashboardService
|
|||||||
->select(DB::raw('project_id, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
->select(DB::raw('project_id, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||||
->where('user_id', '=', $user->getKey())
|
->where('user_id', '=', $user->getKey())
|
||||||
->where('organization_id', '=', $organization->getKey())
|
->where('organization_id', '=', $organization->getKey())
|
||||||
|
->workTime()
|
||||||
->groupBy('project_id');
|
->groupBy('project_id');
|
||||||
|
|
||||||
$query = $this->constrainDateByCurrentWeek($query, $timezone, $user->week_start);
|
$query = $this->constrainDateByCurrentWeek($query, $timezone, $user->week_start);
|
||||||
@@ -433,7 +438,8 @@ class DashboardService
|
|||||||
JOIN time_entries ON time_entries.start < time_ranges."end"
|
JOIN time_entries ON time_entries.start < time_ranges."end"
|
||||||
AND coalesce(time_entries."end", :now::timestamp) > time_ranges.start
|
AND coalesce(time_entries."end", :now::timestamp) > time_ranges.start
|
||||||
WHERE time_entries.user_id = :user_id and
|
WHERE time_entries.user_id = :user_id and
|
||||||
time_entries.organization_id = :organization_id
|
time_entries.organization_id = :organization_id and
|
||||||
|
time_entries.type = :work_type
|
||||||
GROUP BY time_ranges.start
|
GROUP BY time_ranges.start
|
||||||
ORDER BY time_ranges.start
|
ORDER BY time_ranges.start
|
||||||
', [
|
', [
|
||||||
@@ -442,6 +448,7 @@ class DashboardService
|
|||||||
'user_id' => $user->getKey(),
|
'user_id' => $user->getKey(),
|
||||||
'organization_id' => $organization->getKey(),
|
'organization_id' => $organization->getKey(),
|
||||||
'now' => Carbon::now()->toDateTimeString(),
|
'now' => Carbon::now()->toDateTimeString(),
|
||||||
|
'work_type' => TimeEntryType::Work->value,
|
||||||
]))->pluck('aggregate', 'start');
|
]))->pluck('aggregate', 'start');
|
||||||
|
|
||||||
$response = [];
|
$response = [];
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use App\Enums\TagMatchType;
|
|||||||
use App\Enums\TimeEntryAggregationType;
|
use App\Enums\TimeEntryAggregationType;
|
||||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||||
use App\Enums\TimeEntryRoundingType;
|
use App\Enums\TimeEntryRoundingType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Enums\Weekday;
|
use App\Enums\Weekday;
|
||||||
use App\Service\TimeEntryFilter;
|
use App\Service\TimeEntryFilter;
|
||||||
use Illuminate\Contracts\Database\Eloquent\Castable;
|
use Illuminate\Contracts\Database\Eloquent\Castable;
|
||||||
@@ -68,6 +69,8 @@ class ReportPropertiesDto implements Castable
|
|||||||
|
|
||||||
public ?int $roundingMinutes = null;
|
public ?int $roundingMinutes = null;
|
||||||
|
|
||||||
|
public ?TimeEntryType $timeEntryType = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the caster class to use when casting from / to this cast target.
|
* Get the caster class to use when casting from / to this cast target.
|
||||||
*
|
*
|
||||||
@@ -129,6 +132,8 @@ class ReportPropertiesDto implements Castable
|
|||||||
$dto->roundingType = isset($data->roundingType) ? TimeEntryRoundingType::from($data->roundingType) : null;
|
$dto->roundingType = isset($data->roundingType) ? TimeEntryRoundingType::from($data->roundingType) : null;
|
||||||
// Note: roundingMinutes was added later so it is possible that the value is missing in persisted reports in the DB
|
// Note: roundingMinutes was added later so it is possible that the value is missing in persisted reports in the DB
|
||||||
$dto->roundingMinutes = isset($data->roundingMinutes) ? (int) $data->roundingMinutes : null;
|
$dto->roundingMinutes = isset($data->roundingMinutes) ? (int) $data->roundingMinutes : null;
|
||||||
|
// Note: timeEntryType was added later so it is possible that the value is missing in persisted reports in the DB
|
||||||
|
$dto->timeEntryType = isset($data->timeEntryType) ? TimeEntryType::from($data->timeEntryType) : null;
|
||||||
|
|
||||||
return $dto;
|
return $dto;
|
||||||
}
|
}
|
||||||
@@ -157,6 +162,7 @@ class ReportPropertiesDto implements Castable
|
|||||||
'timezone' => $value->timezone,
|
'timezone' => $value->timezone,
|
||||||
'roundingType' => $value->roundingType?->value,
|
'roundingType' => $value->roundingType?->value,
|
||||||
'roundingMinutes' => $value->roundingMinutes,
|
'roundingMinutes' => $value->roundingMinutes,
|
||||||
|
'timeEntryType' => $value->timeEntryType?->value,
|
||||||
];
|
];
|
||||||
|
|
||||||
$jsonString = json_encode($data);
|
$jsonString = json_encode($data);
|
||||||
|
|||||||
@@ -107,6 +107,7 @@ class ExportService
|
|||||||
'end',
|
'end',
|
||||||
'billable_rate',
|
'billable_rate',
|
||||||
'billable',
|
'billable',
|
||||||
|
'type',
|
||||||
'member_id',
|
'member_id',
|
||||||
'user_id',
|
'user_id',
|
||||||
'organization_id',
|
'organization_id',
|
||||||
@@ -131,6 +132,7 @@ class ExportService
|
|||||||
$timeEntry->end?->toIso8601ZuluString() ?? '',
|
$timeEntry->end?->toIso8601ZuluString() ?? '',
|
||||||
$timeEntry->billable_rate ?? '',
|
$timeEntry->billable_rate ?? '',
|
||||||
$timeEntry->billable ? 'true' : 'false',
|
$timeEntry->billable ? 'true' : 'false',
|
||||||
|
$timeEntry->type->value,
|
||||||
$timeEntry->member_id,
|
$timeEntry->member_id,
|
||||||
$timeEntry->user_id,
|
$timeEntry->user_id,
|
||||||
$timeEntry->organization_id,
|
$timeEntry->organization_id,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Service\Import\Importers;
|
namespace App\Service\Import\Importers;
|
||||||
|
|
||||||
use App\Enums\Role;
|
use App\Enums\Role;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Jobs\RecalculateSpentTimeForProject;
|
use App\Jobs\RecalculateSpentTimeForProject;
|
||||||
use App\Jobs\RecalculateSpentTimeForTask;
|
use App\Jobs\RecalculateSpentTimeForTask;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
@@ -71,8 +72,12 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
|||||||
'role' => Role::Placeholder->value,
|
'role' => Role::Placeholder->value,
|
||||||
]);
|
]);
|
||||||
$member = $this->memberImportHelper->getModelById($memberId);
|
$member = $this->memberImportHelper->getModelById($memberId);
|
||||||
|
// Clockify allows a project/task/client/tags/billable on breaks, but those are
|
||||||
|
// meaningless for non-work time. Detect breaks up front and skip creating any of
|
||||||
|
// that so a break can't spawn an orphan project/tag or inflate the import counts.
|
||||||
|
$isBreak = isset($record['Type']) && strtolower($record['Type']) === 'break';
|
||||||
$clientId = null;
|
$clientId = null;
|
||||||
if (($record['Client'] ?? '') !== '') {
|
if (! $isBreak && ($record['Client'] ?? '') !== '') {
|
||||||
$clientId = $this->clientImportHelper->getKey([
|
$clientId = $this->clientImportHelper->getKey([
|
||||||
'name' => $record['Client'],
|
'name' => $record['Client'],
|
||||||
'organization_id' => $this->organization->id,
|
'organization_id' => $this->organization->id,
|
||||||
@@ -81,7 +86,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
|||||||
$projectId = null;
|
$projectId = null;
|
||||||
$project = null;
|
$project = null;
|
||||||
$projectMember = null;
|
$projectMember = null;
|
||||||
if ($record['Project'] !== '') {
|
if (! $isBreak && $record['Project'] !== '') {
|
||||||
$projectId = $this->projectImportHelper->getKey([
|
$projectId = $this->projectImportHelper->getKey([
|
||||||
'name' => $record['Project'],
|
'name' => $record['Project'],
|
||||||
'client_id' => $clientId,
|
'client_id' => $clientId,
|
||||||
@@ -97,7 +102,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
$taskId = null;
|
$taskId = null;
|
||||||
if ($taskKey !== null && $record[$taskKey] !== '') {
|
if (! $isBreak && $taskKey !== null && $record[$taskKey] !== '') {
|
||||||
$taskId = $this->taskImportHelper->getKey([
|
$taskId = $this->taskImportHelper->getKey([
|
||||||
'name' => $record[$taskKey],
|
'name' => $record[$taskKey],
|
||||||
'project_id' => $projectId,
|
'project_id' => $projectId,
|
||||||
@@ -123,7 +128,12 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
|||||||
}
|
}
|
||||||
$timeEntry->billable = $record['Billable'] === 'Yes';
|
$timeEntry->billable = $record['Billable'] === 'Yes';
|
||||||
}
|
}
|
||||||
$timeEntry->tags = $this->getTags($record['Tags']);
|
if ($isBreak) {
|
||||||
|
// Breaks can not be billable or belong to a project/task (already skipped above)
|
||||||
|
$timeEntry->type = TimeEntryType::Break;
|
||||||
|
$timeEntry->billable = false;
|
||||||
|
}
|
||||||
|
$timeEntry->tags = $isBreak ? [] : $this->getTags($record['Tags']);
|
||||||
$timeEntry->is_imported = true;
|
$timeEntry->is_imported = true;
|
||||||
|
|
||||||
// Start
|
// Start
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Service\Import\Importers;
|
namespace App\Service\Import\Importers;
|
||||||
|
|
||||||
use App\Enums\Role;
|
use App\Enums\Role;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Jobs\RecalculateSpentTimeForProject;
|
use App\Jobs\RecalculateSpentTimeForProject;
|
||||||
use App\Jobs\RecalculateSpentTimeForTask;
|
use App\Jobs\RecalculateSpentTimeForTask;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
@@ -255,6 +256,14 @@ class SolidtimeImporter extends DefaultImporter
|
|||||||
throw new ImportException('Invalid billable value');
|
throw new ImportException('Invalid billable value');
|
||||||
}
|
}
|
||||||
$timeEntry->billable = $timeEntryRow['billable'] === 'true';
|
$timeEntry->billable = $timeEntryRow['billable'] === 'true';
|
||||||
|
// The type column does not exist in old exports
|
||||||
|
if (($timeEntryRow['type'] ?? '') !== '') {
|
||||||
|
$type = TimeEntryType::tryFrom($timeEntryRow['type']);
|
||||||
|
if ($type === null) {
|
||||||
|
throw new ImportException('Invalid type value');
|
||||||
|
}
|
||||||
|
$timeEntry->type = $type;
|
||||||
|
}
|
||||||
$timeEntry->tags = $this->getTags($timeEntryRow['tags']);
|
$timeEntry->tags = $this->getTags($timeEntryRow['tags']);
|
||||||
$timeEntry->is_imported = true;
|
$timeEntry->is_imported = true;
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Service\ReportExport;
|
namespace App\Service\ReportExport;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
use App\Service\IntervalService;
|
use App\Service\IntervalService;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
@@ -25,6 +26,7 @@ class TimeEntriesDetailedCsvExport extends CsvExport
|
|||||||
'Duration',
|
'Duration',
|
||||||
'Duration (decimal)',
|
'Duration (decimal)',
|
||||||
'Billable',
|
'Billable',
|
||||||
|
'Break',
|
||||||
'Tags',
|
'Tags',
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -58,6 +60,7 @@ class TimeEntriesDetailedCsvExport extends CsvExport
|
|||||||
'Duration' => $duration !== null ? $interval->format($model->getDuration()) : null,
|
'Duration' => $duration !== null ? $interval->format($model->getDuration()) : null,
|
||||||
'Duration (decimal)' => $duration?->totalHours,
|
'Duration (decimal)' => $duration?->totalHours,
|
||||||
'Billable' => $model->billable ? 'Yes' : 'No',
|
'Billable' => $model->billable ? 'Yes' : 'No',
|
||||||
|
'Break' => $model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||||
'Tags' => $model->tagsRelation->pluck('name')->implode(', '),
|
'Tags' => $model->tagsRelation->pluck('name')->implode(', '),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Service\ReportExport;
|
namespace App\Service\ReportExport;
|
||||||
|
|
||||||
use App\Enums\ExportFormat;
|
use App\Enums\ExportFormat;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
use App\Service\LocalizationService;
|
use App\Service\LocalizationService;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
@@ -106,6 +107,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
|||||||
'Duration',
|
'Duration',
|
||||||
'Duration (decimal)',
|
'Duration (decimal)',
|
||||||
'Billable',
|
'Billable',
|
||||||
|
'Break',
|
||||||
'Tags',
|
'Tags',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -130,6 +132,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
|||||||
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
||||||
$duration?->totalHours,
|
$duration?->totalHours,
|
||||||
$model->billable ? 'Yes' : 'No',
|
$model->billable ? 'Yes' : 'No',
|
||||||
|
$model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||||
$model->tagsRelation->pluck('name')->implode(', '),
|
$model->tagsRelation->pluck('name')->implode(', '),
|
||||||
];
|
];
|
||||||
} elseif ($this->exportFormat === ExportFormat::ODS) {
|
} elseif ($this->exportFormat === ExportFormat::ODS) {
|
||||||
@@ -144,6 +147,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
|||||||
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
||||||
$duration?->totalHours,
|
$duration?->totalHours,
|
||||||
$model->billable ? 'Yes' : 'No',
|
$model->billable ? 'Yes' : 'No',
|
||||||
|
$model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||||
$model->tagsRelation->pluck('name')->implode(', '),
|
$model->tagsRelation->pluck('name')->implode(', '),
|
||||||
];
|
];
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -353,6 +353,13 @@ class TimeEntryAggregationService
|
|||||||
'color' => null,
|
'color' => null,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
} elseif ($type === TimeEntryAggregationType::Type) {
|
||||||
|
foreach ($keys as $key) {
|
||||||
|
$descriptorMap[$key] = [
|
||||||
|
'description' => $key === 'break' ? 'Break' : 'Work time',
|
||||||
|
'color' => null,
|
||||||
|
];
|
||||||
|
}
|
||||||
} elseif ($type === TimeEntryAggregationType::Tag) {
|
} elseif ($type === TimeEntryAggregationType::Tag) {
|
||||||
$tags = Tag::query()
|
$tags = Tag::query()
|
||||||
->whereIn('id', $keys)
|
->whereIn('id', $keys)
|
||||||
@@ -504,6 +511,8 @@ class TimeEntryAggregationService
|
|||||||
return 'client_id';
|
return 'client_id';
|
||||||
} elseif ($group === TimeEntryAggregationType::Billable) {
|
} elseif ($group === TimeEntryAggregationType::Billable) {
|
||||||
return 'billable';
|
return 'billable';
|
||||||
|
} elseif ($group === TimeEntryAggregationType::Type) {
|
||||||
|
return 'type';
|
||||||
} elseif ($group === TimeEntryAggregationType::Description) {
|
} elseif ($group === TimeEntryAggregationType::Description) {
|
||||||
return 'description';
|
return 'description';
|
||||||
} elseif ($group === TimeEntryAggregationType::Tag) {
|
} elseif ($group === TimeEntryAggregationType::Tag) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
|||||||
namespace App\Service;
|
namespace App\Service;
|
||||||
|
|
||||||
use App\Enums\TagMatchType;
|
use App\Enums\TagMatchType;
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\TimeEntry;
|
use App\Models\TimeEntry;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
@@ -144,6 +145,32 @@ class TimeEntryFilter
|
|||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function addTypeFilter(?string $type): self
|
||||||
|
{
|
||||||
|
if ($type === null) {
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
$typeEnum = TimeEntryType::tryFrom($type);
|
||||||
|
if ($typeEnum === null) {
|
||||||
|
Log::warning('Invalid type filter value', ['value' => $type]);
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
$this->addType($typeEnum);
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function addType(?TimeEntryType $type): self
|
||||||
|
{
|
||||||
|
if ($type === null) {
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
$this->builder->where('type', '=', $type->value);
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array<string>|null $clientIds
|
* @param array<string>|null $clientIds
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ class OrganizationFactory extends Factory
|
|||||||
'user_id' => User::factory(),
|
'user_id' => User::factory(),
|
||||||
'personal_team' => true,
|
'personal_team' => true,
|
||||||
'employees_can_see_billable_rates' => false,
|
'employees_can_see_billable_rates' => false,
|
||||||
|
'breaks_enabled' => false,
|
||||||
'number_format' => $this->faker->randomElement(NumberFormat::values()),
|
'number_format' => $this->faker->randomElement(NumberFormat::values()),
|
||||||
'currency_format' => $this->faker->randomElement(CurrencyFormat::values()),
|
'currency_format' => $this->faker->randomElement(CurrencyFormat::values()),
|
||||||
'date_format' => $this->faker->randomElement(DateFormat::values()),
|
'date_format' => $this->faker->randomElement(DateFormat::values()),
|
||||||
@@ -55,6 +56,13 @@ class OrganizationFactory extends Factory
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function withBreaksEnabled(): self
|
||||||
|
{
|
||||||
|
return $this->state(fn (array $attributes) => [
|
||||||
|
'breaks_enabled' => true,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
public function withOwner(?User $owner = null): self
|
public function withOwner(?User $owner = null): self
|
||||||
{
|
{
|
||||||
return $this->state(fn (array $attributes) => [
|
return $this->state(fn (array $attributes) => [
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace Database\Factories;
|
namespace Database\Factories;
|
||||||
|
|
||||||
|
use App\Enums\TimeEntryType;
|
||||||
use App\Models\Member;
|
use App\Models\Member;
|
||||||
use App\Models\Organization;
|
use App\Models\Organization;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
@@ -33,6 +34,7 @@ class TimeEntryFactory extends Factory
|
|||||||
'start' => $start,
|
'start' => $start,
|
||||||
'end' => $this->faker->dateTimeBetween($start, 'now'),
|
'end' => $this->faker->dateTimeBetween($start, 'now'),
|
||||||
'billable' => $this->faker->boolean(),
|
'billable' => $this->faker->boolean(),
|
||||||
|
'type' => TimeEntryType::Work,
|
||||||
'is_imported' => false,
|
'is_imported' => false,
|
||||||
'tags' => [],
|
'tags' => [],
|
||||||
'user_id' => User::factory(),
|
'user_id' => User::factory(),
|
||||||
@@ -44,6 +46,18 @@ class TimeEntryFactory extends Factory
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function isBreak(): self
|
||||||
|
{
|
||||||
|
return $this->state(function (array $attributes): array {
|
||||||
|
return [
|
||||||
|
'type' => TimeEntryType::Break,
|
||||||
|
'billable' => false,
|
||||||
|
'project_id' => null,
|
||||||
|
'task_id' => null,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
public function notBillable(): self
|
public function notBillable(): self
|
||||||
{
|
{
|
||||||
return $this->state(function (array $attributes): array {
|
return $this->state(function (array $attributes): array {
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('time_entries', function (Blueprint $table): void {
|
||||||
|
$table->string('type')->default('work');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('time_entries', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('type');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('organizations', function (Blueprint $table): void {
|
||||||
|
$table->boolean('breaks_enabled')->default(false)->after('prevent_overlapping_time_entries');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('organizations', function (Blueprint $table): void {
|
||||||
|
$table->dropColumn('breaks_enabled');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
278
e2e/breaks.spec.ts
Normal file
278
e2e/breaks.spec.ts
Normal file
@@ -0,0 +1,278 @@
|
|||||||
|
import { expect, test } from '../playwright/fixtures';
|
||||||
|
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||||
|
import type { Page } from '@playwright/test';
|
||||||
|
import {
|
||||||
|
assertThatTimerHasStarted,
|
||||||
|
assertThatTimerIsStopped,
|
||||||
|
newTimeEntryResponse,
|
||||||
|
startOrStopTimerWithButton,
|
||||||
|
stoppedTimeEntryResponse,
|
||||||
|
} from './utils/currentTimeEntry';
|
||||||
|
import { createTimeEntryViaApi, updateOrganizationSettingViaApi } from './utils/api';
|
||||||
|
|
||||||
|
async function goToDashboard(page: Page) {
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
function visibleBreakButton(page: Page) {
|
||||||
|
return page.getByRole('button', { name: 'Take a break' }).locator('visible=true').first();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Breaks are disabled by default for new organizations, so enable them for the break flows.
|
||||||
|
// The tests that assert the disabled behaviour turn them back off explicitly.
|
||||||
|
test.beforeEach(async ({ ctx }) => {
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that switching to a break stops the work timer and starts a break entry', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await goToDashboard(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
await page.getByTestId('time_entry_description').fill('Work before break');
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||||
|
page.getByTestId('time_entry_description').press('Enter'),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// Switch to break: stops the work entry and starts a break entry
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||||
|
visibleBreakButton(page).click(),
|
||||||
|
]);
|
||||||
|
await expect(page.getByText('On break')).toBeVisible();
|
||||||
|
|
||||||
|
// The break bar offers a one-click resume that stops the break and restores
|
||||||
|
// the interrupted work context
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
const resumeButton = page.getByRole('button', { name: 'Resume "Work before break"' });
|
||||||
|
await expect(resumeButton).toBeVisible();
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||||
|
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||||
|
resumeButton.click(),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toHaveValue('Work before break');
|
||||||
|
|
||||||
|
// Cleanup: stop the running entry
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that stopping a break returns to an idle tracker where a fresh entry starts normally', async ({
|
||||||
|
page,
|
||||||
|
}) => {
|
||||||
|
await goToDashboard(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
await page.getByTestId('time_entry_description').fill('Work before break');
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||||
|
page.getByTestId('time_entry_description').press('Enter'),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
|
||||||
|
// Switch to a break
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||||
|
visibleBreakButton(page).click(),
|
||||||
|
]);
|
||||||
|
await expect(page.getByText('On break')).toBeVisible();
|
||||||
|
|
||||||
|
// Stopping the break just ends it — no modal, the tracker returns to the
|
||||||
|
// empty idle input with focus so typing starts a fresh entry
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toHaveValue('');
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeFocused();
|
||||||
|
|
||||||
|
// A fresh entry is the normal start flow: type + Enter
|
||||||
|
await page.getByTestId('time_entry_description').fill('Fresh after break');
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: 'Fresh after break', type: 'work' }),
|
||||||
|
page.getByTestId('time_entry_description').press('Enter'),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
|
||||||
|
// Cleanup: stop the running entry
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { description: 'Fresh after break', type: 'work' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that the more options dropdown can start a break directly', async ({ page }) => {
|
||||||
|
await goToDashboard(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
|
||||||
|
// Start a break straight from the more options dropdown (no create modal)
|
||||||
|
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||||
|
page.getByRole('menuitem', { name: 'Start Break' }).click(),
|
||||||
|
]);
|
||||||
|
await expect(page.getByText('On break')).toBeVisible();
|
||||||
|
|
||||||
|
// Without interrupted work there is nothing to resume, so no resume button is offered
|
||||||
|
await expect(page.getByRole('button', { name: /^Resume/ })).toHaveCount(0);
|
||||||
|
|
||||||
|
// Cleanup: stop the break
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that disabling breaks hides every break-creation entry point', async ({ page, ctx }) => {
|
||||||
|
// Breaks disabled for the organization (delivered to the client via the organization endpoint)
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: false });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Regular work' });
|
||||||
|
|
||||||
|
// Calendar: the empty-slot context menu offers "Create Time Entry" but no "Add Break",
|
||||||
|
// and the edit modal drops the work-time/break type selector
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/calendar');
|
||||||
|
await expect(page.locator('.fc')).toBeVisible();
|
||||||
|
const event = page.locator('.fc-event').filter({ hasText: 'Regular work' }).first();
|
||||||
|
await event.scrollIntoViewIfNeeded();
|
||||||
|
await expect(event).toBeVisible();
|
||||||
|
|
||||||
|
const box = await event.boundingBox();
|
||||||
|
expect(box).not.toBeNull();
|
||||||
|
await page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height + 40, { button: 'right' });
|
||||||
|
await expect(page.getByRole('menu')).toBeVisible();
|
||||||
|
await expect(page.getByRole('menuitem', { name: 'Create Time Entry' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('menuitem', { name: 'Add Break' })).toHaveCount(0);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
|
||||||
|
await event.click({ button: 'right' });
|
||||||
|
await expect(page.getByRole('menu')).toBeVisible();
|
||||||
|
await page.getByRole('menuitem', { name: 'Edit' }).click();
|
||||||
|
await expect(page.getByRole('dialog')).toBeVisible();
|
||||||
|
await expect(
|
||||||
|
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Work time' })
|
||||||
|
).toHaveCount(0);
|
||||||
|
await page.keyboard.press('Escape');
|
||||||
|
|
||||||
|
// Timesheet: no break row is shown
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/timesheet');
|
||||||
|
await expect(page.getByRole('button', { name: 'Add row' }).first()).toBeVisible();
|
||||||
|
await expect(page.getByText('Break', { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
// Dashboard tracker: no "Start Break" in the more options dropdown
|
||||||
|
await goToDashboard(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await expect(page.getByRole('menuitem', { name: 'Switch to simple mode' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('menuitem', { name: 'Start Break' })).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The employee fixture registers a second user and accepts an invitation via Mailpit,
|
||||||
|
// which does not fit into the default per-test timeout.
|
||||||
|
test.describe('Org-level breaks setting', () => {
|
||||||
|
test.describe.configure({ timeout: 60000 });
|
||||||
|
|
||||||
|
test('test that the org-level breaks setting is respected for employees', async ({
|
||||||
|
ctx,
|
||||||
|
employee,
|
||||||
|
}) => {
|
||||||
|
const employeePage = employee.page;
|
||||||
|
|
||||||
|
// Breaks enabled (via beforeEach): the employee sees "Start Break" in the more options dropdown
|
||||||
|
await employeePage.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||||
|
await expect(employeePage.getByTestId('dashboard_view')).toBeVisible();
|
||||||
|
await employeePage.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await expect(
|
||||||
|
employeePage.getByRole('menuitem', { name: 'Switch to simple mode' })
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(employeePage.getByRole('menuitem', { name: 'Start Break' })).toBeVisible();
|
||||||
|
await employeePage.keyboard.press('Escape');
|
||||||
|
|
||||||
|
// The owner disables breaks for the whole organization
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: false });
|
||||||
|
|
||||||
|
// The employee reloads: "Start Break" is gone from the dropdown
|
||||||
|
await employeePage.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||||
|
await expect(employeePage.getByTestId('dashboard_view')).toBeVisible();
|
||||||
|
await employeePage.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await expect(
|
||||||
|
employeePage.getByRole('menuitem', { name: 'Switch to simple mode' })
|
||||||
|
).toBeVisible();
|
||||||
|
await expect(employeePage.getByRole('menuitem', { name: 'Start Break' })).toHaveCount(0);
|
||||||
|
await employeePage.keyboard.press('Escape');
|
||||||
|
|
||||||
|
// With an active timer the break (coffee) button is not shown either
|
||||||
|
await employeePage.getByTestId('time_entry_description').fill('Employee work');
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(employeePage, { description: 'Employee work', type: 'work' }),
|
||||||
|
employeePage.getByTestId('time_entry_description').press('Enter'),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(employeePage);
|
||||||
|
await expect(employeePage.getByRole('button', { name: 'Take a break' })).toHaveCount(0);
|
||||||
|
|
||||||
|
// Cleanup: stop the running entry
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(employeePage, { description: 'Employee work', type: 'work' }),
|
||||||
|
startOrStopTimerWithButton(employeePage),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(employeePage);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that mass update warns about selected breaks and reports skipped entries instead of success', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// One work entry and one break: a billable mass update applies to the work
|
||||||
|
// entry but the server skips the break entirely — the UI must say so.
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Mass update work entry' });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '30min', type: 'break' });
|
||||||
|
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||||
|
await expect(page.locator('[data-testid="time_entry_row"]')).toHaveCount(2);
|
||||||
|
await page.getByLabel('Select All').click();
|
||||||
|
await expect(page.getByText('2 selected')).toBeVisible();
|
||||||
|
await page.getByRole('button', { name: 'Edit' }).click();
|
||||||
|
await expect(page.getByRole('dialog')).toBeVisible();
|
||||||
|
|
||||||
|
// No warning while the changeset is compatible with breaks
|
||||||
|
await expect(page.getByTestId('mass_update_break_warning')).not.toBeVisible();
|
||||||
|
|
||||||
|
// Making the entries billable is break-incompatible → warning appears
|
||||||
|
await page
|
||||||
|
.getByRole('dialog')
|
||||||
|
.getByRole('combobox')
|
||||||
|
.filter({ hasText: 'Set billable status' })
|
||||||
|
.click();
|
||||||
|
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||||
|
await expect(page.getByTestId('mass_update_break_warning')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('mass_update_break_warning')).toContainText('skipped entirely');
|
||||||
|
|
||||||
|
// Submit: the work entry updates, the break is skipped, and the toast
|
||||||
|
// reports the skip instead of claiming success for all entries
|
||||||
|
const [massUpdateResponse] = await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/time-entries') &&
|
||||||
|
response.request().method() === 'PATCH' &&
|
||||||
|
response.status() === 200
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Update Time Entries' }).click(),
|
||||||
|
]);
|
||||||
|
const massUpdateBody = await massUpdateResponse.json();
|
||||||
|
expect(massUpdateBody.success.length).toBe(1);
|
||||||
|
expect(massUpdateBody.error.length).toBe(1);
|
||||||
|
await expect(page.getByText('1 of 2 time entries was skipped')).toBeVisible();
|
||||||
|
});
|
||||||
@@ -2874,3 +2874,54 @@ test.describe('Daily Total After Create', () => {
|
|||||||
}).toPass({ timeout: 5000 });
|
}).toPass({ timeout: 5000 });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that calendar context menu can add a break that fills the gap between two entries', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
// Two work entries today (09:00-10:00 and 11:00-12:00 UTC) with a one hour gap
|
||||||
|
const today = new Date().toISOString().slice(0, 10);
|
||||||
|
const gapStart = `${today}T10:00:00Z`;
|
||||||
|
const gapEnd = `${today}T11:00:00Z`;
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${today}T09:00:00Z`,
|
||||||
|
end: gapStart,
|
||||||
|
description: 'Gap work A',
|
||||||
|
});
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: gapEnd,
|
||||||
|
end: `${today}T12:00:00Z`,
|
||||||
|
description: 'Gap work B',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToCalendar(page);
|
||||||
|
const eventA = page.locator('.fc-event').filter({ hasText: 'Gap work A' }).first();
|
||||||
|
await eventA.scrollIntoViewIfNeeded();
|
||||||
|
await expect(eventA).toBeVisible();
|
||||||
|
|
||||||
|
// Right-click just below entry A (inside the gap, in the same day column)
|
||||||
|
const box = await eventA.boundingBox();
|
||||||
|
expect(box).not.toBeNull();
|
||||||
|
await page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height + 15, {
|
||||||
|
button: 'right',
|
||||||
|
});
|
||||||
|
await expect(page.getByRole('menu')).toBeVisible();
|
||||||
|
await page.getByRole('menuitem', { name: 'Add Break' }).click();
|
||||||
|
await expect(page.getByRole('dialog')).toBeVisible();
|
||||||
|
|
||||||
|
// The break is prefilled to fill the gap exactly
|
||||||
|
const [createResponse] = await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
async (response) =>
|
||||||
|
response.url().includes('/time-entries') &&
|
||||||
|
response.request().method() === 'POST' &&
|
||||||
|
response.status() === 201 &&
|
||||||
|
(await response.json()).data.type === 'break'
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Add Break' }).click(),
|
||||||
|
]);
|
||||||
|
const body = await createResponse.json();
|
||||||
|
expect(body.data.start).toBe(gapStart);
|
||||||
|
expect(body.data.end).toBe(gapEnd);
|
||||||
|
});
|
||||||
|
|||||||
@@ -1019,3 +1019,24 @@ test.describe('Employee Reporting Restrictions', () => {
|
|||||||
await expect(employee.page.getByText('100,00 EUR').first()).toBeVisible();
|
await expect(employee.page.getByText('100,00 EUR').first()).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that reporting has a type filter that can show only breaks', async ({ page, ctx }) => {
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Regular work entry' });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '20min', type: 'break' });
|
||||||
|
|
||||||
|
await goToReporting(page);
|
||||||
|
// The type filter defaults to "Work time"; switching it to "Breaks" re-aggregates.
|
||||||
|
const typeFilter = page.getByRole('combobox').filter({ hasText: 'Work time' });
|
||||||
|
await expect(typeFilter).toBeVisible();
|
||||||
|
await typeFilter.click();
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
(response) =>
|
||||||
|
response.url().includes('/time-entries/aggregate') &&
|
||||||
|
response.url().includes('type=break') &&
|
||||||
|
response.status() === 200
|
||||||
|
),
|
||||||
|
page.getByRole('option', { name: 'Breaks' }).click(),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|||||||
@@ -2303,3 +2303,19 @@ test('test that aggregate row context menu delete removes all grouped entries',
|
|||||||
page.locator('[data-testid="time_entry_row"]').filter({ hasText: description })
|
page.locator('[data-testid="time_entry_row"]').filter({ hasText: description })
|
||||||
).not.toBeVisible();
|
).not.toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that break entries show a break badge and split day total on the time page', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '2h', description: 'Some work' });
|
||||||
|
await createTimeEntryViaApi(ctx, { duration: '30min', type: 'break', description: '' });
|
||||||
|
|
||||||
|
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||||
|
await expect(page.getByTestId('break_badge').first()).toBeVisible();
|
||||||
|
await expect(page.getByTestId('break_badge').first()).toContainText('Break');
|
||||||
|
// Day heading shows the break portion separately from worked time
|
||||||
|
await expect(page.getByTestId('day_break_duration').first()).toBeVisible();
|
||||||
|
await expect(page.getByTestId('day_break_duration').first()).toContainText('break');
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,7 +2,14 @@ import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
|||||||
import { test } from '../playwright/fixtures';
|
import { test } from '../playwright/fixtures';
|
||||||
import { expect } from '@playwright/test';
|
import { expect } from '@playwright/test';
|
||||||
import type { Page } from '@playwright/test';
|
import type { Page } from '@playwright/test';
|
||||||
import { createProjectViaApi, createTaskViaApi, createTimeEntryOnDateViaApi } from './utils/api';
|
import {
|
||||||
|
createProjectViaApi,
|
||||||
|
createTaskViaApi,
|
||||||
|
createTimeEntryOnDateViaApi,
|
||||||
|
createTimeEntryWithTimestampsViaApi,
|
||||||
|
getTimeEntriesViaApi,
|
||||||
|
updateOrganizationSettingViaApi,
|
||||||
|
} from './utils/api';
|
||||||
|
|
||||||
// ──────────────────────────────────────────────────
|
// ──────────────────────────────────────────────────
|
||||||
// Helpers
|
// Helpers
|
||||||
@@ -639,3 +646,279 @@ test('cell accepts various duration input formats', async ({ page, ctx }) => {
|
|||||||
// 1.5 hours = 1h 30min
|
// 1.5 hours = 1h 30min
|
||||||
await expect(mondayInput).toHaveValue('1h 30min');
|
await expect(mondayInput).toHaveValue('1h 30min');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that adding a timesheet break to a full day splits the work entry via the placement modal', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// A single work entry filling the day leaves no gap for a break, so the placement
|
||||||
|
// modal must offer to split it (the only entry) and drop the break in the middle.
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T09:00:00Z`,
|
||||||
|
end: `${day}T17:00:00Z`,
|
||||||
|
description: 'Split me',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToTimesheet(page);
|
||||||
|
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||||
|
|
||||||
|
// The break row is always present — enter a 30m break on Monday
|
||||||
|
const breakRow = page
|
||||||
|
.locator('[data-testid="timesheet_row"]')
|
||||||
|
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||||
|
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||||
|
await breakCell.click();
|
||||||
|
await breakCell.fill('0.5');
|
||||||
|
await breakCell.press('Enter');
|
||||||
|
|
||||||
|
// The placement modal opens with the split preview
|
||||||
|
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
async (resp) =>
|
||||||
|
resp.url().includes('/time-entries') &&
|
||||||
|
resp.request().method() === 'POST' &&
|
||||||
|
resp.status() === 201 &&
|
||||||
|
(await resp.json()).data.type === 'break'
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Add break' }).click(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// The day now has two work halves and one break, none overlapping
|
||||||
|
const entries = await getTimeEntriesViaApi(ctx);
|
||||||
|
const dayEntries = entries
|
||||||
|
.filter((e) => e.start.startsWith(day))
|
||||||
|
.sort((a, b) => a.start.localeCompare(b.start));
|
||||||
|
expect(dayEntries).toHaveLength(3);
|
||||||
|
expect(dayEntries.map((e) => e.type)).toEqual(['work', 'break', 'work']);
|
||||||
|
// The break sits flush between the two halves
|
||||||
|
expect(dayEntries[0].end).toBe(dayEntries[1].start);
|
||||||
|
expect(dayEntries[1].end).toBe(dayEntries[2].start);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that adding a break into an oversized gap places it without moving other entries', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// 09-12 and 15-17 leave a 3h gap — wider than the placement tolerance allows,
|
||||||
|
// but easily big enough to hold the break. Such a gap is deliberate (the app
|
||||||
|
// itself never creates one), so the break goes flush after the morning entry
|
||||||
|
// and nothing else moves — no placement modal.
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T09:00:00Z`,
|
||||||
|
end: `${day}T12:00:00Z`,
|
||||||
|
description: 'Morning',
|
||||||
|
});
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T15:00:00Z`,
|
||||||
|
end: `${day}T17:00:00Z`,
|
||||||
|
description: 'Afternoon',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToTimesheet(page);
|
||||||
|
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||||
|
|
||||||
|
const breakRow = page
|
||||||
|
.locator('[data-testid="timesheet_row"]')
|
||||||
|
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||||
|
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||||
|
await breakCell.click();
|
||||||
|
await breakCell.fill('0.5');
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
async (resp) =>
|
||||||
|
resp.url().includes('/time-entries') &&
|
||||||
|
resp.request().method() === 'POST' &&
|
||||||
|
resp.status() === 201 &&
|
||||||
|
(await resp.json()).data.type === 'break'
|
||||||
|
),
|
||||||
|
breakCell.press('Enter'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await expect(page.getByTestId('break_placement_summary')).not.toBeVisible();
|
||||||
|
const entries = await getTimeEntriesViaApi(ctx);
|
||||||
|
const dayEntries = entries
|
||||||
|
.filter((e) => e.start.startsWith(day))
|
||||||
|
.sort((a, b) => a.start.localeCompare(b.start));
|
||||||
|
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
|
||||||
|
['work', `${day}T09:00:00Z`, `${day}T12:00:00Z`],
|
||||||
|
['break', `${day}T12:00:00Z`, `${day}T12:30:00Z`],
|
||||||
|
['work', `${day}T15:00:00Z`, `${day}T17:00:00Z`],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that the placement modal warns when the chosen time would leave the break misaligned', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// Back-to-back 09-12 and 12-17 leave no gap, so the placement modal opens.
|
||||||
|
// The suggested slot (flush at 12:00) is aligned — no warning. Moving the
|
||||||
|
// break to 07:00, before any work, keeps the plan feasible but the result
|
||||||
|
// would immediately carry the misaligned hint, so the modal warns upfront.
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T09:00:00Z`,
|
||||||
|
end: `${day}T12:00:00Z`,
|
||||||
|
description: 'Morning',
|
||||||
|
});
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T12:00:00Z`,
|
||||||
|
end: `${day}T17:00:00Z`,
|
||||||
|
description: 'Afternoon',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToTimesheet(page);
|
||||||
|
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||||
|
|
||||||
|
const breakRow = page
|
||||||
|
.locator('[data-testid="timesheet_row"]')
|
||||||
|
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||||
|
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||||
|
await breakCell.click();
|
||||||
|
await breakCell.fill('0.5');
|
||||||
|
await breakCell.press('Enter');
|
||||||
|
|
||||||
|
// Default suggestion sits flush between work → no warning
|
||||||
|
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('break_placement_misaligned_warning')).not.toBeVisible();
|
||||||
|
|
||||||
|
// Move the break to 07:00-07:30, before all work
|
||||||
|
const modal = page.getByRole('dialog');
|
||||||
|
const startTimeInput = modal.getByTestId('time_picker_input').first();
|
||||||
|
await startTimeInput.fill('07:00');
|
||||||
|
await startTimeInput.press('Tab');
|
||||||
|
const endTimeInput = modal.getByTestId('time_picker_input').nth(1);
|
||||||
|
await endTimeInput.fill('07:30');
|
||||||
|
await endTimeInput.press('Tab');
|
||||||
|
|
||||||
|
// Feasible (nothing has to move), but flagged as misaligned beforehand
|
||||||
|
await expect(page.getByTestId('break_placement_misaligned_warning')).toBeVisible();
|
||||||
|
await expect(page.getByTestId('break_placement_summary')).toContainText(
|
||||||
|
'No entries need to move.'
|
||||||
|
);
|
||||||
|
|
||||||
|
// The warning is non-blocking: the break can still be added as chosen
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(
|
||||||
|
async (resp) =>
|
||||||
|
resp.url().includes('/time-entries') &&
|
||||||
|
resp.request().method() === 'POST' &&
|
||||||
|
resp.status() === 201 &&
|
||||||
|
(await resp.json()).data.type === 'break'
|
||||||
|
),
|
||||||
|
page.getByRole('button', { name: 'Add break' }).click(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const entries = await getTimeEntriesViaApi(ctx);
|
||||||
|
const dayEntries = entries
|
||||||
|
.filter((e) => e.start.startsWith(day))
|
||||||
|
.sort((a, b) => a.start.localeCompare(b.start));
|
||||||
|
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
|
||||||
|
['break', `${day}T07:00:00Z`, `${day}T07:30:00Z`],
|
||||||
|
['work', `${day}T09:00:00Z`, `${day}T12:00:00Z`],
|
||||||
|
['work', `${day}T12:00:00Z`, `${day}T17:00:00Z`],
|
||||||
|
]);
|
||||||
|
// ...and the timesheet now shows the misaligned-break hint for that day
|
||||||
|
await expect(
|
||||||
|
page.getByRole('button', { name: 'does not align with your work entries' })
|
||||||
|
).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that a misplaced break shows a warning on its timesheet day cell', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// Work ends at 10:00 and the break starts hours later with no work after it,
|
||||||
|
// so it is misplaced and its day header should carry the warning hint.
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T09:00:00Z`,
|
||||||
|
end: `${day}T10:00:00Z`,
|
||||||
|
});
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T14:00:00Z`,
|
||||||
|
end: `${day}T14:30:00Z`,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToTimesheet(page);
|
||||||
|
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||||
|
|
||||||
|
// Exactly one warning, sitting in Monday's day header
|
||||||
|
const hint = page.getByRole('button', {
|
||||||
|
name: 'does not align with your work entries',
|
||||||
|
});
|
||||||
|
await expect(hint).toHaveCount(1);
|
||||||
|
await expect(
|
||||||
|
page.getByTestId('timesheet_day_header').first().getByRole('button', {
|
||||||
|
name: 'does not align with your work entries',
|
||||||
|
})
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
|
// The hint links to the calendar on the affected date
|
||||||
|
await hint.click();
|
||||||
|
await expect(page.getByRole('link', { name: 'Fix in calendar' })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
`/calendar?date=${day}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('test that editing a timesheet break re-places it as one entry instead of fragmenting it', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
// Two work entries with a 1h gap, and a 30m break created directly inside it (12:15–12:45).
|
||||||
|
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||||
|
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T09:00:00Z`,
|
||||||
|
end: `${day}T12:00:00Z`,
|
||||||
|
description: 'Work',
|
||||||
|
});
|
||||||
|
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T13:00:00Z`,
|
||||||
|
end: `${day}T17:00:00Z`,
|
||||||
|
description: 'Work',
|
||||||
|
});
|
||||||
|
const breakEntry = await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||||
|
start: `${day}T12:15:00Z`,
|
||||||
|
end: `${day}T12:45:00Z`,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToTimesheet(page);
|
||||||
|
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||||
|
const breakRow = page
|
||||||
|
.locator('[data-testid="timesheet_row"]')
|
||||||
|
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||||
|
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||||
|
await breakCell.click();
|
||||||
|
await breakCell.fill('0.75'); // 45 minutes — still fits the 1h gap, so it stays anchored
|
||||||
|
await Promise.all([
|
||||||
|
// A break that still fits its gap is re-placed in place (PUT on the same entry),
|
||||||
|
// not deleted and recreated — that's what keeps it a single entry.
|
||||||
|
page.waitForResponse(
|
||||||
|
async (resp) =>
|
||||||
|
resp.url().includes(`/time-entries/${breakEntry.id}`) &&
|
||||||
|
resp.request().method() === 'PUT' &&
|
||||||
|
resp.status() === 200 &&
|
||||||
|
(await resp.json()).data.type === 'break'
|
||||||
|
),
|
||||||
|
breakCell.press('Enter'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Still exactly one break on the day (not fragmented). It stays anchored at its current
|
||||||
|
// start (12:15) rather than re-centering, growing its end to 13:00 to reach 45 minutes.
|
||||||
|
const after = await getTimeEntriesViaApi(ctx);
|
||||||
|
const breaks = after.filter((e) => e.start.startsWith(day) && e.type === 'break');
|
||||||
|
expect(breaks).toHaveLength(1);
|
||||||
|
expect(breaks[0].duration).toBe(2700);
|
||||||
|
expect(breaks[0].start).toBe(`${day}T12:15:00Z`);
|
||||||
|
expect(breaks[0].end).toBe(`${day}T13:00:00Z`);
|
||||||
|
});
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
createProjectViaApi,
|
createProjectViaApi,
|
||||||
createTaskViaApi,
|
createTaskViaApi,
|
||||||
createClientViaApi,
|
createClientViaApi,
|
||||||
|
createTimeEntryViaApi,
|
||||||
archiveProjectViaApi,
|
archiveProjectViaApi,
|
||||||
markTaskDoneViaApi,
|
markTaskDoneViaApi,
|
||||||
updateOrganizationCurrencyViaWeb,
|
updateOrganizationCurrencyViaWeb,
|
||||||
@@ -375,6 +376,66 @@ test('test that timer started on dashboard is visible on time page', async ({ pa
|
|||||||
await assertThatTimerIsStopped(page);
|
await assertThatTimerIsStopped(page);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that picking a recently tracked entry starts a timer with its fields', async ({
|
||||||
|
page,
|
||||||
|
ctx,
|
||||||
|
}) => {
|
||||||
|
const project = await createProjectViaApi(ctx, {
|
||||||
|
name: `RecentProj ${Math.floor(Math.random() * 100000)}`,
|
||||||
|
is_billable: false,
|
||||||
|
});
|
||||||
|
await createTimeEntryViaApi(ctx, {
|
||||||
|
description: 'Recent work item',
|
||||||
|
duration: '1h',
|
||||||
|
projectId: project.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
await goToDashboard(page);
|
||||||
|
const description = page.getByTestId('time_entry_description');
|
||||||
|
await expect(description).toBeEditable();
|
||||||
|
|
||||||
|
// Focusing the description opens the "Recently Tracked" dropdown listing the finished entry.
|
||||||
|
await description.click();
|
||||||
|
const recentEntry = page.getByText('Recent work item').first();
|
||||||
|
await expect(recentEntry).toBeVisible();
|
||||||
|
|
||||||
|
// Clicking it (mousedown) copies its fields — including the project — into a new running entry.
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(async (response) => {
|
||||||
|
if (
|
||||||
|
!response.url().includes('/time-entries') ||
|
||||||
|
response.request().method() !== 'POST' ||
|
||||||
|
response.status() !== 201
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const body = await response.json();
|
||||||
|
return (
|
||||||
|
body.data.description === 'Recent work item' &&
|
||||||
|
body.data.project_id === project.id &&
|
||||||
|
body.data.end === null
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
recentEntry.click(),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
await expect(description).toHaveValue('Recent work item');
|
||||||
|
await expect(page.getByRole('button', { name: project.name })).toBeVisible();
|
||||||
|
|
||||||
|
// Cleanup: stop the running (project-bearing) entry
|
||||||
|
await Promise.all([
|
||||||
|
page.waitForResponse(async (response) => {
|
||||||
|
if (response.status() !== 200 || !response.url().includes('/time-entries/')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const body = await response.json();
|
||||||
|
return body.data.description === 'Recent work item' && body.data.end !== null;
|
||||||
|
}),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
});
|
||||||
|
|
||||||
test('test that creating a new project from the time tracker dropdown prefills the search text', async ({
|
test('test that creating a new project from the time tracker dropdown prefills the search text', async ({
|
||||||
page,
|
page,
|
||||||
ctx,
|
ctx,
|
||||||
@@ -681,3 +742,39 @@ test.describe('Project Task Dropdown', () => {
|
|||||||
await expect(page.getByRole('button', { name: projectName })).toBeVisible();
|
await expect(page.getByRole('button', { name: projectName })).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('test that simple mode hides the project, tag and billable controls', async ({ page }) => {
|
||||||
|
await goToDashboard(page);
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
// Project mode shows the project and billable controls
|
||||||
|
await expect(page.getByRole('button', { name: 'No Project' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('button', { name: 'Non Billable' }).first()).toBeVisible();
|
||||||
|
|
||||||
|
// Switch to simple mode via the more options dropdown (client-side preference, no request)
|
||||||
|
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await page.getByRole('menuitem', { name: 'Switch to simple mode' }).click();
|
||||||
|
|
||||||
|
// Simple mode is the project tracker without the project/tag/billable selectors; the
|
||||||
|
// description input and clock-in/out stay.
|
||||||
|
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||||
|
await expect(page.getByRole('button', { name: 'No Project' })).toHaveCount(0);
|
||||||
|
await expect(page.getByRole('button', { name: 'Non Billable' })).toHaveCount(0);
|
||||||
|
|
||||||
|
// Clock in and out
|
||||||
|
await Promise.all([
|
||||||
|
newTimeEntryResponse(page, { type: 'work' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerHasStarted(page);
|
||||||
|
await page.waitForTimeout(1500);
|
||||||
|
await Promise.all([
|
||||||
|
stoppedTimeEntryResponse(page, { type: 'work' }),
|
||||||
|
startOrStopTimerWithButton(page),
|
||||||
|
]);
|
||||||
|
await assertThatTimerIsStopped(page);
|
||||||
|
|
||||||
|
// Switch back to project mode: the controls return
|
||||||
|
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||||
|
await page.getByRole('menuitem', { name: 'Switch to project mode' }).click();
|
||||||
|
await expect(page.getByRole('button', { name: 'No Project' })).toBeVisible();
|
||||||
|
});
|
||||||
|
|||||||
@@ -406,6 +406,7 @@ export async function createTimeEntryViaApi(
|
|||||||
taskId?: string | null;
|
taskId?: string | null;
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
billable?: boolean;
|
billable?: boolean;
|
||||||
|
type?: 'work' | 'break';
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const { start, end } = createTimestamps(data.duration);
|
const { start, end } = createTimestamps(data.duration);
|
||||||
@@ -421,6 +422,7 @@ export async function createTimeEntryViaApi(
|
|||||||
task_id: data.taskId ?? null,
|
task_id: data.taskId ?? null,
|
||||||
tags: data.tags ?? [],
|
tags: data.tags ?? [],
|
||||||
billable: data.billable ?? false,
|
billable: data.billable ?? false,
|
||||||
|
type: data.type ?? 'work',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -754,6 +756,7 @@ export async function getTimeEntriesViaApi(
|
|||||||
project_id: string | null;
|
project_id: string | null;
|
||||||
task_id: string | null;
|
task_id: string | null;
|
||||||
description: string;
|
description: string;
|
||||||
|
type: 'work' | 'break';
|
||||||
}>
|
}>
|
||||||
> {
|
> {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -779,6 +782,7 @@ export async function createTimeEntryWithTimestampsViaApi(
|
|||||||
taskId?: string | null;
|
taskId?: string | null;
|
||||||
tags?: string[];
|
tags?: string[];
|
||||||
billable?: boolean;
|
billable?: boolean;
|
||||||
|
type?: 'work' | 'break';
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const response = await ctx.request.post(
|
const response = await ctx.request.post(
|
||||||
@@ -793,12 +797,19 @@ export async function createTimeEntryWithTimestampsViaApi(
|
|||||||
task_id: data.taskId ?? null,
|
task_id: data.taskId ?? null,
|
||||||
tags: data.tags ?? [],
|
tags: data.tags ?? [],
|
||||||
billable: data.billable ?? false,
|
billable: data.billable ?? false,
|
||||||
|
type: data.type ?? 'work',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
expect(response.status()).toBe(201);
|
expect(response.status()).toBe(201);
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
return body.data as { id: string; start: string; end: string; description: string };
|
return body.data as {
|
||||||
|
id: string;
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
description: string;
|
||||||
|
type: 'work' | 'break';
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ──────────────────────────────────────────────────
|
// ──────────────────────────────────────────────────
|
||||||
@@ -903,3 +914,71 @@ export async function createReportViaApi(
|
|||||||
public_until: string | null;
|
public_until: string | null;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ──────────────────────────────────────────────────
|
||||||
|
// Invoices
|
||||||
|
// ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function createInvoiceViaApi(
|
||||||
|
ctx: TestContext,
|
||||||
|
data: {
|
||||||
|
reference: string;
|
||||||
|
buyer_name?: string;
|
||||||
|
seller_name?: string;
|
||||||
|
currency?: string;
|
||||||
|
date?: string;
|
||||||
|
tax_rate?: number;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
const response = await ctx.request.post(
|
||||||
|
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/invoices`,
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
seller_name: data.seller_name ?? 'Test Seller',
|
||||||
|
buyer_name: data.buyer_name ?? 'Test Buyer',
|
||||||
|
reference: data.reference,
|
||||||
|
currency: data.currency ?? 'EUR',
|
||||||
|
date: data.date ?? new Date().toISOString().split('T')[0],
|
||||||
|
// Mirror the UI create form, which always sends a tax rate (default 0).
|
||||||
|
// Invoices with a null tax_rate currently crash PDF rendering.
|
||||||
|
tax_rate: data.tax_rate ?? 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
expect(response.status()).toBe(201);
|
||||||
|
const body = await response.json();
|
||||||
|
return body.data as { id: string; reference: string; buyer_name: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateInvoiceSettingsViaApi(ctx: TestContext, data: Record<string, unknown>) {
|
||||||
|
const response = await ctx.request.put(
|
||||||
|
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/invoice-settings`,
|
||||||
|
{ data }
|
||||||
|
);
|
||||||
|
expect(response.status()).toBe(200);
|
||||||
|
const body = await response.json();
|
||||||
|
return body.data as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getInvoiceSettingsViaApi(ctx: TestContext) {
|
||||||
|
const response = await ctx.request.get(
|
||||||
|
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/invoice-settings`
|
||||||
|
);
|
||||||
|
expect(response.status()).toBe(200);
|
||||||
|
const body = await response.json();
|
||||||
|
return body.data as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getInvoicesViaApi(ctx: TestContext) {
|
||||||
|
const response = await ctx.request.get(
|
||||||
|
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/invoices`
|
||||||
|
);
|
||||||
|
expect(response.status()).toBe(200);
|
||||||
|
const body = await response.json();
|
||||||
|
return body.data as Array<{
|
||||||
|
id: string;
|
||||||
|
reference: string;
|
||||||
|
buyer_name: string;
|
||||||
|
paid_date: string | null;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,7 +20,17 @@ export async function assertThatTimerHasStarted(page: Page) {
|
|||||||
|
|
||||||
export function newTimeEntryResponse(
|
export function newTimeEntryResponse(
|
||||||
page: Page,
|
page: Page,
|
||||||
{ description = '', status = 201, tags = [] } = {}
|
{
|
||||||
|
description = '',
|
||||||
|
status = 201,
|
||||||
|
tags = [],
|
||||||
|
type,
|
||||||
|
}: {
|
||||||
|
description?: string;
|
||||||
|
status?: number;
|
||||||
|
tags?: string[];
|
||||||
|
type?: 'work' | 'break';
|
||||||
|
} = {}
|
||||||
) {
|
) {
|
||||||
return page.waitForResponse(async (response) => {
|
return page.waitForResponse(async (response) => {
|
||||||
return (
|
return (
|
||||||
@@ -34,6 +44,7 @@ export function newTimeEntryResponse(
|
|||||||
(await response.json()).data.description === description &&
|
(await response.json()).data.description === description &&
|
||||||
(await response.json()).data.task_id === null &&
|
(await response.json()).data.task_id === null &&
|
||||||
(await response.json()).data.user_id !== null &&
|
(await response.json()).data.user_id !== null &&
|
||||||
|
(type === undefined || (await response.json()).data.type === type) &&
|
||||||
JSON.stringify((await response.json()).data.tags) === JSON.stringify(tags)
|
JSON.stringify((await response.json()).data.tags) === JSON.stringify(tags)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -48,7 +59,18 @@ export async function assertThatTimerIsStopped(page: Page) {
|
|||||||
).toHaveClass(/bg-accent-300\/70/);
|
).toHaveClass(/bg-accent-300\/70/);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function stoppedTimeEntryResponse(page: Page, { description = '', tags = [] } = {}) {
|
export async function stoppedTimeEntryResponse(
|
||||||
|
page: Page,
|
||||||
|
{
|
||||||
|
description = '',
|
||||||
|
tags = [],
|
||||||
|
type,
|
||||||
|
}: {
|
||||||
|
description?: string;
|
||||||
|
tags?: string[];
|
||||||
|
type?: 'work' | 'break';
|
||||||
|
} = {}
|
||||||
|
) {
|
||||||
return page.waitForResponse(async (response) => {
|
return page.waitForResponse(async (response) => {
|
||||||
return (
|
return (
|
||||||
response.status() === 200 &&
|
response.status() === 200 &&
|
||||||
@@ -62,6 +84,7 @@ export async function stoppedTimeEntryResponse(page: Page, { description = '', t
|
|||||||
(await response.json()).data.task_id === null &&
|
(await response.json()).data.task_id === null &&
|
||||||
(await response.json()).data.duration !== null &&
|
(await response.json()).data.duration !== null &&
|
||||||
(await response.json()).data.user_id !== null &&
|
(await response.json()).data.user_id !== null &&
|
||||||
|
(type === undefined || (await response.json()).data.type === type) &&
|
||||||
JSON.stringify((await response.json()).data.tags) === JSON.stringify(tags)
|
JSON.stringify((await response.json()).data.tags) === JSON.stringify(tags)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import { CheckCircleIcon, TagIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
|
import { CheckCircleIcon, TagIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
|
||||||
import { FolderIcon } from '@heroicons/vue/16/solid';
|
import { FolderIcon } from '@heroicons/vue/16/solid';
|
||||||
import { Check } from '@lucide/vue';
|
import { Check, Coffee } from '@lucide/vue';
|
||||||
import { RadioGroupIndicator, RadioGroupItem, RadioGroupRoot, type AcceptableValue } from 'reka-ui';
|
import { RadioGroupIndicator, RadioGroupItem, RadioGroupRoot, type AcceptableValue } from 'reka-ui';
|
||||||
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
||||||
import ReportingRoundingControls from '@/Components/Common/Reporting/ReportingRoundingControls.vue';
|
import ReportingRoundingControls from '@/Components/Common/Reporting/ReportingRoundingControls.vue';
|
||||||
@@ -27,6 +28,7 @@ const selectedClients = defineModel<string[]>('selectedClients', { required: tru
|
|||||||
const selectedTags = defineModel<string[]>('selectedTags', { required: true });
|
const selectedTags = defineModel<string[]>('selectedTags', { required: true });
|
||||||
const tagMatchType = defineModel<TagMatchType>('tagMatchType', { required: true });
|
const tagMatchType = defineModel<TagMatchType>('tagMatchType', { required: true });
|
||||||
const billable = defineModel<'true' | 'false' | null>('billable', { required: true });
|
const billable = defineModel<'true' | 'false' | null>('billable', { required: true });
|
||||||
|
const entryType = defineModel<'work' | 'break' | null>('entryType', { required: true });
|
||||||
const roundingEnabled = defineModel<boolean>('roundingEnabled', { required: true });
|
const roundingEnabled = defineModel<boolean>('roundingEnabled', { required: true });
|
||||||
const roundingType = defineModel<TimeEntryRoundingType>('roundingType', { required: true });
|
const roundingType = defineModel<TimeEntryRoundingType>('roundingType', { required: true });
|
||||||
const roundingMinutes = defineModel<number>('roundingMinutes', { required: true });
|
const roundingMinutes = defineModel<number>('roundingMinutes', { required: true });
|
||||||
@@ -37,6 +39,8 @@ const emit = defineEmits<{
|
|||||||
submit: [];
|
submit: [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
const { tags } = useTagsQuery();
|
const { tags } = useTagsQuery();
|
||||||
|
|
||||||
const tagMatchOptions: { value: TagMatchType; label: string }[] = [
|
const tagMatchOptions: { value: TagMatchType; label: string }[] = [
|
||||||
@@ -162,6 +166,38 @@ async function createTag(name: string) {
|
|||||||
<SelectItem value="false">Non Billable</SelectItem>
|
<SelectItem value="false">Non Billable</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
<Select
|
||||||
|
v-if="breaksEnabled"
|
||||||
|
v-model="entryType"
|
||||||
|
@update:model-value="emit('submit')">
|
||||||
|
<SelectTrigger
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
:active="entryType !== null"
|
||||||
|
:show-chevron="false">
|
||||||
|
<SelectValue class="flex items-center gap-2">
|
||||||
|
<Coffee
|
||||||
|
class="h-4 w-4"
|
||||||
|
:class="
|
||||||
|
entryType !== null
|
||||||
|
? 'dark:text-accent-300/80 text-accent-400/80'
|
||||||
|
: 'text-text-quaternary'
|
||||||
|
" />
|
||||||
|
<span class="text-text-secondary">{{
|
||||||
|
entryType === null
|
||||||
|
? 'Type'
|
||||||
|
: entryType === 'break'
|
||||||
|
? 'Breaks'
|
||||||
|
: 'Work time'
|
||||||
|
}}</span>
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem :value="null">Both</SelectItem>
|
||||||
|
<SelectItem value="work">Work time</SelectItem>
|
||||||
|
<SelectItem value="break">Breaks</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
<ReportingRoundingControls
|
<ReportingRoundingControls
|
||||||
v-model:enabled="roundingEnabled"
|
v-model:enabled="roundingEnabled"
|
||||||
v-model:type="roundingType"
|
v-model:type="roundingType"
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ const selectedClients = ref<string[]>([]);
|
|||||||
const tagMatchType = ref<TagMatchType>('contains');
|
const tagMatchType = ref<TagMatchType>('contains');
|
||||||
|
|
||||||
const billable = ref<'true' | 'false' | null>(null);
|
const billable = ref<'true' | 'false' | null>(null);
|
||||||
|
const entryType = ref<'work' | 'break' | null>('work');
|
||||||
const roundingEnabled = ref<boolean>(false);
|
const roundingEnabled = ref<boolean>(false);
|
||||||
const roundingType = ref<TimeEntryRoundingType>('nearest');
|
const roundingType = ref<TimeEntryRoundingType>('nearest');
|
||||||
const roundingMinutes = ref<number>(15);
|
const roundingMinutes = ref<number>(15);
|
||||||
@@ -126,6 +127,7 @@ const filterParams = computed<AggregatedTimeEntriesQueryParams>(() => {
|
|||||||
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
|
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
|
||||||
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
|
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
|
||||||
billable: billable.value !== null ? billable.value : undefined,
|
billable: billable.value !== null ? billable.value : undefined,
|
||||||
|
type: entryType.value !== null ? entryType.value : undefined,
|
||||||
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
|
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
|
||||||
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
|
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
|
||||||
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
|
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
|
||||||
@@ -160,7 +162,7 @@ const aggregatedTableTimeEntries = computed<AggregatedTimeEntries | undefined>((
|
|||||||
});
|
});
|
||||||
|
|
||||||
const reportProperties = computed(() => {
|
const reportProperties = computed(() => {
|
||||||
const { billable: billableFilter, ...rest } = filterParams.value;
|
const { billable: billableFilter, type: typeFilter, ...rest } = filterParams.value;
|
||||||
|
|
||||||
let billableValue: boolean | null = null;
|
let billableValue: boolean | null = null;
|
||||||
if (billableFilter === 'true') {
|
if (billableFilter === 'true') {
|
||||||
@@ -172,6 +174,7 @@ const reportProperties = computed(() => {
|
|||||||
return {
|
return {
|
||||||
...rest,
|
...rest,
|
||||||
billable: billableValue,
|
billable: billableValue,
|
||||||
|
time_entry_type: typeFilter ?? null,
|
||||||
group: group.value,
|
group: group.value,
|
||||||
sub_group: subGroup.value,
|
sub_group: subGroup.value,
|
||||||
history_group: getOptimalGroupingOption(startDate.value, endDate.value),
|
history_group: getOptimalGroupingOption(startDate.value, endDate.value),
|
||||||
@@ -371,6 +374,7 @@ const tableData = computed(() => {
|
|||||||
v-model:selected-tags="selectedTags"
|
v-model:selected-tags="selectedTags"
|
||||||
v-model:tag-match-type="tagMatchType"
|
v-model:tag-match-type="tagMatchType"
|
||||||
v-model:billable="billable"
|
v-model:billable="billable"
|
||||||
|
v-model:entry-type="entryType"
|
||||||
v-model:rounding-enabled="roundingEnabled"
|
v-model:rounding-enabled="roundingEnabled"
|
||||||
v-model:rounding-type="roundingType"
|
v-model:rounding-type="roundingType"
|
||||||
v-model:rounding-minutes="roundingMinutes"
|
v-model:rounding-minutes="roundingMinutes"
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ const {
|
|||||||
},
|
},
|
||||||
queries: {
|
queries: {
|
||||||
member_id: getCurrentMembershipId(),
|
member_id: getCurrentMembershipId(),
|
||||||
|
type: 'work',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ const queryParams = computed<AggregatedTimeEntriesQueryParams>(() => {
|
|||||||
group: group.value,
|
group: group.value,
|
||||||
sub_group: subGroup.value,
|
sub_group: subGroup.value,
|
||||||
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
|
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
|
||||||
|
// Breaks are excluded from all dashboard stats (see DashboardService workTime())
|
||||||
|
type: 'work',
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import CardTitle from '@/packages/ui/src/CardTitle.vue';
|
|||||||
import { usePage } from '@inertiajs/vue3';
|
import { usePage } from '@inertiajs/vue3';
|
||||||
import { type User } from '@/types/models';
|
import { type User } from '@/types/models';
|
||||||
import { computed, onMounted, watch } from 'vue';
|
import { computed, onMounted, watch } from 'vue';
|
||||||
import dayjs from 'dayjs';
|
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||||
import utc from 'dayjs/plugin/utc';
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import duration from 'dayjs/plugin/duration';
|
|
||||||
|
|
||||||
import { useCurrentTimeEntryStore } from '@/utils/useCurrentTimeEntry';
|
import { getLastWorkTimeEntry, useCurrentTimeEntryStore } from '@/utils/useCurrentTimeEntry';
|
||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||||
|
import { useLocalStorage } from '@vueuse/core';
|
||||||
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
||||||
import { switchOrganization } from '@/utils/useOrganization';
|
import { switchOrganization } from '@/utils/useOrganization';
|
||||||
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
||||||
@@ -20,6 +20,7 @@ import { useClientsQuery } from '@/utils/useClientsQuery';
|
|||||||
import { useTagsStore } from '@/utils/useTags';
|
import { useTagsStore } from '@/utils/useTags';
|
||||||
import { useProjectsStore } from '@/utils/useProjects';
|
import { useProjectsStore } from '@/utils/useProjects';
|
||||||
import TimeTrackerControls from '@/packages/ui/src/TimeTracker/TimeTrackerControls.vue';
|
import TimeTrackerControls from '@/packages/ui/src/TimeTracker/TimeTrackerControls.vue';
|
||||||
|
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
|
||||||
import type {
|
import type {
|
||||||
CreateClientBody,
|
CreateClientBody,
|
||||||
CreateProjectBody,
|
CreateProjectBody,
|
||||||
@@ -44,15 +45,15 @@ const page = usePage<{
|
|||||||
user: User;
|
user: User;
|
||||||
};
|
};
|
||||||
}>();
|
}>();
|
||||||
dayjs.extend(duration);
|
const dayjs = getDayJsInstance();
|
||||||
|
|
||||||
dayjs.extend(utc);
|
|
||||||
|
|
||||||
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
||||||
|
const breaksEnabled = useBreaksEnabled(organization);
|
||||||
|
|
||||||
const currentTimeEntryStore = useCurrentTimeEntryStore();
|
const currentTimeEntryStore = useCurrentTimeEntryStore();
|
||||||
const { currentTimeEntry, isActive, now } = storeToRefs(currentTimeEntryStore);
|
const { currentTimeEntry, isActive, isOnBreak, now } = storeToRefs(currentTimeEntryStore);
|
||||||
const { startLiveTimer, stopLiveTimer, setActiveState } = currentTimeEntryStore;
|
const { startLiveTimer, stopLiveTimer, setActiveState, startBreak, resumeWorkAfterBreak } =
|
||||||
|
currentTimeEntryStore;
|
||||||
|
|
||||||
const { projects } = useProjectsQuery();
|
const { projects } = useProjectsQuery();
|
||||||
const { tasks } = useTasksQuery();
|
const { tasks } = useTasksQuery();
|
||||||
@@ -67,6 +68,8 @@ const showManualTimeEntryModal = ref(false);
|
|||||||
const { createTimeEntry: createTimeEntryMutation, deleteTimeEntry } = useTimeEntriesMutations();
|
const { createTimeEntry: createTimeEntryMutation, deleteTimeEntry } = useTimeEntriesMutations();
|
||||||
const { data: timeEntriesData } = useTimeEntriesInfiniteQuery();
|
const { data: timeEntriesData } = useTimeEntriesInfiniteQuery();
|
||||||
const timeEntries = computed(() => timeEntriesData.value?.pages.flatMap((page) => page.data) || []);
|
const timeEntries = computed(() => timeEntriesData.value?.pages.flatMap((page) => page.data) || []);
|
||||||
|
const lastWorkTimeEntry = computed(() => getLastWorkTimeEntry(timeEntries.value));
|
||||||
|
const canResumeAfterBreak = computed(() => lastWorkTimeEntry.value !== null);
|
||||||
|
|
||||||
watch(isActive, () => {
|
watch(isActive, () => {
|
||||||
if (isActive.value) {
|
if (isActive.value) {
|
||||||
@@ -123,6 +126,14 @@ async function createTimeEntry(timeEntry: Omit<CreateTimeEntryBody, 'member_id'>
|
|||||||
showManualTimeEntryModal.value = false;
|
showManualTimeEntryModal.value = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resumePreviousWorkAfterBreak() {
|
||||||
|
const timeEntry = lastWorkTimeEntry.value;
|
||||||
|
if (!timeEntry) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await resumeWorkAfterBreak(timeEntry);
|
||||||
|
}
|
||||||
|
|
||||||
async function createTimeEntryFromCurrentEntry() {
|
async function createTimeEntryFromCurrentEntry() {
|
||||||
const { start, end, description, project_id, task_id, billable, tags } = currentTimeEntry.value;
|
const { start, end, description, project_id, task_id, billable, tags } = currentTimeEntry.value;
|
||||||
await createTimeEntry({ start, end, description, project_id, task_id, billable, tags });
|
await createTimeEntry({ start, end, description, project_id, task_id, billable, tags });
|
||||||
@@ -142,6 +153,16 @@ async function discardCurrentTimeEntry() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Time tracker UI mode is a per-device UI preference, stored client-side and keyed by organization
|
||||||
|
const timeTrackerMode = useLocalStorage<TimeTrackerMode>(
|
||||||
|
`solidtime/time-tracker-mode/${getCurrentOrganizationId()}`,
|
||||||
|
'project'
|
||||||
|
);
|
||||||
|
|
||||||
|
function toggleTimeTrackerMode() {
|
||||||
|
timeTrackerMode.value = timeTrackerMode.value === 'simple' ? 'project' : 'simple';
|
||||||
|
}
|
||||||
|
|
||||||
const { tags } = useTagsQuery();
|
const { tags } = useTagsQuery();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -186,17 +207,29 @@ const { tags } = useTagsQuery();
|
|||||||
:time-entries
|
:time-entries
|
||||||
:create-tag
|
:create-tag
|
||||||
:is-active
|
:is-active
|
||||||
|
:is-on-break="isOnBreak"
|
||||||
|
:breaks-enabled="breaksEnabled"
|
||||||
|
:can-resume-after-break="canResumeAfterBreak"
|
||||||
|
:resume-description="lastWorkTimeEntry?.description ?? null"
|
||||||
|
:time-tracker-mode="timeTrackerMode"
|
||||||
:currency="getOrganizationCurrencyString()"
|
:currency="getOrganizationCurrencyString()"
|
||||||
@start-live-timer="startLiveTimer"
|
@start-live-timer="startLiveTimer"
|
||||||
@stop-live-timer="stopLiveTimer"
|
@stop-live-timer="stopLiveTimer"
|
||||||
@start-timer="setActiveState(true)"
|
@start-timer="setActiveState(true)"
|
||||||
@stop-timer="setActiveState(false)"
|
@stop-timer="setActiveState(false)"
|
||||||
|
@start-break="startBreak"
|
||||||
|
@resume-after-break="resumePreviousWorkAfterBreak"
|
||||||
@update-time-entry="updateTimeEntry"
|
@update-time-entry="updateTimeEntry"
|
||||||
@create-time-entry="createTimeEntryFromCurrentEntry"></TimeTrackerControls>
|
@create-time-entry="createTimeEntryFromCurrentEntry"></TimeTrackerControls>
|
||||||
</div>
|
</div>
|
||||||
<TimeTrackerMoreOptionsDropdown
|
<TimeTrackerMoreOptionsDropdown
|
||||||
:has-active-timer="isActive"
|
:has-active-timer="isActive"
|
||||||
|
:time-tracker-mode="timeTrackerMode"
|
||||||
|
:is-on-break="isOnBreak"
|
||||||
|
:breaks-enabled="breaksEnabled"
|
||||||
@manual-entry="showManualTimeEntryModal = true"
|
@manual-entry="showManualTimeEntryModal = true"
|
||||||
|
@start-break="startBreak"
|
||||||
|
@toggle-time-tracker-mode="toggleTimeTrackerMode"
|
||||||
@discard="discardCurrentTimeEntry"></TimeTrackerMoreOptionsDropdown>
|
@discard="discardCurrentTimeEntry"></TimeTrackerMoreOptionsDropdown>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
225
resources/js/Components/Timesheet/BreakPlacementModal.vue
Normal file
225
resources/js/Components/Timesheet/BreakPlacementModal.vue
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import DialogModal from '@/packages/ui/src/DialogModal.vue';
|
||||||
|
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||||
|
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
|
import TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
|
||||||
|
import { formatTime, getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
|
import { computed, inject, ref, watch, type ComputedRef } from 'vue';
|
||||||
|
import type { Organization } from '@/packages/api/src';
|
||||||
|
import {
|
||||||
|
BREAK_GAP_TOLERANCE_SECONDS,
|
||||||
|
placementMode,
|
||||||
|
planMoveInsert,
|
||||||
|
planSplitEntry,
|
||||||
|
type BreakPlacementRequest,
|
||||||
|
} from '@/utils/timesheet/breakPlacementMath';
|
||||||
|
import { BREAK_GAP_TOLERANCE_MINUTES } from '@/packages/ui/src/utils/breakPlacement';
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
request: BreakPlacementRequest | null;
|
||||||
|
apply: (breakStart: string, durationSeconds: number) => Promise<void>;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{ cancel: [] }>();
|
||||||
|
|
||||||
|
const organization = inject<ComputedRef<Organization>>('organization');
|
||||||
|
|
||||||
|
const show = computed(() => props.request !== null);
|
||||||
|
const mode = computed(() => (props.request ? placementMode(props.request) : null));
|
||||||
|
const saving = ref(false);
|
||||||
|
|
||||||
|
const localStart = ref('');
|
||||||
|
const localEnd = ref('');
|
||||||
|
|
||||||
|
// Seed the pickers from the suggested placement whenever a new request arrives.
|
||||||
|
watch(
|
||||||
|
() => props.request,
|
||||||
|
(request) => {
|
||||||
|
if (!request) return;
|
||||||
|
localStart.value = getLocalizedDayJs(request.defaultBreakStart).format();
|
||||||
|
localEnd.value = getLocalizedDayJs(request.defaultBreakStart)
|
||||||
|
.add(request.durationSeconds, 'second')
|
||||||
|
.format();
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
const utcStart = computed(() => getLocalizedDayJs(localStart.value).utc().format());
|
||||||
|
const durationSeconds = computed(() =>
|
||||||
|
getLocalizedDayJs(localEnd.value)
|
||||||
|
.utc()
|
||||||
|
.diff(getLocalizedDayJs(localStart.value).utc(), 'second')
|
||||||
|
);
|
||||||
|
|
||||||
|
const splitPlan = computed(() => {
|
||||||
|
if (!props.request || mode.value !== 'split' || durationSeconds.value <= 0) return null;
|
||||||
|
return planSplitEntry(props.request.workEntries[0]!, durationSeconds.value, utcStart.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
const movePlan = computed(() => {
|
||||||
|
if (!props.request || mode.value !== 'move' || durationSeconds.value <= 0) return null;
|
||||||
|
return planMoveInsert(
|
||||||
|
[...props.request.workEntries, ...props.request.otherEntries],
|
||||||
|
props.request.dayStart,
|
||||||
|
props.request.dayEnd,
|
||||||
|
utcStart.value,
|
||||||
|
durationSeconds.value
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Non-blocking heads-up: the placement is feasible but the break would end up
|
||||||
|
// further than the tolerance from work on either side, so it would carry the
|
||||||
|
// misaligned warning right after being created. Mirrors getBreakPlacementHint,
|
||||||
|
// but computed against the planned (post-shift) layout.
|
||||||
|
const resultMisaligned = computed<boolean>(() => {
|
||||||
|
const req = props.request;
|
||||||
|
const plan = movePlan.value;
|
||||||
|
if (!req || mode.value !== 'move' || !plan) return false;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const toMs = (iso: string) => dayjs.utc(iso).valueOf();
|
||||||
|
const breakStartMs = toMs(plan.breakSlot.start);
|
||||||
|
const breakEndMs = toMs(plan.breakSlot.end);
|
||||||
|
const shiftedById = new Map(plan.shifted.map((s) => [s.id, s]));
|
||||||
|
|
||||||
|
let prevWorkEndMs: number | null = null;
|
||||||
|
let nextWorkStartMs: number | null = null;
|
||||||
|
for (const entry of req.workEntries) {
|
||||||
|
const planned = shiftedById.get(entry.id) ?? entry;
|
||||||
|
const startMs = toMs(planned.start);
|
||||||
|
const endMs = toMs(planned.end);
|
||||||
|
if (endMs <= breakStartMs && (prevWorkEndMs === null || endMs > prevWorkEndMs)) {
|
||||||
|
prevWorkEndMs = endMs;
|
||||||
|
}
|
||||||
|
if (startMs >= breakEndMs && (nextWorkStartMs === null || startMs < nextWorkStartMs)) {
|
||||||
|
nextWorkStartMs = startMs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const toleranceMs = BREAK_GAP_TOLERANCE_SECONDS * 1000;
|
||||||
|
return (
|
||||||
|
prevWorkEndMs === null ||
|
||||||
|
breakStartMs - prevWorkEndMs > toleranceMs ||
|
||||||
|
nextWorkStartMs === null ||
|
||||||
|
nextWorkStartMs - breakEndMs > toleranceMs
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
const feasible = computed(() =>
|
||||||
|
mode.value === 'split' ? splitPlan.value !== null : movePlan.value !== null
|
||||||
|
);
|
||||||
|
|
||||||
|
function fmt(iso: string): string {
|
||||||
|
return formatTime(iso, organization?.value?.time_format);
|
||||||
|
}
|
||||||
|
|
||||||
|
const explanation = computed(() => {
|
||||||
|
if (!props.request) return '';
|
||||||
|
return mode.value === 'split'
|
||||||
|
? "There's no free gap that fits this break, so the work entry will be split and the break placed inside it."
|
||||||
|
: "There's no free gap that fits this break, so the surrounding entries will be shifted to make room.";
|
||||||
|
});
|
||||||
|
|
||||||
|
// Human-readable summary of what will change, so the user can confirm the edit.
|
||||||
|
const changeSummary = computed<string[]>(() => {
|
||||||
|
if (mode.value === 'split') {
|
||||||
|
const plan = splitPlan.value;
|
||||||
|
if (!plan) return [];
|
||||||
|
return [
|
||||||
|
`${fmt(plan.firstHalf.start)}–${fmt(plan.firstHalf.end)} (work)`,
|
||||||
|
`${fmt(plan.breakSlot.start)}–${fmt(plan.breakSlot.end)} (break)`,
|
||||||
|
`${fmt(plan.secondHalf.start)}–${fmt(plan.secondHalf.end)} (work)`,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
const plan = movePlan.value;
|
||||||
|
if (!plan) return [];
|
||||||
|
if (plan.shifted.length === 0) return ['No entries need to move.'];
|
||||||
|
return plan.shifted.map((shift) => {
|
||||||
|
const isBreak = props.request!.otherEntries.some((e) => e.id === shift.id);
|
||||||
|
const original =
|
||||||
|
props.request!.workEntries.find((e) => e.id === shift.id) ??
|
||||||
|
props.request!.otherEntries.find((e) => e.id === shift.id)!;
|
||||||
|
const label = `${fmt(original.start)}–${fmt(original.end)} → ${fmt(shift.start)}–${fmt(shift.end)}`;
|
||||||
|
return isBreak ? `${label} (break)` : label;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
if (!feasible.value || durationSeconds.value <= 0) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
await props.apply(utcStart.value, durationSeconds.value);
|
||||||
|
} catch {
|
||||||
|
// apply surfaces its own error toast; keep the modal open so the user can retry
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<DialogModal closeable :show="show" @close="emit('cancel')">
|
||||||
|
<template #title>
|
||||||
|
<div class="flex items-center space-x-2">
|
||||||
|
<Coffee class="w-5 h-5 text-text-secondary" />
|
||||||
|
<span>Add break</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #content>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<p class="text-sm text-text-secondary">{{ explanation }}</p>
|
||||||
|
|
||||||
|
<TimeRangeFields
|
||||||
|
v-model:start="localStart"
|
||||||
|
v-model:end="localEnd"
|
||||||
|
date-picker-size="sm"></TimeRangeFields>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="feasible"
|
||||||
|
data-testid="break_placement_summary"
|
||||||
|
class="rounded-lg border border-card-border bg-secondary/40 px-3 py-2 text-sm text-text-secondary space-y-1">
|
||||||
|
<div class="text-xs uppercase tracking-wide text-text-tertiary">
|
||||||
|
{{ mode === 'split' ? 'Result' : 'Entries that move' }}
|
||||||
|
</div>
|
||||||
|
<div v-for="(line, index) in changeSummary" :key="index" class="tabular-nums">
|
||||||
|
{{ line }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="feasible && resultMisaligned"
|
||||||
|
data-testid="break_placement_misaligned_warning"
|
||||||
|
class="rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-700 dark:text-yellow-400">
|
||||||
|
At this time the break would sit more than
|
||||||
|
{{ BREAK_GAP_TOLERANCE_MINUTES }} minutes away from your work entries and will
|
||||||
|
be flagged as misaligned.
|
||||||
|
</div>
|
||||||
|
<!-- `request` guard (not just !feasible): when the request is cleared on save,
|
||||||
|
the dialog fades out with content still mounted — don't flash the error then -->
|
||||||
|
<div
|
||||||
|
v-if="!feasible && request"
|
||||||
|
data-testid="break_placement_infeasible"
|
||||||
|
class="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
|
||||||
|
{{
|
||||||
|
mode === 'split'
|
||||||
|
? "This break doesn't fit there — it must lie inside the work entry, leaving at least a minute of work on each side."
|
||||||
|
: "This break doesn't fit at that time without pushing an entry outside the day. Try a shorter break or a different time."
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #footer>
|
||||||
|
<SecondaryButton @click="emit('cancel')">Cancel</SecondaryButton>
|
||||||
|
<PrimaryButton
|
||||||
|
class="ms-3"
|
||||||
|
:class="{ 'opacity-25': saving || !feasible }"
|
||||||
|
:disabled="saving || !feasible"
|
||||||
|
@click="submit">
|
||||||
|
Add break
|
||||||
|
</PrimaryButton>
|
||||||
|
</template>
|
||||||
|
</DialogModal>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
||||||
@@ -93,4 +93,26 @@ describe('TimesheetCell', () => {
|
|||||||
|
|
||||||
expect((wrapper.get('input').element as HTMLInputElement).disabled).toBe(true);
|
expect((wrapper.get('input').element as HTMLInputElement).disabled).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('renders read-only and emits nothing when the row is read-only', async () => {
|
||||||
|
const wrapper = mount(TimesheetCell, {
|
||||||
|
props: {
|
||||||
|
cell: buildCell(2 * 3600),
|
||||||
|
dayIndex: 0,
|
||||||
|
date: '2026-04-13',
|
||||||
|
isToday: false,
|
||||||
|
hasRunningEntry: false,
|
||||||
|
readonly: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const input = wrapper.get('input');
|
||||||
|
expect((input.element as HTMLInputElement).disabled).toBe(true);
|
||||||
|
|
||||||
|
await input.trigger('focus');
|
||||||
|
await input.setValue('4h');
|
||||||
|
await input.trigger('blur');
|
||||||
|
|
||||||
|
expect(wrapper.emitted('update')).toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ const props = defineProps<{
|
|||||||
date: string;
|
date: string;
|
||||||
isToday: boolean;
|
isToday: boolean;
|
||||||
hasRunningEntry: boolean;
|
hasRunningEntry: boolean;
|
||||||
|
readonly?: boolean;
|
||||||
saveStatus?: CellSaveStatus;
|
saveStatus?: CellSaveStatus;
|
||||||
pendingSeconds?: number;
|
pendingSeconds?: number;
|
||||||
}>();
|
}>();
|
||||||
@@ -30,6 +31,16 @@ const emit = defineEmits<{
|
|||||||
const displaySeconds = computed(() => props.pendingSeconds ?? props.cell?.totalSeconds ?? 0);
|
const displaySeconds = computed(() => props.pendingSeconds ?? props.cell?.totalSeconds ?? 0);
|
||||||
const isSaving = computed(() => props.saveStatus === 'saving');
|
const isSaving = computed(() => props.saveStatus === 'saving');
|
||||||
|
|
||||||
|
// A cell is non-editable while its entry is running or when the row itself is
|
||||||
|
// read-only (e.g. a leftover break row after breaks were disabled). Both render
|
||||||
|
// the same disabled input, differing only in the tooltip explanation.
|
||||||
|
const isReadonly = computed(() => props.hasRunningEntry || props.readonly === true);
|
||||||
|
const readonlyTooltip = computed(() =>
|
||||||
|
props.hasRunningEntry
|
||||||
|
? 'Stop the running time entry to edit the timesheet'
|
||||||
|
: 'Breaks are disabled for this organization'
|
||||||
|
);
|
||||||
|
|
||||||
// Swap the border color (don't layer) to avoid same-specificity fights.
|
// Swap the border color (don't layer) to avoid same-specificity fights.
|
||||||
const inputClass = computed(() => {
|
const inputClass = computed(() => {
|
||||||
const border = props.saveStatus === 'error' ? 'border-red-500/70' : 'border-input-border';
|
const border = props.saveStatus === 'error' ? 'border-red-500/70' : 'border-input-border';
|
||||||
@@ -51,7 +62,7 @@ const inputClass = computed(() => {
|
|||||||
data-testid="timesheet_cell"
|
data-testid="timesheet_cell"
|
||||||
class="flex items-center justify-center border-t border-default-background-separator"
|
class="flex items-center justify-center border-t border-default-background-separator"
|
||||||
:class="{ 'bg-default-background': isToday }">
|
:class="{ 'bg-default-background': isToday }">
|
||||||
<TooltipProvider v-if="hasRunningEntry" :delay-duration="100">
|
<TooltipProvider v-if="isReadonly" :delay-duration="100">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger as-child>
|
<TooltipTrigger as-child>
|
||||||
<span class="inline-block cursor-not-allowed">
|
<span class="inline-block cursor-not-allowed">
|
||||||
@@ -68,7 +79,7 @@ const inputClass = computed(() => {
|
|||||||
disabled:opacity-50 disabled:cursor-not-allowed" />
|
disabled:opacity-50 disabled:cursor-not-allowed" />
|
||||||
</span>
|
</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent> Stop the running time entry to edit the timesheet </TooltipContent>
|
<TooltipContent>{{ readonlyTooltip }}</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
import { inject, type ComputedRef } from 'vue';
|
import { inject, type ComputedRef } from 'vue';
|
||||||
import { Button } from '@/packages/ui/src/Buttons';
|
import { Button } from '@/packages/ui/src/Buttons';
|
||||||
import { PlusIcon } from '@heroicons/vue/20/solid';
|
import { PlusIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import { ExclamationTriangleIcon, ArrowRightIcon } from '@heroicons/vue/16/solid';
|
||||||
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/packages/ui/src';
|
||||||
|
import { Link } from '@inertiajs/vue3';
|
||||||
import TimesheetRow from '@/Components/Timesheet/TimesheetRow.vue';
|
import TimesheetRow from '@/Components/Timesheet/TimesheetRow.vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||||
@@ -26,6 +29,8 @@ defineProps<{
|
|||||||
todayDate: string;
|
todayDate: string;
|
||||||
dayTotals: number[];
|
dayTotals: number[];
|
||||||
weekTotalFormatted: string;
|
weekTotalFormatted: string;
|
||||||
|
breakDayTotals: number[];
|
||||||
|
breakGrandTotal: number;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
tasks: Task[];
|
tasks: Task[];
|
||||||
clients: Client[];
|
clients: Client[];
|
||||||
@@ -39,6 +44,7 @@ defineProps<{
|
|||||||
formatDuration: (seconds: number) => string;
|
formatDuration: (seconds: number) => string;
|
||||||
cellStatuses: Record<string, CellSaveStatus>;
|
cellStatuses: Record<string, CellSaveStatus>;
|
||||||
cellPendingSeconds: Record<string, number>;
|
cellPendingSeconds: Record<string, number>;
|
||||||
|
misplacedBreakDates?: Set<string>;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
@@ -74,9 +80,34 @@ const emit = defineEmits<{
|
|||||||
<div
|
<div
|
||||||
v-for="day in weekDays"
|
v-for="day in weekDays"
|
||||||
:key="day"
|
:key="day"
|
||||||
|
data-testid="timesheet_day_header"
|
||||||
class="bg-background dark:bg-secondary px-2 py-1 text-center">
|
class="bg-background dark:bg-secondary px-2 py-1 text-center">
|
||||||
<div class="text-xs font-medium text-text-secondary">
|
<div
|
||||||
{{ dayjs(day).format('ddd D') }}
|
class="flex items-center justify-center gap-1 text-xs font-medium text-text-secondary">
|
||||||
|
<span>{{ dayjs(day).format('ddd D') }}</span>
|
||||||
|
<DropdownMenu v-if="misplacedBreakDates?.has(day)">
|
||||||
|
<DropdownMenuTrigger as-child>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title="A break on this day does not align with your work entries"
|
||||||
|
class="flex items-center justify-center shrink-0 rounded-full p-0.5 text-amber-500 hover:bg-amber-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||||
|
<ExclamationTriangleIcon class="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent class="min-w-[240px]" align="start">
|
||||||
|
<div class="px-3 py-2 space-y-1.5">
|
||||||
|
<p class="text-xs text-text-secondary">
|
||||||
|
A break on this day is not directly between work entries.
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
:href="`/calendar?date=${day}`"
|
||||||
|
class="inline-flex items-center gap-1 text-sm font-medium text-accent-400 hover:underline">
|
||||||
|
Fix in calendar
|
||||||
|
<ArrowRightIcon class="w-3.5 h-3.5" />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -85,7 +116,7 @@ const emit = defineEmits<{
|
|||||||
</div>
|
</div>
|
||||||
<div class="bg-background dark:bg-secondary"></div>
|
<div class="bg-background dark:bg-secondary"></div>
|
||||||
|
|
||||||
<!-- Data rows -->
|
<!-- Data rows (break row is pinned last) -->
|
||||||
<TimesheetRow
|
<TimesheetRow
|
||||||
v-for="row in rows"
|
v-for="row in rows"
|
||||||
:key="row.key"
|
:key="row.key"
|
||||||
@@ -140,9 +171,9 @@ const emit = defineEmits<{
|
|||||||
</TimeTrackerProjectTaskDropdown>
|
</TimeTrackerProjectTaskDropdown>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Totals row -->
|
<!-- Totals row: worked time, with break time annotated below (calendar-style) -->
|
||||||
<div
|
<div
|
||||||
class="border-t border-default-background-separator bg-background dark:bg-secondary pl-7 pr-3 py-1 text-xs text-text-tertiary md:sticky md:left-0 md:z-10">
|
class="flex items-center border-t border-default-background-separator bg-background dark:bg-secondary pl-7 pr-3 py-1 text-xs text-text-tertiary md:sticky md:left-0 md:z-10">
|
||||||
Total
|
Total
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -150,18 +181,24 @@ const emit = defineEmits<{
|
|||||||
:key="dayIndex"
|
:key="dayIndex"
|
||||||
data-testid="timesheet_day_total"
|
data-testid="timesheet_day_total"
|
||||||
:class="[
|
:class="[
|
||||||
'flex items-center justify-center border-t border-default-background-separator bg-background dark:bg-secondary px-2 py-1 text-xs font-medium',
|
'flex flex-col items-center justify-center border-t border-default-background-separator bg-background dark:bg-secondary px-2 py-1 text-xs font-medium leading-tight',
|
||||||
weekDays[dayIndex] === todayDate
|
weekDays[dayIndex] === todayDate
|
||||||
? 'text-text-primary'
|
? 'text-text-primary'
|
||||||
: 'text-text-secondary',
|
: 'text-text-secondary',
|
||||||
]">
|
]">
|
||||||
<span class="w-[80px] text-center">
|
<span>{{ total > 0 ? formatDuration(total) : '-' }}</span>
|
||||||
{{ total > 0 ? formatDuration(total) : '-' }}
|
<span
|
||||||
|
v-if="(breakDayTotals[dayIndex] ?? 0) > 0"
|
||||||
|
class="font-normal text-text-tertiary">
|
||||||
|
+{{ formatDuration(breakDayTotals[dayIndex] ?? 0) }} break
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="flex items-center justify-end border-t border-default-background-separator bg-background dark:bg-secondary pl-3 pr-3 py-1 text-xs font-semibold text-text-primary">
|
class="flex flex-col items-end justify-center border-t border-default-background-separator bg-background dark:bg-secondary pl-3 pr-3 py-1 text-xs font-semibold text-text-primary leading-tight">
|
||||||
{{ weekTotalFormatted }}
|
<span>{{ weekTotalFormatted }}</span>
|
||||||
|
<span v-if="breakGrandTotal > 0" class="font-normal text-text-tertiary">
|
||||||
|
+{{ formatDuration(breakGrandTotal) }} break
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="border-t border-default-background-separator bg-background dark:bg-secondary"></div>
|
class="border-t border-default-background-separator bg-background dark:bg-secondary"></div>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, inject, type ComputedRef } from 'vue';
|
import { computed, inject, type ComputedRef } from 'vue';
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import { XMarkIcon } from '@heroicons/vue/16/solid';
|
import { XMarkIcon } from '@heroicons/vue/16/solid';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
import TimesheetCell from './TimesheetCell.vue';
|
import TimesheetCell from './TimesheetCell.vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTagDropdown.vue';
|
import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTagDropdown.vue';
|
||||||
@@ -22,6 +24,7 @@ import {
|
|||||||
import { Button } from '@/packages/ui/src/Buttons';
|
import { Button } from '@/packages/ui/src/Buttons';
|
||||||
|
|
||||||
const organization = inject<ComputedRef<Organization>>('organization');
|
const organization = inject<ComputedRef<Organization>>('organization');
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
row: TimesheetRow;
|
row: TimesheetRow;
|
||||||
@@ -62,6 +65,11 @@ const selectedTask = computed({
|
|||||||
|
|
||||||
const rowTotalFormatted = computed(() => props.formatDuration(props.row.totalSeconds));
|
const rowTotalFormatted = computed(() => props.formatDuration(props.row.totalSeconds));
|
||||||
|
|
||||||
|
// A break row can survive after breaks are disabled (its entries are
|
||||||
|
// grandfathered). Those cells become read-only — creating/editing break time is
|
||||||
|
// rejected server-side — leaving the remove button as the only action.
|
||||||
|
const cellsReadonly = computed(() => props.row.type === 'break' && !breaksEnabled.value);
|
||||||
|
|
||||||
function hasRunningEntry(dayIndex: number): boolean {
|
function hasRunningEntry(dayIndex: number): boolean {
|
||||||
const cell = props.row.cells.get(dayIndex);
|
const cell = props.row.cells.get(dayIndex);
|
||||||
if (!cell) return false;
|
if (!cell) return false;
|
||||||
@@ -74,7 +82,13 @@ function hasRunningEntry(dayIndex: number): boolean {
|
|||||||
<!-- Project/Task column -->
|
<!-- Project/Task column -->
|
||||||
<div
|
<div
|
||||||
class="flex items-center gap-1 border-t border-default-background-separator bg-default-background pl-4 pr-3 py-2 md:sticky md:left-0 md:z-10">
|
class="flex items-center gap-1 border-t border-default-background-separator bg-default-background pl-4 pr-3 py-2 md:sticky md:left-0 md:z-10">
|
||||||
<div class="flex-1 min-w-0">
|
<div
|
||||||
|
v-if="row.type === 'break'"
|
||||||
|
class="flex flex-1 items-center gap-1.5 min-w-0 px-2 py-1 text-sm text-text-secondary">
|
||||||
|
<Coffee class="w-4 h-4" />
|
||||||
|
<span>Break</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex-1 min-w-0">
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
v-model:project="selectedProject"
|
v-model:project="selectedProject"
|
||||||
v-model:task="selectedTask"
|
v-model:task="selectedTask"
|
||||||
@@ -94,11 +108,13 @@ function hasRunningEntry(dayIndex: number): boolean {
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-1 flex-shrink-0 ml-auto">
|
<div class="flex items-center gap-1 flex-shrink-0 ml-auto">
|
||||||
<TimeEntryRowTagDropdown
|
<TimeEntryRowTagDropdown
|
||||||
|
v-if="row.type !== 'break'"
|
||||||
:create-tag="createTag"
|
:create-tag="createTag"
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
:model-value="row.tags"
|
:model-value="row.tags"
|
||||||
@changed="emit('tagsChange', $event)" />
|
@changed="emit('tagsChange', $event)" />
|
||||||
<BillableToggleButton
|
<BillableToggleButton
|
||||||
|
v-if="row.type !== 'break'"
|
||||||
:model-value="row.billable"
|
:model-value="row.billable"
|
||||||
size="small"
|
size="small"
|
||||||
faded
|
faded
|
||||||
@@ -115,6 +131,7 @@ function hasRunningEntry(dayIndex: number): boolean {
|
|||||||
:date="day"
|
:date="day"
|
||||||
:is-today="day === todayDate"
|
:is-today="day === todayDate"
|
||||||
:has-running-entry="hasRunningEntry(dayIndex)"
|
:has-running-entry="hasRunningEntry(dayIndex)"
|
||||||
|
:readonly="cellsReadonly"
|
||||||
:save-status="cellStatuses[makeCellStatusKey(row.key, dayIndex)]"
|
:save-status="cellStatuses[makeCellStatusKey(row.key, dayIndex)]"
|
||||||
:pending-seconds="cellPendingSeconds[makeCellStatusKey(row.key, dayIndex)]"
|
:pending-seconds="cellPendingSeconds[makeCellStatusKey(row.key, dayIndex)]"
|
||||||
@update="(seconds) => emit('cellUpdate', dayIndex, seconds)" />
|
@update="(seconds) => emit('cellUpdate', dayIndex, seconds)" />
|
||||||
@@ -126,10 +143,11 @@ function hasRunningEntry(dayIndex: number): boolean {
|
|||||||
{{ rowTotalFormatted }}
|
{{ rowTotalFormatted }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Remove action -->
|
<!-- Remove action (the break row is permanent while breaks are enabled) -->
|
||||||
<div
|
<div
|
||||||
class="flex items-center justify-center border-t border-default-background-separator pr-4 py-3">
|
class="flex items-center justify-center border-t border-default-background-separator pr-4 py-3">
|
||||||
<Button
|
<Button
|
||||||
|
v-if="!(row.type === 'break' && breaksEnabled)"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="icon"
|
size="icon"
|
||||||
aria-label="Remove row"
|
aria-label="Remove row"
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
|||||||
const calendarStart = ref<Dayjs | undefined>(undefined);
|
const calendarStart = ref<Dayjs | undefined>(undefined);
|
||||||
const calendarEnd = ref<Dayjs | undefined>(undefined);
|
const calendarEnd = ref<Dayjs | undefined>(undefined);
|
||||||
|
|
||||||
|
// Optional deep link (e.g. "Fix in calendar") that opens the calendar on a specific day
|
||||||
|
const initialDate = new URLSearchParams(window.location.search).get('date');
|
||||||
|
|
||||||
// Test-injectable activity periods (for E2E testing).
|
// Test-injectable activity periods (for E2E testing).
|
||||||
// These hooks are no-ops in production — they only take effect when test code
|
// These hooks are no-ops in production — they only take effect when test code
|
||||||
// explicitly sets window globals, so they are safe to ship.
|
// explicitly sets window globals, so they are safe to ship.
|
||||||
@@ -128,6 +131,7 @@ function onRefresh() {
|
|||||||
:enable-estimated-time="isAllowedToPerformPremiumAction()"
|
:enable-estimated-time="isAllowedToPerformPremiumAction()"
|
||||||
:currency="getOrganizationCurrencyString()"
|
:currency="getOrganizationCurrencyString()"
|
||||||
:can-create-project="canCreateProjects()"
|
:can-create-project="canCreateProjects()"
|
||||||
|
:initial-date="initialDate"
|
||||||
:organization-billable-rate="organization?.billable_rate ?? null"
|
:organization-billable-rate="organization?.billable_rate ?? null"
|
||||||
:create-time-entry="createTimeEntry"
|
:create-time-entry="createTimeEntry"
|
||||||
:update-time-entry="updateTimeEntry"
|
:update-time-entry="updateTimeEntry"
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ const selectedTasks = ref<string[]>([]);
|
|||||||
const selectedClients = ref<string[]>([]);
|
const selectedClients = ref<string[]>([]);
|
||||||
const tagMatchType = ref<TagMatchType>('contains');
|
const tagMatchType = ref<TagMatchType>('contains');
|
||||||
const billable = ref<'true' | 'false' | null>(null);
|
const billable = ref<'true' | 'false' | null>(null);
|
||||||
|
const entryType = ref<'work' | 'break' | null>('work');
|
||||||
const roundingEnabled = ref<boolean>(false);
|
const roundingEnabled = ref<boolean>(false);
|
||||||
const roundingType = ref<TimeEntryRoundingType>('nearest');
|
const roundingType = ref<TimeEntryRoundingType>('nearest');
|
||||||
const roundingMinutes = ref<number>(15);
|
const roundingMinutes = ref<number>(15);
|
||||||
@@ -106,6 +107,7 @@ function getFilterAttributes() {
|
|||||||
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
|
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
|
||||||
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
|
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
|
||||||
billable: billable.value !== null ? billable.value : undefined,
|
billable: billable.value !== null ? billable.value : undefined,
|
||||||
|
type: entryType.value !== null ? entryType.value : undefined,
|
||||||
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
|
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
|
||||||
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
|
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
|
||||||
};
|
};
|
||||||
@@ -329,6 +331,7 @@ async function downloadExport(format: ExportFormat) {
|
|||||||
v-model:selected-tags="selectedTags"
|
v-model:selected-tags="selectedTags"
|
||||||
v-model:tag-match-type="tagMatchType"
|
v-model:tag-match-type="tagMatchType"
|
||||||
v-model:billable="billable"
|
v-model:billable="billable"
|
||||||
|
v-model:entry-type="entryType"
|
||||||
v-model:rounding-enabled="roundingEnabled"
|
v-model:rounding-enabled="roundingEnabled"
|
||||||
v-model:rounding-type="roundingType"
|
v-model:rounding-type="roundingType"
|
||||||
v-model:rounding-minutes="roundingMinutes"
|
v-model:rounding-minutes="roundingMinutes"
|
||||||
|
|||||||
@@ -17,15 +17,18 @@ const queryClient = useQueryClient();
|
|||||||
const form = ref<{
|
const form = ref<{
|
||||||
prevent_overlapping_time_entries: boolean;
|
prevent_overlapping_time_entries: boolean;
|
||||||
employees_can_manage_tasks: boolean;
|
employees_can_manage_tasks: boolean;
|
||||||
|
breaks_enabled: boolean;
|
||||||
}>({
|
}>({
|
||||||
prevent_overlapping_time_entries: false,
|
prevent_overlapping_time_entries: false,
|
||||||
employees_can_manage_tasks: false,
|
employees_can_manage_tasks: false,
|
||||||
|
breaks_enabled: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
form.value.prevent_overlapping_time_entries =
|
form.value.prevent_overlapping_time_entries =
|
||||||
organization.value?.prevent_overlapping_time_entries ?? false;
|
organization.value?.prevent_overlapping_time_entries ?? false;
|
||||||
form.value.employees_can_manage_tasks = organization.value?.employees_can_manage_tasks ?? false;
|
form.value.employees_can_manage_tasks = organization.value?.employees_can_manage_tasks ?? false;
|
||||||
|
form.value.breaks_enabled = organization.value?.breaks_enabled ?? false;
|
||||||
});
|
});
|
||||||
|
|
||||||
const mutation = useMutation({
|
const mutation = useMutation({
|
||||||
@@ -39,6 +42,7 @@ async function submit() {
|
|||||||
await mutation.mutateAsync({
|
await mutation.mutateAsync({
|
||||||
prevent_overlapping_time_entries: form.value.prevent_overlapping_time_entries,
|
prevent_overlapping_time_entries: form.value.prevent_overlapping_time_entries,
|
||||||
employees_can_manage_tasks: form.value.employees_can_manage_tasks,
|
employees_can_manage_tasks: form.value.employees_can_manage_tasks,
|
||||||
|
breaks_enabled: form.value.breaks_enabled,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -69,6 +73,10 @@ async function submit() {
|
|||||||
>Allow Employees to manage tasks</FieldLabel
|
>Allow Employees to manage tasks</FieldLabel
|
||||||
>
|
>
|
||||||
</Field>
|
</Field>
|
||||||
|
<Field orientation="horizontal">
|
||||||
|
<Checkbox id="breaksEnabled" v-model:checked="form.breaks_enabled" />
|
||||||
|
<FieldLabel for="breaksEnabled">Allow tracking breaks</FieldLabel>
|
||||||
|
</Field>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import AppLayout from '@/Layouts/AppLayout.vue';
|
import AppLayout from '@/Layouts/AppLayout.vue';
|
||||||
import TimeTracker from '@/Components/TimeTracker.vue';
|
import TimeTracker from '@/Components/TimeTracker.vue';
|
||||||
|
import { router } from '@inertiajs/vue3';
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import MainContainer from '@/packages/ui/src/MainContainer.vue';
|
import MainContainer from '@/packages/ui/src/MainContainer.vue';
|
||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
@@ -102,6 +103,11 @@ function deleteSelected() {
|
|||||||
deleteTimeEntries(selectedTimeEntries.value);
|
deleteTimeEntries(selectedTimeEntries.value);
|
||||||
selectedTimeEntries.value = [];
|
selectedTimeEntries.value = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SPA-navigate the calendar to a break's day so its placement can be fixed there.
|
||||||
|
function goToCalendarDay(date: string) {
|
||||||
|
router.visit(`/calendar?date=${date}`);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -153,6 +159,7 @@ function deleteSelected() {
|
|||||||
:currency="getOrganizationCurrencyString()"
|
:currency="getOrganizationCurrencyString()"
|
||||||
:time-entries="timeEntries"
|
:time-entries="timeEntries"
|
||||||
:group-similar-time-entries="groupSimilarTimeEntriesSetting"
|
:group-similar-time-entries="groupSimilarTimeEntriesSetting"
|
||||||
|
:fix-in-calendar="goToCalendarDay"
|
||||||
:tags="tags"></TimeEntryGroupedTable>
|
:tags="tags"></TimeEntryGroupedTable>
|
||||||
<div v-if="isPending" class="flex justify-center items-center py-12">
|
<div v-if="isPending" class="flex justify-center items-center py-12">
|
||||||
<LoadingSpinner></LoadingSpinner>
|
<LoadingSpinner></LoadingSpinner>
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, watch } from 'vue';
|
import { computed, watch } from 'vue';
|
||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import AppLayout from '@/Layouts/AppLayout.vue';
|
import AppLayout from '@/Layouts/AppLayout.vue';
|
||||||
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
|
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
|
||||||
import TimesheetHeader from '@/Components/Timesheet/TimesheetHeader.vue';
|
import TimesheetHeader from '@/Components/Timesheet/TimesheetHeader.vue';
|
||||||
import TimesheetGrid from '@/Components/Timesheet/TimesheetGrid.vue';
|
import TimesheetGrid from '@/Components/Timesheet/TimesheetGrid.vue';
|
||||||
import TimesheetFooterActions from '@/Components/Timesheet/TimesheetFooterActions.vue';
|
import TimesheetFooterActions from '@/Components/Timesheet/TimesheetFooterActions.vue';
|
||||||
import RemoveRowDialog from '@/Components/Timesheet/RemoveRowDialog.vue';
|
import RemoveRowDialog from '@/Components/Timesheet/RemoveRowDialog.vue';
|
||||||
|
import BreakPlacementModal from '@/Components/Timesheet/BreakPlacementModal.vue';
|
||||||
import { useTimesheetQuery } from '@/utils/useTimesheetQuery';
|
import { useTimesheetQuery } from '@/utils/useTimesheetQuery';
|
||||||
import { useTimesheetGrid } from '@/utils/useTimesheetGrid';
|
import { useTimesheetGrid } from '@/utils/useTimesheetGrid';
|
||||||
import { useTimeEntriesMutations } from '@/utils/useTimeEntriesMutations';
|
import { useTimeEntriesMutations } from '@/utils/useTimeEntriesMutations';
|
||||||
@@ -22,7 +24,12 @@ import { getCurrentOrganizationId } from '@/utils/useUser';
|
|||||||
import { getOrganizationCurrencyString } from '@/utils/money';
|
import { getOrganizationCurrencyString } from '@/utils/money';
|
||||||
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
|
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
|
||||||
import { canCreateProjects } from '@/utils/permissions';
|
import { canCreateProjects } from '@/utils/permissions';
|
||||||
import { formatHumanReadableDuration } from '@/packages/ui/src/utils/time';
|
import {
|
||||||
|
formatHumanReadableDuration,
|
||||||
|
getLocalizedDateFromTimestamp,
|
||||||
|
getLocalizedDayJs,
|
||||||
|
} from '@/packages/ui/src/utils/time';
|
||||||
|
import { getBreakPlacementHint } from '@/packages/ui/src/utils/breakPlacement';
|
||||||
import { useTimesheetWeek } from '@/utils/timesheet/useTimesheetWeek';
|
import { useTimesheetWeek } from '@/utils/timesheet/useTimesheetWeek';
|
||||||
import { useTimesheetCellMutations } from '@/utils/timesheet/useTimesheetCellMutations';
|
import { useTimesheetCellMutations } from '@/utils/timesheet/useTimesheetCellMutations';
|
||||||
import { useTimesheetRowMutations } from '@/utils/timesheet/useTimesheetRowMutations';
|
import { useTimesheetRowMutations } from '@/utils/timesheet/useTimesheetRowMutations';
|
||||||
@@ -45,8 +52,17 @@ const {
|
|||||||
} = useTimesheetWeek();
|
} = useTimesheetWeek();
|
||||||
|
|
||||||
// ── Data fetching ─────────────────────────────────────────────────
|
// ── Data fetching ─────────────────────────────────────────────────
|
||||||
|
// The query fetches one padding day on each side of the week so that entries
|
||||||
|
// crossing midnight at the week edges are known to the break-placement solver.
|
||||||
const { data, isPending } = useTimesheetQuery(weekStart, weekEnd);
|
const { data, isPending } = useTimesheetQuery(weekStart, weekEnd);
|
||||||
const timeEntries = computed(() => data.value?.data ?? []);
|
const allTimeEntries = computed(() => data.value?.data ?? []);
|
||||||
|
// The grid and week-scoped features only see entries starting in the visible week.
|
||||||
|
const timeEntries = computed(() => {
|
||||||
|
const weekDaySet = new Set(weekDays.value);
|
||||||
|
return allTimeEntries.value.filter((entry) =>
|
||||||
|
weekDaySet.has(getLocalizedDateFromTimestamp(entry.start))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
const { projects } = useProjectsQuery();
|
const { projects } = useProjectsQuery();
|
||||||
const { tasks } = useTasksQuery();
|
const { tasks } = useTasksQuery();
|
||||||
@@ -56,19 +72,31 @@ const { now: currentTimerNow } = storeToRefs(useCurrentTimeEntryStore());
|
|||||||
|
|
||||||
const mutations = useTimeEntriesMutations();
|
const mutations = useTimeEntriesMutations();
|
||||||
|
|
||||||
|
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
||||||
|
const breaksEnabled = useBreaksEnabled(organization);
|
||||||
|
|
||||||
// ── Grid computation ──────────────────────────────────────────────
|
// ── Grid computation ──────────────────────────────────────────────
|
||||||
const { rows, dayTotals, grandTotal, addSlot, removeSlot, updateSlot, clearSlots } =
|
const {
|
||||||
useTimesheetGrid(timeEntries, weekDays, projects, tasks, currentTimerNow);
|
rows,
|
||||||
|
dayTotals,
|
||||||
|
grandTotal,
|
||||||
|
breakDayTotals,
|
||||||
|
breakGrandTotal,
|
||||||
|
addSlot,
|
||||||
|
removeSlot,
|
||||||
|
updateSlot,
|
||||||
|
clearSlots,
|
||||||
|
} = useTimesheetGrid(timeEntries, weekDays, projects, tasks, currentTimerNow, breaksEnabled);
|
||||||
|
|
||||||
// Wipe slots on week navigation so the new week starts fresh — the
|
// Wipe slots on week navigation so the new week starts fresh — the
|
||||||
// grid's watcher will reseed from the newly fetched entries.
|
// grid's watcher will reseed from the newly fetched entries.
|
||||||
watch(weekStart, () => clearSlots());
|
// flush: 'sync' so the wipe happens the moment weekStart is assigned, BEFORE
|
||||||
|
// the same flush recomputes `timeEntries` (it depends on weekDays) and lets
|
||||||
|
// the grid seed the new week — otherwise a cached (prefetched) week seeds
|
||||||
|
// first, gets wiped here, and nothing re-triggers the seeding afterwards.
|
||||||
|
watch(weekStart, () => clearSlots(), { flush: 'sync' });
|
||||||
|
|
||||||
// ── Formatters ────────────────────────────────────────────────────
|
// ── Formatters ────────────────────────────────────────────────────
|
||||||
// Pull number/interval format off the org via its query rather than
|
|
||||||
// inject('organization'), which is undefined during the page's setup
|
|
||||||
// (AppLayout provides it later in the lifecycle).
|
|
||||||
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
|
||||||
const intervalFormat = computed(() => organization.value?.interval_format ?? 'hours-minutes');
|
const intervalFormat = computed(() => organization.value?.interval_format ?? 'hours-minutes');
|
||||||
const numberFormat = computed(() => organization.value?.number_format ?? 'point');
|
const numberFormat = computed(() => organization.value?.number_format ?? 'point');
|
||||||
|
|
||||||
@@ -90,12 +118,28 @@ const weekRangeDisplay = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ── Cell / row mutation handlers ──────────────────────────────────
|
// ── Cell / row mutation handlers ──────────────────────────────────
|
||||||
const { handleCellUpdate, cellStatus, cellPendingSeconds } = useTimesheetCellMutations(
|
const {
|
||||||
weekDays,
|
handleCellUpdate,
|
||||||
timeEntries,
|
cellStatus,
|
||||||
rows,
|
cellPendingSeconds,
|
||||||
removeSlot
|
breakPlacementRequest,
|
||||||
);
|
applyBreakPlacement,
|
||||||
|
dismissBreakPlacement,
|
||||||
|
} = useTimesheetCellMutations(weekDays, allTimeEntries, rows, removeSlot);
|
||||||
|
|
||||||
|
// Local dates (YYYY-MM-DD) that have a misplaced break. There is only one break
|
||||||
|
// row, so a flat set is enough — its cells show a warning for dates in the set.
|
||||||
|
const misplacedBreakDates = computed<Set<string>>(() => {
|
||||||
|
const dates = new Set<string>();
|
||||||
|
for (const entry of timeEntries.value) {
|
||||||
|
if (entry.type !== 'break') continue;
|
||||||
|
// Hint against the padded list so work just across midnight counts.
|
||||||
|
if (getBreakPlacementHint(entry, allTimeEntries.value)?.misplaced) {
|
||||||
|
dates.add(getLocalizedDayJs(entry.start).format('YYYY-MM-DD'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dates;
|
||||||
|
});
|
||||||
|
|
||||||
const { handleRowIdentityChange, handleAddRow } = useTimesheetRowMutations(
|
const { handleRowIdentityChange, handleAddRow } = useTimesheetRowMutations(
|
||||||
mutations,
|
mutations,
|
||||||
@@ -125,7 +169,8 @@ const { isCopyingLastWeek, copyLastWeekRows, copyLastWeekWithTime } = useCopyLas
|
|||||||
weekDays,
|
weekDays,
|
||||||
rows,
|
rows,
|
||||||
timeEntries,
|
timeEntries,
|
||||||
addSlot
|
addSlot,
|
||||||
|
breaksEnabled
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── Inline creation helpers (passed to TimesheetRow) ──────────────
|
// ── Inline creation helpers (passed to TimesheetRow) ──────────────
|
||||||
@@ -161,6 +206,8 @@ async function createTag(name: string): Promise<Tag | undefined> {
|
|||||||
:today-date="todayDate"
|
:today-date="todayDate"
|
||||||
:day-totals="dayTotals"
|
:day-totals="dayTotals"
|
||||||
:week-total-formatted="weekTotalFormatted"
|
:week-total-formatted="weekTotalFormatted"
|
||||||
|
:break-day-totals="breakDayTotals"
|
||||||
|
:break-grand-total="breakGrandTotal"
|
||||||
:projects="projects"
|
:projects="projects"
|
||||||
:tasks="tasks"
|
:tasks="tasks"
|
||||||
:clients="clients"
|
:clients="clients"
|
||||||
@@ -174,6 +221,7 @@ async function createTag(name: string): Promise<Tag | undefined> {
|
|||||||
:format-duration="formatDuration"
|
:format-duration="formatDuration"
|
||||||
:cell-statuses="cellStatus"
|
:cell-statuses="cellStatus"
|
||||||
:cell-pending-seconds="cellPendingSeconds"
|
:cell-pending-seconds="cellPendingSeconds"
|
||||||
|
:misplaced-break-dates="misplacedBreakDates"
|
||||||
@remove-row="handleRemoveRow"
|
@remove-row="handleRemoveRow"
|
||||||
@cell-update="handleCellUpdate"
|
@cell-update="handleCellUpdate"
|
||||||
@project-task-change="
|
@project-task-change="
|
||||||
@@ -199,5 +247,10 @@ async function createTag(name: string): Promise<Tag | undefined> {
|
|||||||
:entry-count="deleteRowEntryCount"
|
:entry-count="deleteRowEntryCount"
|
||||||
:project-name="deleteRowProjectName"
|
:project-name="deleteRowProjectName"
|
||||||
@confirm="confirmDeleteRow" />
|
@confirm="confirmDeleteRow" />
|
||||||
|
|
||||||
|
<BreakPlacementModal
|
||||||
|
:request="breakPlacementRequest"
|
||||||
|
:apply="applyBreakPlacement"
|
||||||
|
@cancel="dismissBreakPlacement" />
|
||||||
</AppLayout>
|
</AppLayout>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export type Invitation = InvitationsIndexResponse['data'][0];
|
|||||||
|
|
||||||
export type TimeEntryResponse = ZodiosResponseByAlias<SolidTimeApi, 'getTimeEntries'>;
|
export type TimeEntryResponse = ZodiosResponseByAlias<SolidTimeApi, 'getTimeEntries'>;
|
||||||
export type TimeEntry = TimeEntryResponse['data'][0];
|
export type TimeEntry = TimeEntryResponse['data'][0];
|
||||||
|
export type TimeEntryType = TimeEntry['type'];
|
||||||
|
|
||||||
export type CreateTimeEntryBody = ZodiosBodyByAlias<SolidTimeApi, 'createTimeEntry'>;
|
export type CreateTimeEntryBody = ZodiosBodyByAlias<SolidTimeApi, 'createTimeEntry'>;
|
||||||
|
|
||||||
|
|||||||
@@ -319,6 +319,7 @@ const OrganizationResource = z
|
|||||||
employees_can_see_billable_rates: z.boolean(),
|
employees_can_see_billable_rates: z.boolean(),
|
||||||
employees_can_manage_tasks: z.boolean(),
|
employees_can_manage_tasks: z.boolean(),
|
||||||
prevent_overlapping_time_entries: z.boolean(),
|
prevent_overlapping_time_entries: z.boolean(),
|
||||||
|
breaks_enabled: z.boolean(),
|
||||||
currency: z.string(),
|
currency: z.string(),
|
||||||
currency_symbol: z.string(),
|
currency_symbol: z.string(),
|
||||||
number_format: NumberFormat,
|
number_format: NumberFormat,
|
||||||
@@ -336,6 +337,7 @@ const OrganizationUpdateRequest = z
|
|||||||
employees_can_see_billable_rates: z.boolean(),
|
employees_can_see_billable_rates: z.boolean(),
|
||||||
employees_can_manage_tasks: z.boolean(),
|
employees_can_manage_tasks: z.boolean(),
|
||||||
prevent_overlapping_time_entries: z.boolean(),
|
prevent_overlapping_time_entries: z.boolean(),
|
||||||
|
breaks_enabled: z.boolean(),
|
||||||
number_format: NumberFormat,
|
number_format: NumberFormat,
|
||||||
currency_format: CurrencyFormat,
|
currency_format: CurrencyFormat,
|
||||||
date_format: DateFormat,
|
date_format: DateFormat,
|
||||||
@@ -420,6 +422,7 @@ const TimeEntryAggregationType = z.enum([
|
|||||||
'billable',
|
'billable',
|
||||||
'description',
|
'description',
|
||||||
'tag',
|
'tag',
|
||||||
|
'type',
|
||||||
]);
|
]);
|
||||||
const TimeEntryAggregationTypeInterval = z.enum(['day', 'week', 'month', 'year']);
|
const TimeEntryAggregationTypeInterval = z.enum(['day', 'week', 'month', 'year']);
|
||||||
const Weekday = z.enum([
|
const Weekday = z.enum([
|
||||||
@@ -479,6 +482,7 @@ const DetailedReportResource = z
|
|||||||
active: z.union([z.boolean(), z.null()]),
|
active: z.union([z.boolean(), z.null()]),
|
||||||
member_ids: z.union([z.array(z.string()), z.null()]),
|
member_ids: z.union([z.array(z.string()), z.null()]),
|
||||||
billable: z.union([z.boolean(), z.null()]),
|
billable: z.union([z.boolean(), z.null()]),
|
||||||
|
time_entry_type: z.union([z.enum(['work', 'break']), z.null()]),
|
||||||
client_ids: z.union([z.array(z.string()), z.null()]),
|
client_ids: z.union([z.array(z.string()), z.null()]),
|
||||||
project_ids: z.union([z.array(z.string()), z.null()]),
|
project_ids: z.union([z.array(z.string()), z.null()]),
|
||||||
tag_ids: z.union([z.array(z.string()), z.null()]),
|
tag_ids: z.union([z.array(z.string()), z.null()]),
|
||||||
@@ -631,6 +635,7 @@ const TaskUpdateRequest = z
|
|||||||
.passthrough();
|
.passthrough();
|
||||||
const start = z.union([z.string(), z.null()]).optional();
|
const start = z.union([z.string(), z.null()]).optional();
|
||||||
const rounding_minutes = z.union([z.number(), z.null()]).optional();
|
const rounding_minutes = z.union([z.number(), z.null()]).optional();
|
||||||
|
const TimeEntryType = z.enum(['work', 'break']);
|
||||||
const TimeEntryResource = z
|
const TimeEntryResource = z
|
||||||
.object({
|
.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
@@ -644,6 +649,7 @@ const TimeEntryResource = z
|
|||||||
user_id: z.string(),
|
user_id: z.string(),
|
||||||
tags: z.array(z.string()),
|
tags: z.array(z.string()),
|
||||||
billable: z.boolean(),
|
billable: z.boolean(),
|
||||||
|
type: TimeEntryType,
|
||||||
})
|
})
|
||||||
.passthrough();
|
.passthrough();
|
||||||
const TimeEntryStoreRequest = z
|
const TimeEntryStoreRequest = z
|
||||||
@@ -654,6 +660,7 @@ const TimeEntryStoreRequest = z
|
|||||||
start: z.string(),
|
start: z.string(),
|
||||||
end: z.union([z.string(), z.null()]).optional(),
|
end: z.union([z.string(), z.null()]).optional(),
|
||||||
billable: z.boolean(),
|
billable: z.boolean(),
|
||||||
|
type: TimeEntryType.optional(),
|
||||||
description: z.union([z.string(), z.null()]).optional(),
|
description: z.union([z.string(), z.null()]).optional(),
|
||||||
tags: z.union([z.array(z.string()), z.null()]).optional(),
|
tags: z.union([z.array(z.string()), z.null()]).optional(),
|
||||||
})
|
})
|
||||||
@@ -667,6 +674,7 @@ const TimeEntryUpdateMultipleRequest = z
|
|||||||
project_id: z.union([z.string(), z.null()]),
|
project_id: z.union([z.string(), z.null()]),
|
||||||
task_id: z.union([z.string(), z.null()]),
|
task_id: z.union([z.string(), z.null()]),
|
||||||
billable: z.boolean(),
|
billable: z.boolean(),
|
||||||
|
type: TimeEntryType,
|
||||||
description: z.union([z.string(), z.null()]),
|
description: z.union([z.string(), z.null()]),
|
||||||
tags: z.union([z.array(z.string()), z.null()]),
|
tags: z.union([z.array(z.string()), z.null()]),
|
||||||
})
|
})
|
||||||
@@ -682,6 +690,7 @@ const TimeEntryUpdateRequest = z
|
|||||||
start: z.string(),
|
start: z.string(),
|
||||||
end: z.union([z.string(), z.null()]),
|
end: z.union([z.string(), z.null()]),
|
||||||
billable: z.boolean(),
|
billable: z.boolean(),
|
||||||
|
type: TimeEntryType,
|
||||||
description: z.union([z.string(), z.null()]),
|
description: z.union([z.string(), z.null()]),
|
||||||
tags: z.union([z.array(z.string()), z.null()]),
|
tags: z.union([z.array(z.string()), z.null()]),
|
||||||
})
|
})
|
||||||
@@ -774,6 +783,7 @@ export const schemas = {
|
|||||||
TaskUpdateRequest,
|
TaskUpdateRequest,
|
||||||
start,
|
start,
|
||||||
rounding_minutes,
|
rounding_minutes,
|
||||||
|
TimeEntryType,
|
||||||
TimeEntryResource,
|
TimeEntryResource,
|
||||||
TimeEntryStoreRequest,
|
TimeEntryStoreRequest,
|
||||||
TimeEntryUpdateMultipleRequest,
|
TimeEntryUpdateMultipleRequest,
|
||||||
@@ -3736,6 +3746,11 @@ Users with the permission `time-entries:view:own` can only use this en
|
|||||||
type: 'Query',
|
type: 'Query',
|
||||||
schema: z.enum(['true', 'false']).optional(),
|
schema: z.enum(['true', 'false']).optional(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'type',
|
||||||
|
type: 'Query',
|
||||||
|
schema: TimeEntryType.optional(),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'limit',
|
name: 'limit',
|
||||||
type: 'Query',
|
type: 'Query',
|
||||||
@@ -3895,7 +3910,9 @@ Users with the permission `time-entries:view:own` can only use this en
|
|||||||
schema: z.string(),
|
schema: z.string(),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
response: z.object({ success: z.string(), error: z.string() }).passthrough(),
|
response: z
|
||||||
|
.object({ success: z.array(z.string()), error: z.array(z.string()) })
|
||||||
|
.passthrough(),
|
||||||
errors: [
|
errors: [
|
||||||
{
|
{
|
||||||
status: 401,
|
status: 401,
|
||||||
@@ -4085,6 +4102,7 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
'billable',
|
'billable',
|
||||||
'description',
|
'description',
|
||||||
'tag',
|
'tag',
|
||||||
|
'type',
|
||||||
])
|
])
|
||||||
.optional(),
|
.optional(),
|
||||||
},
|
},
|
||||||
@@ -4104,6 +4122,7 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
'billable',
|
'billable',
|
||||||
'description',
|
'description',
|
||||||
'tag',
|
'tag',
|
||||||
|
'type',
|
||||||
])
|
])
|
||||||
.optional(),
|
.optional(),
|
||||||
},
|
},
|
||||||
@@ -4137,6 +4156,11 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
type: 'Query',
|
type: 'Query',
|
||||||
schema: z.enum(['true', 'false']).optional(),
|
schema: z.enum(['true', 'false']).optional(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'type',
|
||||||
|
type: 'Query',
|
||||||
|
schema: TimeEntryType.optional(),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'fill_gaps_in_time_groups',
|
name: 'fill_gaps_in_time_groups',
|
||||||
type: 'Query',
|
type: 'Query',
|
||||||
@@ -4277,6 +4301,7 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
'billable',
|
'billable',
|
||||||
'description',
|
'description',
|
||||||
'tag',
|
'tag',
|
||||||
|
'type',
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -4294,6 +4319,7 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
'billable',
|
'billable',
|
||||||
'description',
|
'description',
|
||||||
'tag',
|
'tag',
|
||||||
|
'type',
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -4331,6 +4357,11 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
type: 'Query',
|
type: 'Query',
|
||||||
schema: z.enum(['true', 'false']).optional(),
|
schema: z.enum(['true', 'false']).optional(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'type',
|
||||||
|
type: 'Query',
|
||||||
|
schema: TimeEntryType.optional(),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'fill_gaps_in_time_groups',
|
name: 'fill_gaps_in_time_groups',
|
||||||
type: 'Query',
|
type: 'Query',
|
||||||
@@ -4459,6 +4490,11 @@ If the group parameters are all set to `null` or are all missing, the
|
|||||||
type: 'Query',
|
type: 'Query',
|
||||||
schema: z.enum(['true', 'false']).optional(),
|
schema: z.enum(['true', 'false']).optional(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'type',
|
||||||
|
type: 'Query',
|
||||||
|
schema: TimeEntryType.optional(),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'limit',
|
name: 'limit',
|
||||||
type: 'Query',
|
type: 'Query',
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
|
|||||||
variant: {
|
variant: {
|
||||||
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
|
||||||
destructive:
|
destructive:
|
||||||
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
|
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 dark:bg-destructive/70',
|
||||||
outline:
|
outline:
|
||||||
'border shadow-xs hover:text-text-primary bg-card-background dark:bg-transparent border-input dark:border-input hover:bg-white/5',
|
'border shadow-xs hover:text-text-primary bg-card-background dark:bg-transparent border-input dark:border-input hover:bg-white/5',
|
||||||
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ const emit = defineEmits<{
|
|||||||
getEventOpacityClass(dayEvent, dayStr),
|
getEventOpacityClass(dayEvent, dayStr),
|
||||||
{
|
{
|
||||||
'running-entry rounded-b-none': dayEvent.event.isRunning,
|
'running-entry rounded-b-none': dayEvent.event.isRunning,
|
||||||
|
'fc-event-break': dayEvent.event.isBreak,
|
||||||
'fc-event-dragging': isDragging && dragEventId === dayEvent.event.id,
|
'fc-event-dragging': isDragging && dragEventId === dayEvent.event.id,
|
||||||
'fc-event-resizing': resizeEventId === dayEvent.event.id,
|
'fc-event-resizing': resizeEventId === dayEvent.event.id,
|
||||||
'rounded-t-none': dayEvent.isClippedStart,
|
'rounded-t-none': dayEvent.isClippedStart,
|
||||||
@@ -121,6 +122,8 @@ const emit = defineEmits<{
|
|||||||
:project-name="dayEvent.event.project?.name"
|
:project-name="dayEvent.event.project?.name"
|
||||||
:task-name="dayEvent.event.task?.name"
|
:task-name="dayEvent.event.task?.name"
|
||||||
:client-name="dayEvent.event.client?.name"
|
:client-name="dayEvent.event.client?.name"
|
||||||
|
:is-break="dayEvent.event.isBreak"
|
||||||
|
:is-misplaced-break="dayEvent.event.isMisplacedBreak"
|
||||||
:duration-seconds="getEventDurationSeconds(dayEvent, dayStr)" />
|
:duration-seconds="getEventDurationSeconds(dayEvent, dayStr)" />
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -413,4 +416,15 @@ const emit = defineEmits<{
|
|||||||
.fc-events-inset-expanded {
|
.fc-events-inset-expanded {
|
||||||
left: 204px;
|
left: 204px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Breaks get a hatched texture so they can not be confused with a project color */
|
||||||
|
.fc-event-break {
|
||||||
|
background-image: repeating-linear-gradient(
|
||||||
|
-45deg,
|
||||||
|
transparent,
|
||||||
|
transparent 5px,
|
||||||
|
rgba(217, 119, 6, 0.15) 5px,
|
||||||
|
rgba(217, 119, 6, 0.15) 7px
|
||||||
|
);
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -7,10 +7,12 @@ import type { Dayjs } from 'dayjs';
|
|||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
date: Dayjs;
|
date: Dayjs;
|
||||||
totalSeconds?: number;
|
totalSeconds?: number;
|
||||||
|
breakSeconds?: number;
|
||||||
isToday?: boolean;
|
isToday?: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const totalSecondsValue = computed(() => props.totalSeconds ?? 0);
|
const totalSecondsValue = computed(() => props.totalSeconds ?? 0);
|
||||||
|
const breakSecondsValue = computed(() => props.breakSeconds ?? 0);
|
||||||
|
|
||||||
const organization = inject('organization') as ComputedRef<Organization | undefined> | undefined;
|
const organization = inject('organization') as ComputedRef<Organization | undefined> | undefined;
|
||||||
const intervalFormat = computed(() => organization?.value?.interval_format);
|
const intervalFormat = computed(() => organization?.value?.interval_format);
|
||||||
@@ -24,6 +26,10 @@ const numberFormat = computed(() => organization?.value?.number_format);
|
|||||||
</div>
|
</div>
|
||||||
<span class="block text-xs text-muted-foreground font-medium mt-0.5">
|
<span class="block text-xs text-muted-foreground font-medium mt-0.5">
|
||||||
{{ formatHumanReadableDuration(totalSecondsValue, intervalFormat, numberFormat) }}
|
{{ formatHumanReadableDuration(totalSecondsValue, intervalFormat, numberFormat) }}
|
||||||
|
<template v-if="breakSecondsValue > 0">
|
||||||
|
· {{ formatHumanReadableDuration(breakSecondsValue, intervalFormat, numberFormat) }}
|
||||||
|
break
|
||||||
|
</template>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
import { computed, inject, type ComputedRef } from 'vue';
|
import { computed, inject, type ComputedRef } from 'vue';
|
||||||
import { formatHumanReadableDuration, getDayJsInstance } from '../utils/time';
|
import { formatHumanReadableDuration, getDayJsInstance } from '../utils/time';
|
||||||
import type { Organization } from '@/packages/api/src';
|
import type { Organization } from '@/packages/api/src';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
|
import { ExclamationTriangleIcon } from '@heroicons/vue/20/solid';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
title: string;
|
title: string;
|
||||||
@@ -11,6 +13,8 @@ const props = defineProps<{
|
|||||||
durationSeconds?: number;
|
durationSeconds?: number;
|
||||||
start?: string | Date | null;
|
start?: string | Date | null;
|
||||||
end?: string | Date | null;
|
end?: string | Date | null;
|
||||||
|
isBreak?: boolean;
|
||||||
|
isMisplacedBreak?: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const effectiveDurationSeconds = computed(() => {
|
const effectiveDurationSeconds = computed(() => {
|
||||||
@@ -41,7 +45,15 @@ const formattedDuration = computed(() =>
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="text-2xs leading-tight px-0.5 py-1">
|
<div class="text-2xs leading-tight px-0.5 py-1">
|
||||||
<div class="font-semibold">{{ title }}</div>
|
<div class="font-semibold flex items-center gap-1">
|
||||||
|
<Coffee v-if="isBreak" class="w-3 h-3 shrink-0" />
|
||||||
|
<span class="truncate">{{ title }}</span>
|
||||||
|
<ExclamationTriangleIcon
|
||||||
|
v-if="isMisplacedBreak"
|
||||||
|
data-testid="calendar_break_placement_hint"
|
||||||
|
title="This break does not align with your work entries"
|
||||||
|
class="w-3 h-3 shrink-0 text-amber-600 dark:text-amber-400" />
|
||||||
|
</div>
|
||||||
<div v-if="projectName" class="font-medium opacity-90">
|
<div v-if="projectName" class="font-medium opacity-90">
|
||||||
{{ projectName }}
|
{{ projectName }}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ import {
|
|||||||
} from 'vue';
|
} from 'vue';
|
||||||
import { useLocalStorage } from '@vueuse/core';
|
import { useLocalStorage } from '@vueuse/core';
|
||||||
import { useCssVariable } from '../utils/useCssVariable';
|
import { useCssVariable } from '../utils/useCssVariable';
|
||||||
import { getLocalizedDayJs } from '../utils/time';
|
import { useBreaksEnabled } from '../utils/useBreaksEnabled';
|
||||||
|
import { getLocalizedDayJs, getLocalizedDayJsFromMinutes } from '../utils/time';
|
||||||
import { LoadingSpinner, TimeEntryCreateModal, TimeEntryEditModal } from '..';
|
import { LoadingSpinner, TimeEntryCreateModal, TimeEntryEditModal } from '..';
|
||||||
|
import BreakCreateModal from '../TimeEntry/BreakCreateModal.vue';
|
||||||
import FullCalendarDayHeader from './FullCalendarDayHeader.vue';
|
import FullCalendarDayHeader from './FullCalendarDayHeader.vue';
|
||||||
import CalendarToolbar from './CalendarToolbar.vue';
|
import CalendarToolbar from './CalendarToolbar.vue';
|
||||||
import CalendarDayColumn from './CalendarDayColumn.vue';
|
import CalendarDayColumn from './CalendarDayColumn.vue';
|
||||||
@@ -34,6 +36,7 @@ import {
|
|||||||
StopIcon,
|
StopIcon,
|
||||||
XMarkIcon,
|
XMarkIcon,
|
||||||
} from '@heroicons/vue/20/solid';
|
} from '@heroicons/vue/20/solid';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
import type { ActivityPeriod } from './activityTypes';
|
import type { ActivityPeriod } from './activityTypes';
|
||||||
import { SLOT_HEIGHT, TIME_AXIS_WIDTH, type DayEvent } from './calendarTypes';
|
import { SLOT_HEIGHT, TIME_AXIS_WIDTH, type DayEvent } from './calendarTypes';
|
||||||
import { useCalendarGrid } from './useCalendarGrid';
|
import { useCalendarGrid } from './useCalendarGrid';
|
||||||
@@ -74,6 +77,8 @@ const props = defineProps<{
|
|||||||
currency: string;
|
currency: string;
|
||||||
canCreateProject: boolean;
|
canCreateProject: boolean;
|
||||||
organizationBillableRate: number | null;
|
organizationBillableRate: number | null;
|
||||||
|
// Local date (YYYY-MM-DD) to open the calendar on, e.g. from a "Fix in calendar" deep link
|
||||||
|
initialDate?: string | null;
|
||||||
|
|
||||||
createTimeEntry: (
|
createTimeEntry: (
|
||||||
entry: Omit<TimeEntry, 'id' | 'organization_id' | 'user_id'>
|
entry: Omit<TimeEntry, 'id' | 'organization_id' | 'user_id'>
|
||||||
@@ -87,6 +92,9 @@ const props = defineProps<{
|
|||||||
|
|
||||||
const newEventStart = ref<Dayjs | null>(null);
|
const newEventStart = ref<Dayjs | null>(null);
|
||||||
const newEventEnd = ref<Dayjs | null>(null);
|
const newEventEnd = ref<Dayjs | null>(null);
|
||||||
|
const showCreateBreakModal = ref(false);
|
||||||
|
const newBreakStart = ref<Dayjs | null>(null);
|
||||||
|
const newBreakEnd = ref<Dayjs | null>(null);
|
||||||
const showCreateTimeEntryModal = ref<boolean>(false);
|
const showCreateTimeEntryModal = ref<boolean>(false);
|
||||||
const showEditTimeEntryModal = ref<boolean>(false);
|
const showEditTimeEntryModal = ref<boolean>(false);
|
||||||
const selectedTimeEntry = ref<TimeEntry | null>(null);
|
const selectedTimeEntry = ref<TimeEntry | null>(null);
|
||||||
@@ -114,6 +122,7 @@ const currentTime = ref(getLocalizedDayJs());
|
|||||||
let currentTimeInterval: ReturnType<typeof setInterval> | null = null;
|
let currentTimeInterval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
const organization = inject<ComputedRef<Organization>>('organization');
|
const organization = inject<ComputedRef<Organization>>('organization');
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
slots,
|
slots,
|
||||||
@@ -138,12 +147,23 @@ const {
|
|||||||
} = useCalendarNavigation({
|
} = useCalendarNavigation({
|
||||||
onDatesChange: (payload) => emit('dates-change', payload),
|
onDatesChange: (payload) => emit('dates-change', payload),
|
||||||
scrollToCurrentTime: () => scrollToCurrentTime(),
|
scrollToCurrentTime: () => scrollToCurrentTime(),
|
||||||
|
// Parse as local midnight in the user's timezone — getLocalizedDayJs would
|
||||||
|
// treat the bare date as UTC midnight, landing on the previous local day
|
||||||
|
// for negative UTC offsets
|
||||||
|
initialDate: props.initialDate ? getLocalizedDayJsFromMinutes(props.initialDate, 0) : null,
|
||||||
});
|
});
|
||||||
|
|
||||||
const cssBackground = useCssVariable('--color-bg-background');
|
const cssBackground = useCssVariable('--color-bg-background');
|
||||||
|
|
||||||
const { optimisticOverrides, calendarEvents, eventsByDay, dailyTotals, isToday, nowIndicatorTop } =
|
const {
|
||||||
useCalendarEvents({
|
optimisticOverrides,
|
||||||
|
calendarEvents,
|
||||||
|
eventsByDay,
|
||||||
|
dailyTotals,
|
||||||
|
dailyBreakTotals,
|
||||||
|
isToday,
|
||||||
|
nowIndicatorTop,
|
||||||
|
} = useCalendarEvents({
|
||||||
timeEntries: () => props.timeEntries,
|
timeEntries: () => props.timeEntries,
|
||||||
projects: () => props.projects,
|
projects: () => props.projects,
|
||||||
clients: () => props.clients,
|
clients: () => props.clients,
|
||||||
@@ -244,6 +264,7 @@ const {
|
|||||||
handleContextStop,
|
handleContextStop,
|
||||||
handleContextDiscard,
|
handleContextDiscard,
|
||||||
handleContextCreate,
|
handleContextCreate,
|
||||||
|
handleContextCreateBreak,
|
||||||
} = useContextMenu({
|
} = useContextMenu({
|
||||||
calendarSettings,
|
calendarSettings,
|
||||||
calendarEvents,
|
calendarEvents,
|
||||||
@@ -262,6 +283,11 @@ const {
|
|||||||
newEventEnd.value = end;
|
newEventEnd.value = end;
|
||||||
showCreateTimeEntryModal.value = true;
|
showCreateTimeEntryModal.value = true;
|
||||||
},
|
},
|
||||||
|
onCreateBreak: (start, end) => {
|
||||||
|
newBreakStart.value = start;
|
||||||
|
newBreakEnd.value = end;
|
||||||
|
showCreateBreakModal.value = true;
|
||||||
|
},
|
||||||
emitRefresh: () => emit('refresh'),
|
emitRefresh: () => emit('refresh'),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -274,6 +300,14 @@ watch(showCreateTimeEntryModal, (value) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
watch(showCreateBreakModal, (value) => {
|
||||||
|
if (!value) {
|
||||||
|
newBreakStart.value = null;
|
||||||
|
newBreakEnd.value = null;
|
||||||
|
emit('refresh');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
watch(showEditTimeEntryModal, (value) => {
|
watch(showEditTimeEntryModal, (value) => {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
selectedTimeEntry.value = null;
|
selectedTimeEntry.value = null;
|
||||||
@@ -455,6 +489,12 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
|
|||||||
:start="newEventStart ? newEventStart.toISOString() : undefined"
|
:start="newEventStart ? newEventStart.toISOString() : undefined"
|
||||||
:end="newEventEnd ? newEventEnd.toISOString() : undefined" />
|
:end="newEventEnd ? newEventEnd.toISOString() : undefined" />
|
||||||
|
|
||||||
|
<BreakCreateModal
|
||||||
|
v-model:show="showCreateBreakModal"
|
||||||
|
:create-time-entry="createTimeEntry"
|
||||||
|
:start="newBreakStart ? newBreakStart.toISOString() : undefined"
|
||||||
|
:end="newBreakEnd ? newBreakEnd.toISOString() : undefined" />
|
||||||
|
|
||||||
<TimeEntryEditModal
|
<TimeEntryEditModal
|
||||||
v-model:show="showEditTimeEntryModal"
|
v-model:show="showEditTimeEntryModal"
|
||||||
:time-entry="selectedTimeEntry as any"
|
:time-entry="selectedTimeEntry as any"
|
||||||
@@ -516,8 +556,9 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
|
|||||||
<FullCalendarDayHeader
|
<FullCalendarDayHeader
|
||||||
:date="day"
|
:date="day"
|
||||||
:is-today="isToday(day)"
|
:is-today="isToday(day)"
|
||||||
:total-seconds="
|
:total-seconds="dailyTotals[day.format('YYYY-MM-DD')] || 0"
|
||||||
dailyTotals[day.format('YYYY-MM-DD')] || 0
|
:break-seconds="
|
||||||
|
dailyBreakTotals[day.format('YYYY-MM-DD')] || 0
|
||||||
" />
|
" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -682,11 +723,19 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
|
|||||||
<PencilIcon class="w-4 h-4 text-icon-default" />
|
<PencilIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Edit</span>
|
<span>Edit</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuItem class="space-x-3" @select="handleContextDuplicate()">
|
<!-- Duplicate/Split create a new entry of the same type, which the
|
||||||
|
server rejects for breaks when breaks are disabled -->
|
||||||
|
<ContextMenuItem
|
||||||
|
v-if="contextMenuTimeEntry.type !== 'break' || breaksEnabled"
|
||||||
|
class="space-x-3"
|
||||||
|
@select="handleContextDuplicate()">
|
||||||
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
|
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Duplicate</span>
|
<span>Duplicate</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuItem class="space-x-3" @select="handleContextSplit()">
|
<ContextMenuItem
|
||||||
|
v-if="contextMenuTimeEntry.type !== 'break' || breaksEnabled"
|
||||||
|
class="space-x-3"
|
||||||
|
@select="handleContextSplit()">
|
||||||
<ScissorsIcon class="w-4 h-4 text-icon-default" />
|
<ScissorsIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Split</span>
|
<span>Split</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
@@ -716,6 +765,13 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
|
|||||||
<PlusIcon class="w-4 h-4 text-icon-default" />
|
<PlusIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Create Time Entry</span>
|
<span>Create Time Entry</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
<ContextMenuItem
|
||||||
|
v-if="breaksEnabled"
|
||||||
|
class="space-x-3"
|
||||||
|
@select="handleContextCreateBreak()">
|
||||||
|
<Coffee class="w-4 h-4 text-icon-default" />
|
||||||
|
<span>Add Break</span>
|
||||||
|
</ContextMenuItem>
|
||||||
</template>
|
</template>
|
||||||
</ContextMenuContent>
|
</ContextMenuContent>
|
||||||
</ContextMenu>
|
</ContextMenu>
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export interface CalendarEvent {
|
|||||||
client?: Client;
|
client?: Client;
|
||||||
task?: Task;
|
task?: Task;
|
||||||
isRunning: boolean;
|
isRunning: boolean;
|
||||||
|
isBreak: boolean;
|
||||||
|
isMisplacedBreak: boolean;
|
||||||
durationMinutes: number;
|
durationMinutes: number;
|
||||||
title: string;
|
title: string;
|
||||||
backgroundColor: string;
|
backgroundColor: string;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { computed, ref, type Ref, type ComputedRef } from 'vue';
|
|||||||
import chroma from 'chroma-js';
|
import chroma from 'chroma-js';
|
||||||
import type { Dayjs } from 'dayjs';
|
import type { Dayjs } from 'dayjs';
|
||||||
import type { TimeEntry, Project, Client, Task } from '@/packages/api/src';
|
import type { TimeEntry, Project, Client, Task } from '@/packages/api/src';
|
||||||
|
import { getBreakPlacementHint } from '../utils/breakPlacement';
|
||||||
import { getDayJsInstance, getLocalizedDayJs } from '../utils/time';
|
import { getDayJsInstance, getLocalizedDayJs } from '../utils/time';
|
||||||
import type { CalendarSettings } from './calendarSettings';
|
import type { CalendarSettings } from './calendarSettings';
|
||||||
import type { CalendarEvent, DayEvent } from './calendarTypes';
|
import type { CalendarEvent, DayEvent } from './calendarTypes';
|
||||||
@@ -181,7 +182,8 @@ export function useCalendarEvents(params: {
|
|||||||
|
|
||||||
const calendarEvents = computed<CalendarEvent[]>(() => {
|
const calendarEvents = computed<CalendarEvent[]>(() => {
|
||||||
const themeBackground = params.cssBackground.value?.trim();
|
const themeBackground = params.cssBackground.value?.trim();
|
||||||
return params.timeEntries().map((rawEntry) => {
|
const allEntries = params.timeEntries();
|
||||||
|
return allEntries.map((rawEntry) => {
|
||||||
const timeEntry = optimisticOverrides.value.get(rawEntry.id) || rawEntry;
|
const timeEntry = optimisticOverrides.value.get(rawEntry.id) || rawEntry;
|
||||||
const isRunning = timeEntry.end === null;
|
const isRunning = timeEntry.end === null;
|
||||||
const project = params.projects().find((p) => p.id === timeEntry.project_id);
|
const project = params.projects().find((p) => p.id === timeEntry.project_id);
|
||||||
@@ -196,9 +198,20 @@ export function useCalendarEvents(params: {
|
|||||||
'minutes'
|
'minutes'
|
||||||
);
|
);
|
||||||
|
|
||||||
const title = timeEntry.description || 'No description';
|
const isBreak = timeEntry.type === 'break';
|
||||||
const baseColor = project?.color || '#6B7280';
|
const isMisplacedBreak = isBreak
|
||||||
const backgroundColor = chroma.mix(baseColor, themeBackground, 0.65, 'lab').hex();
|
? (getBreakPlacementHint(timeEntry, allEntries)?.misplaced ?? false)
|
||||||
|
: false;
|
||||||
|
let title: string;
|
||||||
|
if (isBreak) {
|
||||||
|
title = timeEntry.description ? `Break · ${timeEntry.description}` : 'Break';
|
||||||
|
} else {
|
||||||
|
title = timeEntry.description || 'No description';
|
||||||
|
}
|
||||||
|
const baseColor = isBreak ? '#F59E0B' : project?.color || '#6B7280';
|
||||||
|
const backgroundColor = chroma
|
||||||
|
.mix(baseColor, themeBackground, isBreak ? 0.75 : 0.65, 'lab')
|
||||||
|
.hex();
|
||||||
const borderColor = chroma.mix(baseColor, themeBackground, 0.5, 'lab').hex();
|
const borderColor = chroma.mix(baseColor, themeBackground, 0.5, 'lab').hex();
|
||||||
|
|
||||||
const startTime = getLocalizedDayJs(timeEntry.start);
|
const startTime = getLocalizedDayJs(timeEntry.start);
|
||||||
@@ -215,6 +228,8 @@ export function useCalendarEvents(params: {
|
|||||||
client,
|
client,
|
||||||
task,
|
task,
|
||||||
isRunning,
|
isRunning,
|
||||||
|
isBreak,
|
||||||
|
isMisplacedBreak,
|
||||||
durationMinutes,
|
durationMinutes,
|
||||||
title,
|
title,
|
||||||
backgroundColor,
|
backgroundColor,
|
||||||
@@ -253,9 +268,12 @@ export function useCalendarEvents(params: {
|
|||||||
return result;
|
return result;
|
||||||
});
|
});
|
||||||
|
|
||||||
const dailyTotals = computed(() => {
|
function computeDailyTotals(filter: (entry: TimeEntry) => boolean): Record<string, number> {
|
||||||
const totals: Record<string, number> = {};
|
const totals: Record<string, number> = {};
|
||||||
params.timeEntries().forEach((entry) => {
|
params
|
||||||
|
.timeEntries()
|
||||||
|
.filter(filter)
|
||||||
|
.forEach((entry) => {
|
||||||
const date = getLocalizedDayJs(entry.start).format('YYYY-MM-DD');
|
const date = getLocalizedDayJs(entry.start).format('YYYY-MM-DD');
|
||||||
let durationSeconds: number;
|
let durationSeconds: number;
|
||||||
|
|
||||||
@@ -274,7 +292,13 @@ export function useCalendarEvents(params: {
|
|||||||
totals[date] = (totals[date] || 0) + durationSeconds;
|
totals[date] = (totals[date] || 0) + durationSeconds;
|
||||||
});
|
});
|
||||||
return totals;
|
return totals;
|
||||||
});
|
}
|
||||||
|
|
||||||
|
// Breaks are not working time: the day total only sums work entries,
|
||||||
|
// the break portion is exposed separately
|
||||||
|
const dailyTotals = computed(() => computeDailyTotals((entry) => entry.type !== 'break'));
|
||||||
|
|
||||||
|
const dailyBreakTotals = computed(() => computeDailyTotals((entry) => entry.type === 'break'));
|
||||||
|
|
||||||
function isToday(day: Dayjs): boolean {
|
function isToday(day: Dayjs): boolean {
|
||||||
return day.isSame(getLocalizedDayJs(), 'day');
|
return day.isSame(getLocalizedDayJs(), 'day');
|
||||||
@@ -294,6 +318,7 @@ export function useCalendarEvents(params: {
|
|||||||
calendarEvents,
|
calendarEvents,
|
||||||
eventsByDay,
|
eventsByDay,
|
||||||
dailyTotals,
|
dailyTotals,
|
||||||
|
dailyBreakTotals,
|
||||||
isToday,
|
isToday,
|
||||||
nowIndicatorTop,
|
nowIndicatorTop,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ import { getWeekStartDayNumber } from '../utils/settings';
|
|||||||
export function useCalendarNavigation(callbacks: {
|
export function useCalendarNavigation(callbacks: {
|
||||||
onDatesChange: (payload: { start: Dayjs; end: Dayjs }) => void;
|
onDatesChange: (payload: { start: Dayjs; end: Dayjs }) => void;
|
||||||
scrollToCurrentTime: () => void;
|
scrollToCurrentTime: () => void;
|
||||||
|
initialDate?: Dayjs | null;
|
||||||
}) {
|
}) {
|
||||||
const activeView = ref('timeGridWeek');
|
const activeView = ref('timeGridWeek');
|
||||||
const currentDate = ref(getLocalizedDayJs());
|
const currentDate = ref(callbacks.initialDate ?? getLocalizedDayJs());
|
||||||
|
|
||||||
function getFirstDay(): number {
|
function getFirstDay(): number {
|
||||||
return getWeekStartDayNumber();
|
return getWeekStartDayNumber();
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { computed, ref } from 'vue';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { TimeEntry } from '@/packages/api/src';
|
||||||
|
import type { CalendarEvent } from './calendarTypes';
|
||||||
|
import { useContextMenu } from './useContextMenu';
|
||||||
|
|
||||||
|
function breakEntry(): TimeEntry {
|
||||||
|
return {
|
||||||
|
id: 'break-1',
|
||||||
|
start: '2026-07-14T10:00:00Z',
|
||||||
|
end: '2026-07-14T11:00:00Z',
|
||||||
|
duration: 3600,
|
||||||
|
description: 'Lunch',
|
||||||
|
project_id: null,
|
||||||
|
task_id: null,
|
||||||
|
organization_id: 'organization-1',
|
||||||
|
user_id: 'user-1',
|
||||||
|
tags: [],
|
||||||
|
billable: false,
|
||||||
|
type: 'break',
|
||||||
|
} as TimeEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useContextMenu break actions', () => {
|
||||||
|
const createTimeEntry = vi.fn().mockResolvedValue(undefined);
|
||||||
|
const updateTimeEntry = vi.fn().mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
function contextMenu() {
|
||||||
|
const entry = breakEntry();
|
||||||
|
const calendarEvents = computed(() => [
|
||||||
|
{
|
||||||
|
id: entry.id,
|
||||||
|
timeEntry: entry,
|
||||||
|
} as CalendarEvent,
|
||||||
|
]);
|
||||||
|
const menu = useContextMenu({
|
||||||
|
calendarSettings: ref({
|
||||||
|
snapMinutes: 15,
|
||||||
|
startHour: 0,
|
||||||
|
endHour: 24,
|
||||||
|
slotMinutes: 15,
|
||||||
|
}),
|
||||||
|
calendarEvents,
|
||||||
|
pixelsToMinutesFromMidnight: () => 0,
|
||||||
|
getDayFromClientX: () => null,
|
||||||
|
clientYToGridPixels: () => 0,
|
||||||
|
createTimeEntry,
|
||||||
|
updateTimeEntry,
|
||||||
|
deleteTimeEntry: vi.fn().mockResolvedValue(undefined),
|
||||||
|
onEditEvent: vi.fn(),
|
||||||
|
onCreateEvent: vi.fn(),
|
||||||
|
onCreateBreak: vi.fn(),
|
||||||
|
emitRefresh: vi.fn(),
|
||||||
|
});
|
||||||
|
|
||||||
|
menu.handleCalendarContextMenu({
|
||||||
|
target: {
|
||||||
|
closest: () => ({
|
||||||
|
getAttribute: () => entry.id,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
} as unknown as MouseEvent);
|
||||||
|
|
||||||
|
return menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('preserves the type when duplicating a break', async () => {
|
||||||
|
await contextMenu().handleContextDuplicate();
|
||||||
|
|
||||||
|
expect(createTimeEntry).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves the type when creating the second half of a split break', async () => {
|
||||||
|
await contextMenu().handleContextSplit();
|
||||||
|
|
||||||
|
expect(updateTimeEntry).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(createTimeEntry).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ref, type Ref, type ComputedRef } from 'vue';
|
import { ref, type Ref, type ComputedRef } from 'vue';
|
||||||
import type { Dayjs } from 'dayjs';
|
import type { Dayjs } from 'dayjs';
|
||||||
import type { TimeEntry } from '@/packages/api/src';
|
import type { TimeEntry } from '@/packages/api/src';
|
||||||
import { getDayJsInstance, getLocalizedDayJsFromMinutes } from '../utils/time';
|
import { getDayJsInstance, getLocalizedDayJs, getLocalizedDayJsFromMinutes } from '../utils/time';
|
||||||
|
|
||||||
import type { CalendarSettings } from './calendarSettings';
|
import type { CalendarSettings } from './calendarSettings';
|
||||||
import type { CalendarEvent } from './calendarTypes';
|
import type { CalendarEvent } from './calendarTypes';
|
||||||
@@ -19,6 +19,7 @@ export function useContextMenu(params: {
|
|||||||
deleteTimeEntry: (id: string) => Promise<void>;
|
deleteTimeEntry: (id: string) => Promise<void>;
|
||||||
onEditEvent: (entry: TimeEntry) => void;
|
onEditEvent: (entry: TimeEntry) => void;
|
||||||
onCreateEvent: (start: Dayjs, end: Dayjs) => void;
|
onCreateEvent: (start: Dayjs, end: Dayjs) => void;
|
||||||
|
onCreateBreak: (start: Dayjs, end: Dayjs) => void;
|
||||||
emitRefresh: () => void;
|
emitRefresh: () => void;
|
||||||
}) {
|
}) {
|
||||||
const contextMenuTimeEntry = ref<TimeEntry | null>(null);
|
const contextMenuTimeEntry = ref<TimeEntry | null>(null);
|
||||||
@@ -73,6 +74,7 @@ export function useContextMenu(params: {
|
|||||||
start: entry.start,
|
start: entry.start,
|
||||||
end: entry.end,
|
end: entry.end,
|
||||||
billable: entry.billable,
|
billable: entry.billable,
|
||||||
|
type: entry.type,
|
||||||
description: entry.description,
|
description: entry.description,
|
||||||
project_id: entry.project_id,
|
project_id: entry.project_id,
|
||||||
task_id: entry.task_id,
|
task_id: entry.task_id,
|
||||||
@@ -108,6 +110,7 @@ export function useContextMenu(params: {
|
|||||||
start: midpoint.utc().format(),
|
start: midpoint.utc().format(),
|
||||||
end: entry.end,
|
end: entry.end,
|
||||||
billable: entry.billable,
|
billable: entry.billable,
|
||||||
|
type: entry.type,
|
||||||
description: entry.description,
|
description: entry.description,
|
||||||
project_id: entry.project_id,
|
project_id: entry.project_id,
|
||||||
task_id: entry.task_id,
|
task_id: entry.task_id,
|
||||||
@@ -154,6 +157,47 @@ export function useContextMenu(params: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleContextCreateBreak() {
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
if (!contextMenuCreateTime.value) {
|
||||||
|
params.onCreateBreak(dayjs().utc().subtract(30, 'minute'), dayjs().utc());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const clickTime = contextMenuCreateTime.value.start;
|
||||||
|
// Day matching must use the user's configured timezone (the calendar renders
|
||||||
|
// its day columns in that timezone), not the browser's local timezone
|
||||||
|
const clickDate = getLocalizedDayJs(clickTime.format()).format('YYYY-MM-DD');
|
||||||
|
|
||||||
|
// When the click lands in a gap between two entries of the same day,
|
||||||
|
// the break is prefilled to exactly fill that gap
|
||||||
|
let previousEnd: Dayjs | null = null;
|
||||||
|
let nextStart: Dayjs | null = null;
|
||||||
|
for (const calendarEvent of params.calendarEvents.value) {
|
||||||
|
const entry = calendarEvent.timeEntry;
|
||||||
|
const entryStart = dayjs.utc(entry.start);
|
||||||
|
if (getLocalizedDayJs(entry.start).format('YYYY-MM-DD') !== clickDate) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const entryEnd = entry.end === null ? null : dayjs.utc(entry.end);
|
||||||
|
if (entryEnd !== null && !entryEnd.isAfter(clickTime)) {
|
||||||
|
if (previousEnd === null || entryEnd.isAfter(previousEnd)) {
|
||||||
|
previousEnd = entryEnd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!entryStart.isBefore(clickTime)) {
|
||||||
|
if (nextStart === null || entryStart.isBefore(nextStart)) {
|
||||||
|
nextStart = entryStart;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previousEnd !== null && nextStart !== null && previousEnd.isBefore(nextStart)) {
|
||||||
|
params.onCreateBreak(previousEnd, nextStart);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
params.onCreateBreak(contextMenuCreateTime.value.start, contextMenuCreateTime.value.end);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
contextMenuTimeEntry,
|
contextMenuTimeEntry,
|
||||||
contextMenuCreateTime,
|
contextMenuCreateTime,
|
||||||
@@ -165,5 +209,6 @@ export function useContextMenu(params: {
|
|||||||
handleContextStop,
|
handleContextStop,
|
||||||
handleContextDiscard,
|
handleContextDiscard,
|
||||||
handleContextCreate,
|
handleContextCreate,
|
||||||
|
handleContextCreateBreak,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
121
resources/js/packages/ui/src/TimeEntry/BreakCreateModal.vue
Normal file
121
resources/js/packages/ui/src/TimeEntry/BreakCreateModal.vue
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
||||||
|
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||||
|
import DialogModal from '@/packages/ui/src/DialogModal.vue';
|
||||||
|
import { computed, ref, watch } from 'vue';
|
||||||
|
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
|
import { Field, FieldLabel } from '../field';
|
||||||
|
import { getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
||||||
|
import type { CreateTimeEntryBody } from '@/packages/api/src';
|
||||||
|
import TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
|
|
||||||
|
const show = defineModel('show', { default: false });
|
||||||
|
const saving = ref(false);
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
createTimeEntry: (entry: Omit<CreateTimeEntryBody, 'member_id'>) => Promise<void>;
|
||||||
|
start?: string;
|
||||||
|
end?: string;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
function defaultStart() {
|
||||||
|
return getDayJsInstance().utc().subtract(30, 'm').second(0).format();
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultEnd() {
|
||||||
|
return getDayJsInstance().utc().second(0).format();
|
||||||
|
}
|
||||||
|
|
||||||
|
const note = ref('');
|
||||||
|
const localStart = ref(getLocalizedDayJs(defaultStart()).format());
|
||||||
|
const localEnd = ref(getLocalizedDayJs(defaultEnd()).format());
|
||||||
|
|
||||||
|
// Prefill start/end when the modal is opened with a given range (e.g. from the calendar)
|
||||||
|
watch(
|
||||||
|
() => props.start,
|
||||||
|
(value) => {
|
||||||
|
if (value) {
|
||||||
|
localStart.value = getLocalizedDayJs(value).format();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
watch(
|
||||||
|
() => props.end,
|
||||||
|
(value) => {
|
||||||
|
if (value) {
|
||||||
|
localEnd.value = getLocalizedDayJs(value).format();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const durationSeconds = computed(() =>
|
||||||
|
getLocalizedDayJs(localEnd.value).diff(getLocalizedDayJs(localStart.value), 'second')
|
||||||
|
);
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
if (durationSeconds.value <= 0) return;
|
||||||
|
saving.value = true;
|
||||||
|
try {
|
||||||
|
await props.createTimeEntry({
|
||||||
|
description: note.value,
|
||||||
|
project_id: null,
|
||||||
|
task_id: null,
|
||||||
|
tags: [],
|
||||||
|
billable: false,
|
||||||
|
type: 'break',
|
||||||
|
start: getLocalizedDayJs(localStart.value).utc().format(),
|
||||||
|
end: getLocalizedDayJs(localEnd.value).utc().format(),
|
||||||
|
});
|
||||||
|
note.value = '';
|
||||||
|
localStart.value = getLocalizedDayJs(defaultStart()).format();
|
||||||
|
localEnd.value = getLocalizedDayJs(defaultEnd()).format();
|
||||||
|
show.value = false;
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<DialogModal closeable :show="show" @close="show = false">
|
||||||
|
<template #title>
|
||||||
|
<div class="flex items-center space-x-2 text-amber-600 dark:text-amber-400">
|
||||||
|
<Coffee class="w-5 h-5" />
|
||||||
|
<span> Add break </span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #content>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<TimeRangeFields
|
||||||
|
v-model:start="localStart"
|
||||||
|
v-model:end="localEnd"
|
||||||
|
date-picker-size="sm"></TimeRangeFields>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel for="break_note">Note (optional)</FieldLabel>
|
||||||
|
<TextInput
|
||||||
|
id="break_note"
|
||||||
|
v-model="note"
|
||||||
|
placeholder="e.g. Lunch"
|
||||||
|
type="text"
|
||||||
|
class="block w-full"
|
||||||
|
@keydown.enter="submit" />
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>
|
||||||
|
<PrimaryButton
|
||||||
|
tabindex="2"
|
||||||
|
class="ms-3"
|
||||||
|
:class="{ 'opacity-25': saving }"
|
||||||
|
:disabled="saving || durationSeconds <= 0"
|
||||||
|
@click="submit">
|
||||||
|
Add Break
|
||||||
|
</PrimaryButton>
|
||||||
|
</template>
|
||||||
|
</DialogModal>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
||||||
14
resources/js/packages/ui/src/TimeEntry/BreakLabel.vue
Normal file
14
resources/js/packages/ui/src/TimeEntry/BreakLabel.vue
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-testid="break_badge"
|
||||||
|
class="flex items-center space-x-1.5 text-sm font-medium text-text-secondary">
|
||||||
|
<Coffee class="w-4 h-4 text-text-tertiary" />
|
||||||
|
<span>Break</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped></style>
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ExclamationTriangleIcon, ArrowRightIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/packages/ui/src';
|
||||||
|
|
||||||
|
// Warning affordance for a misplaced break: an amber triangle that opens a small
|
||||||
|
// popover offering to jump to the break's day in the calendar. Rendered by the
|
||||||
|
// caller only when the break is actually misplaced (see `showPlacementHint`).
|
||||||
|
defineProps<{
|
||||||
|
// Local day (YYYY-MM-DD) the calendar should navigate to.
|
||||||
|
fixDate: string;
|
||||||
|
// Delegated navigation — packages/ui stays router-agnostic.
|
||||||
|
fixInCalendar?: (date: string) => void;
|
||||||
|
}>();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger as-child>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-testid="break_placement_hint"
|
||||||
|
title="This break does not align with your work entries"
|
||||||
|
class="flex items-center justify-center shrink-0 rounded-full p-0.5 text-amber-500 hover:bg-amber-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||||
|
<ExclamationTriangleIcon class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent class="min-w-[260px]" align="start">
|
||||||
|
<div class="px-3 py-2 space-y-1.5">
|
||||||
|
<p class="text-xs text-text-secondary">
|
||||||
|
This break is not directly between work entries.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
v-if="fixInCalendar"
|
||||||
|
type="button"
|
||||||
|
data-testid="break_fix_in_calendar"
|
||||||
|
class="inline-flex items-center gap-1 text-sm font-medium text-accent-400 hover:underline"
|
||||||
|
@click="fixInCalendar(fixDate)">
|
||||||
|
Fix in calendar
|
||||||
|
<ArrowRightIcon class="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</template>
|
||||||
@@ -16,11 +16,19 @@ import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTag
|
|||||||
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
|
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
||||||
import { ref, inject, type ComputedRef } from 'vue';
|
import { ref, inject, computed, type ComputedRef } from 'vue';
|
||||||
import { formatHumanReadableDuration, formatStartEnd } from '@/packages/ui/src/utils/time';
|
import {
|
||||||
|
formatHumanReadableDuration,
|
||||||
|
formatStartEnd,
|
||||||
|
getLocalizedDayJs,
|
||||||
|
} from '@/packages/ui/src/utils/time';
|
||||||
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
|
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
|
||||||
import GroupedItemsCountButton from '@/packages/ui/src/GroupedItemsCountButton.vue';
|
import GroupedItemsCountButton from '@/packages/ui/src/GroupedItemsCountButton.vue';
|
||||||
import type { TimeEntriesGroupedByType } from '@/types/time-entries';
|
import type { TimeEntriesGroupedByType } from '@/types/time-entries';
|
||||||
|
import {
|
||||||
|
findMisplacedBreak,
|
||||||
|
type BreakPlacementHint,
|
||||||
|
} from '@/packages/ui/src/utils/breakPlacement';
|
||||||
import {
|
import {
|
||||||
Checkbox,
|
Checkbox,
|
||||||
ContextMenu,
|
ContextMenu,
|
||||||
@@ -30,6 +38,9 @@ import {
|
|||||||
ContextMenuTrigger,
|
ContextMenuTrigger,
|
||||||
} from '@/packages/ui/src';
|
} from '@/packages/ui/src';
|
||||||
import { PlayIcon, TrashIcon } from '@heroicons/vue/20/solid';
|
import { PlayIcon, TrashIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import BreakLabel from '@/packages/ui/src/TimeEntry/BreakLabel.vue';
|
||||||
|
import BreakPlacementHintButton from '@/packages/ui/src/TimeEntry/BreakPlacementHintButton.vue';
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import { twMerge } from 'tailwind-merge';
|
import { twMerge } from 'tailwind-merge';
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
timeEntry: TimeEntriesGroupedByType;
|
timeEntry: TimeEntriesGroupedByType;
|
||||||
@@ -50,6 +61,8 @@ const props = defineProps<{
|
|||||||
selectedTimeEntries: TimeEntry[];
|
selectedTimeEntries: TimeEntry[];
|
||||||
enableEstimatedTime: boolean;
|
enableEstimatedTime: boolean;
|
||||||
canCreateProject: boolean;
|
canCreateProject: boolean;
|
||||||
|
breakPlacementHints?: Record<string, BreakPlacementHint | null>;
|
||||||
|
fixInCalendar?: (date: string) => void;
|
||||||
}>();
|
}>();
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
selected: [TimeEntry[]];
|
selected: [TimeEntry[]];
|
||||||
@@ -57,6 +70,26 @@ const emit = defineEmits<{
|
|||||||
}>();
|
}>();
|
||||||
|
|
||||||
const organization = inject<ComputedRef<Organization>>('organization');
|
const organization = inject<ComputedRef<Organization>>('organization');
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
|
// Continue creates a new entry of the same type, which the server rejects
|
||||||
|
// for breaks when breaks are disabled for the organization
|
||||||
|
const canRecreate = computed(() => props.timeEntry.type !== 'break' || breaksEnabled.value);
|
||||||
|
|
||||||
|
// Grouped breaks collapse into a single summary row, so surface the placement
|
||||||
|
// warning if any entry in the group is misplaced. All grouped entries share the
|
||||||
|
// same day, so the first misplaced one supplies the calendar navigation date.
|
||||||
|
const misplacedBreakEntry = computed<TimeEntry | null>(() =>
|
||||||
|
findMisplacedBreak(props.timeEntry.timeEntries, props.breakPlacementHints ?? {})
|
||||||
|
);
|
||||||
|
const showPlacementHint = computed(
|
||||||
|
() => props.timeEntry.type === 'break' && misplacedBreakEntry.value !== null
|
||||||
|
);
|
||||||
|
const breakFixDate = computed(() =>
|
||||||
|
misplacedBreakEntry.value
|
||||||
|
? getLocalizedDayJs(misplacedBreakEntry.value.start).format('YYYY-MM-DD')
|
||||||
|
: ''
|
||||||
|
);
|
||||||
|
|
||||||
function updateTimeEntryDescription(description: string) {
|
function updateTimeEntryDescription(description: string) {
|
||||||
props.updateTimeEntries(
|
props.updateTimeEntries(
|
||||||
@@ -121,12 +154,26 @@ function onSelectChange(checked: boolean) {
|
|||||||
{{ timeEntry?.timeEntries?.length }}
|
{{ timeEntry?.timeEntries?.length }}
|
||||||
</GroupedItemsCountButton>
|
</GroupedItemsCountButton>
|
||||||
<TimeEntryDescriptionInput
|
<TimeEntryDescriptionInput
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
class="min-w-0 mr-4 shrink"
|
class="min-w-0 mr-4 shrink"
|
||||||
:model-value="timeEntry.description"
|
:model-value="timeEntry.description"
|
||||||
@changed="
|
@changed="
|
||||||
updateTimeEntryDescription
|
updateTimeEntryDescription
|
||||||
"></TimeEntryDescriptionInput>
|
"></TimeEntryDescriptionInput>
|
||||||
|
<BreakLabel
|
||||||
|
v-if="timeEntry.type === 'break'"
|
||||||
|
class="px-2 shrink-0" />
|
||||||
|
<span
|
||||||
|
v-if="timeEntry.type === 'break' && timeEntry.description"
|
||||||
|
class="min-w-0 mr-4 shrink truncate text-sm text-text-secondary">
|
||||||
|
{{ timeEntry.description }}
|
||||||
|
</span>
|
||||||
|
<BreakPlacementHintButton
|
||||||
|
v-if="showPlacementHint"
|
||||||
|
:fix-date="breakFixDate"
|
||||||
|
:fix-in-calendar="fixInCalendar" />
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
class="min-w-0 shrink"
|
class="min-w-0 shrink"
|
||||||
:clients
|
:clients
|
||||||
:create-project
|
:create-project
|
||||||
@@ -147,11 +194,13 @@ function onSelectChange(checked: boolean) {
|
|||||||
<div
|
<div
|
||||||
class="hidden @lg:flex items-center font-medium space-x-1 @lg:space-x-2 shrink-0">
|
class="hidden @lg:flex items-center font-medium space-x-1 @lg:space-x-2 shrink-0">
|
||||||
<TimeEntryRowTagDropdown
|
<TimeEntryRowTagDropdown
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
:create-tag
|
:create-tag
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
:model-value="timeEntry.tags"
|
:model-value="timeEntry.tags"
|
||||||
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
||||||
<BillableToggleButton
|
<BillableToggleButton
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
:model-value="timeEntry.billable"
|
:model-value="timeEntry.billable"
|
||||||
size="small"
|
size="small"
|
||||||
faded
|
faded
|
||||||
@@ -189,6 +238,7 @@ function onSelectChange(checked: boolean) {
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<TimeTrackerStartStop
|
<TimeTrackerStartStop
|
||||||
|
v-if="canRecreate"
|
||||||
:active="!!(timeEntry.start && !timeEntry.end)"
|
:active="!!(timeEntry.start && !timeEntry.end)"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
class="opacity-60 flex group-hover:opacity-100 focus-visible:opacity-100"
|
class="opacity-60 flex group-hover:opacity-100 focus-visible:opacity-100"
|
||||||
@@ -231,7 +281,17 @@ function onSelectChange(checked: boolean) {
|
|||||||
</div>
|
</div>
|
||||||
<!-- Second row: project/task - tags - billable - start - more -->
|
<!-- Second row: project/task - tags - billable - start - more -->
|
||||||
<div class="flex items-center justify-between mt-1">
|
<div class="flex items-center justify-between mt-1">
|
||||||
|
<div
|
||||||
|
v-if="timeEntry.type === 'break'"
|
||||||
|
class="flex items-center min-w-0">
|
||||||
|
<BreakLabel class="px-2 min-w-0" />
|
||||||
|
<BreakPlacementHintButton
|
||||||
|
v-if="showPlacementHint"
|
||||||
|
:fix-date="breakFixDate"
|
||||||
|
:fix-in-calendar="fixInCalendar" />
|
||||||
|
</div>
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
|
v-else
|
||||||
class="min-w-0"
|
class="min-w-0"
|
||||||
:clients
|
:clients
|
||||||
:create-project
|
:create-project
|
||||||
@@ -249,16 +309,19 @@ function onSelectChange(checked: boolean) {
|
|||||||
"></TimeTrackerProjectTaskDropdown>
|
"></TimeTrackerProjectTaskDropdown>
|
||||||
<div class="flex items-center shrink-0">
|
<div class="flex items-center shrink-0">
|
||||||
<TimeEntryRowTagDropdown
|
<TimeEntryRowTagDropdown
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
:create-tag
|
:create-tag
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
:model-value="timeEntry.tags"
|
:model-value="timeEntry.tags"
|
||||||
compact
|
compact
|
||||||
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
||||||
<BillableToggleButton
|
<BillableToggleButton
|
||||||
|
v-if="timeEntry.type !== 'break'"
|
||||||
:model-value="timeEntry.billable"
|
:model-value="timeEntry.billable"
|
||||||
size="small"
|
size="small"
|
||||||
@changed="updateTimeEntryBillable"></BillableToggleButton>
|
@changed="updateTimeEntryBillable"></BillableToggleButton>
|
||||||
<TimeTrackerStartStop
|
<TimeTrackerStartStop
|
||||||
|
v-if="canRecreate"
|
||||||
:active="!!(timeEntry.start && !timeEntry.end)"
|
:active="!!(timeEntry.start && !timeEntry.end)"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
class="ml-2"
|
class="ml-2"
|
||||||
@@ -278,7 +341,7 @@ function onSelectChange(checked: boolean) {
|
|||||||
</MainContainer>
|
</MainContainer>
|
||||||
<div
|
<div
|
||||||
v-if="expanded"
|
v-if="expanded"
|
||||||
class="w-full border-t border-default-background-separator bg-black/15">
|
class="w-full border-t border-default-background-separator bg-black/5 dark:bg-black/15">
|
||||||
<TimeEntryRow
|
<TimeEntryRow
|
||||||
v-for="subEntry in timeEntry.timeEntries"
|
v-for="subEntry in timeEntry.timeEntries"
|
||||||
:key="subEntry.id"
|
:key="subEntry.id"
|
||||||
@@ -303,6 +366,8 @@ function onSelectChange(checked: boolean) {
|
|||||||
:duplicate-time-entry="() => duplicateTimeEntry(subEntry)"
|
:duplicate-time-entry="() => duplicateTimeEntry(subEntry)"
|
||||||
:currency="currency"
|
:currency="currency"
|
||||||
:create-tag
|
:create-tag
|
||||||
|
:placement-hint="breakPlacementHints?.[subEntry.id] ?? null"
|
||||||
|
:fix-in-calendar="fixInCalendar"
|
||||||
:time-entry="subEntry"
|
:time-entry="subEntry"
|
||||||
@selected="emit('selected', [subEntry])"
|
@selected="emit('selected', [subEntry])"
|
||||||
@unselected="emit('unselected', [subEntry])"></TimeEntryRow>
|
@unselected="emit('unselected', [subEntry])"></TimeEntryRow>
|
||||||
@@ -311,12 +376,13 @@ function onSelectChange(checked: boolean) {
|
|||||||
</ContextMenuTrigger>
|
</ContextMenuTrigger>
|
||||||
<ContextMenuContent class="min-w-[160px]">
|
<ContextMenuContent class="min-w-[160px]">
|
||||||
<ContextMenuItem
|
<ContextMenuItem
|
||||||
|
v-if="canRecreate"
|
||||||
class="space-x-3"
|
class="space-x-3"
|
||||||
@select="onStartStopClick(timeEntry.timeEntries[0]!)">
|
@select="onStartStopClick(timeEntry.timeEntries[0]!)">
|
||||||
<PlayIcon class="w-4 h-4 text-icon-default" />
|
<PlayIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Continue</span>
|
<span>Continue</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuSeparator />
|
<ContextMenuSeparator v-if="canRecreate" />
|
||||||
<ContextMenuItem
|
<ContextMenuItem
|
||||||
class="space-x-3 text-destructive"
|
class="space-x-3 text-destructive"
|
||||||
@select="deleteTimeEntries(timeEntry?.timeEntries ?? [])">
|
@select="deleteTimeEntries(timeEntry?.timeEntries ?? [])">
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import DialogModal from '@/packages/ui/src/DialogModal.vue';
|
|||||||
import { computed, nextTick, ref, watch } from 'vue';
|
import { computed, nextTick, ref, watch } from 'vue';
|
||||||
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
import { Field, FieldLabel } from '../field';
|
|
||||||
import { TagIcon } from '@heroicons/vue/20/solid';
|
import { TagIcon } from '@heroicons/vue/20/solid';
|
||||||
import { getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
import { getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
||||||
import type {
|
import type {
|
||||||
@@ -19,12 +18,8 @@ import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
|
|||||||
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
|
||||||
import { Button } from '@/packages/ui/src/Buttons';
|
import { Button } from '@/packages/ui/src/Buttons';
|
||||||
import DatePicker from '@/packages/ui/src/Input/DatePicker.vue';
|
import TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
|
||||||
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
|
|
||||||
|
|
||||||
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
|
|
||||||
import type { Tag, Task } from '@/packages/api/src';
|
import type { Tag, Task } from '@/packages/api/src';
|
||||||
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
|
|
||||||
|
|
||||||
const show = defineModel('show', { default: false });
|
const show = defineModel('show', { default: false });
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
@@ -62,6 +57,7 @@ const timeEntryDefaultValues = {
|
|||||||
task_id: null,
|
task_id: null,
|
||||||
tags: [],
|
tags: [],
|
||||||
billable: false,
|
billable: false,
|
||||||
|
type: 'work' as CreateTimeEntryBody['type'],
|
||||||
start: getDayJsInstance().utc().subtract(1, 'h').second(0).format(),
|
start: getDayJsInstance().utc().subtract(1, 'h').second(0).format(),
|
||||||
end: getDayJsInstance().utc().second(0).format(),
|
end: getDayJsInstance().utc().second(0).format(),
|
||||||
};
|
};
|
||||||
@@ -107,9 +103,6 @@ const localEnd = ref(getLocalizedDayJs(timeEntryDefaultValues.end).format());
|
|||||||
|
|
||||||
watch(localStart, (value) => {
|
watch(localStart, (value) => {
|
||||||
timeEntry.value.start = getLocalizedDayJs(value).utc().format();
|
timeEntry.value.start = getLocalizedDayJs(value).utc().format();
|
||||||
if (getLocalizedDayJs(localEnd.value).isBefore(getLocalizedDayJs(value))) {
|
|
||||||
localEnd.value = value;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
watch(localEnd, (value) => {
|
watch(localEnd, (value) => {
|
||||||
@@ -202,39 +195,11 @@ const billableProxy = computed({
|
|||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-2 sm:grid-cols-5 gap-4 pt-4">
|
<TimeRangeFields
|
||||||
<Field class="col-span-2 sm:col-span-3">
|
|
||||||
<FieldLabel>Duration</FieldLabel>
|
|
||||||
<div class="space-y-2 flex flex-col">
|
|
||||||
<DurationHumanInput
|
|
||||||
v-model:start="localStart"
|
v-model:start="localStart"
|
||||||
v-model:end="localEnd"
|
v-model:end="localEnd"
|
||||||
name="Duration"></DurationHumanInput>
|
show-hint
|
||||||
<div class="text-sm flex space-x-1">
|
class="pt-4"></TimeRangeFields>
|
||||||
<InformationCircleIcon
|
|
||||||
class="w-4 shrink-0 text-text-quaternary"></InformationCircleIcon>
|
|
||||||
<span class="text-text-secondary text-xs">
|
|
||||||
You can type natural language like
|
|
||||||
<span class="font-semibold"> 2h 30m</span>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>Start</FieldLabel>
|
|
||||||
<div class="flex flex-col gap-2">
|
|
||||||
<TimePickerSimple v-model="localStart" class="w-full"></TimePickerSimple>
|
|
||||||
<DatePicker v-model="localStart" class="w-full" tabindex="1"></DatePicker>
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel>End</FieldLabel>
|
|
||||||
<div class="flex flex-col gap-2">
|
|
||||||
<TimePickerSimple v-model="localEnd" class="w-full"></TimePickerSimple>
|
|
||||||
<DatePicker v-model="localEnd" class="w-full" tabindex="1"></DatePicker>
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>
|
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>
|
||||||
|
|||||||
@@ -23,8 +23,14 @@ import DatePicker from '@/packages/ui/src/Input/DatePicker.vue';
|
|||||||
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
|
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
|
||||||
|
|
||||||
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
|
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
import type { Tag, Task } from '@/packages/api/src';
|
import type { Tag, Task } from '@/packages/api/src';
|
||||||
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
|
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
|
|
||||||
|
// Breaks may have been disabled after this entry was created, so an existing break can still be
|
||||||
|
// edited (and converted back), but a work entry may only offer the break option when enabled.
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
const show = defineModel('show', { default: false });
|
const show = defineModel('show', { default: false });
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
@@ -137,6 +143,24 @@ const billableProxy = computed({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isBreak = computed(() => editableTimeEntry.value?.type === 'break');
|
||||||
|
|
||||||
|
const typeProxy = computed({
|
||||||
|
get: () => editableTimeEntry.value?.type ?? 'work',
|
||||||
|
set: (value: string) => {
|
||||||
|
if (editableTimeEntry.value) {
|
||||||
|
editableTimeEntry.value.type = value as TimeEntry['type'];
|
||||||
|
if (value === 'break') {
|
||||||
|
// Breaks can not be billable, have tags or belong to a project/task
|
||||||
|
editableTimeEntry.value.project_id = null;
|
||||||
|
editableTimeEntry.value.task_id = null;
|
||||||
|
editableTimeEntry.value.billable = false;
|
||||||
|
editableTimeEntry.value.tags = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -162,7 +186,7 @@ const billableProxy = computed({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col sm:flex-row sm:items-end gap-2">
|
<div class="flex flex-col sm:flex-row sm:items-end gap-2">
|
||||||
<div class="flex-1 min-w-0">
|
<div v-if="!isBreak" class="flex-1 min-w-0">
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
v-model:project="editableTimeEntry.project_id"
|
v-model:project="editableTimeEntry.project_id"
|
||||||
v-model:task="editableTimeEntry.task_id"
|
v-model:task="editableTimeEntry.task_id"
|
||||||
@@ -178,8 +202,24 @@ const billableProxy = computed({
|
|||||||
:tasks="tasks"
|
:tasks="tasks"
|
||||||
:enable-estimated-time="enableEstimatedTime" />
|
:enable-estimated-time="enableEstimatedTime" />
|
||||||
</div>
|
</div>
|
||||||
|
<div v-else class="flex-1 min-w-0"></div>
|
||||||
<div class="flex items-center gap-2 shrink-0">
|
<div class="flex items-center gap-2 shrink-0">
|
||||||
|
<Select v-if="breaksEnabled || isBreak" v-model="typeProxy">
|
||||||
|
<SelectTrigger :show-chevron="false">
|
||||||
|
<SelectValue class="flex items-center gap-2">
|
||||||
|
<Coffee
|
||||||
|
class="h-4 w-4"
|
||||||
|
:class="isBreak ? 'text-amber-500' : 'text-icon-default'" />
|
||||||
|
<span>{{ isBreak ? 'Break' : 'Work time' }}</span>
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="work">Work time</SelectItem>
|
||||||
|
<SelectItem value="break">Break</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
<TagDropdown
|
<TagDropdown
|
||||||
|
v-if="!isBreak"
|
||||||
v-model="editableTimeEntry.tags"
|
v-model="editableTimeEntry.tags"
|
||||||
:create-tag
|
:create-tag
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
@@ -195,7 +235,7 @@ const billableProxy = computed({
|
|||||||
</Button>
|
</Button>
|
||||||
</template>
|
</template>
|
||||||
</TagDropdown>
|
</TagDropdown>
|
||||||
<Select v-model="billableProxy">
|
<Select v-if="!isBreak" v-model="billableProxy">
|
||||||
<SelectTrigger :show-chevron="false">
|
<SelectTrigger :show-chevron="false">
|
||||||
<SelectValue class="flex items-center gap-2">
|
<SelectValue class="flex items-center gap-2">
|
||||||
<BillableIcon class="h-4 text-icon-default" />
|
<BillableIcon class="h-4 text-icon-default" />
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ import type {
|
|||||||
Client,
|
Client,
|
||||||
} from '@/packages/api/src';
|
} from '@/packages/api/src';
|
||||||
import { getDayJsInstance, getLocalizedDateFromTimestamp } from '@/packages/ui/src/utils/time';
|
import { getDayJsInstance, getLocalizedDateFromTimestamp } from '@/packages/ui/src/utils/time';
|
||||||
|
import {
|
||||||
|
getBreakPlacementHint,
|
||||||
|
type BreakPlacementHint,
|
||||||
|
} from '@/packages/ui/src/utils/breakPlacement';
|
||||||
import TimeEntryAggregateRow from '@/packages/ui/src/TimeEntry/TimeEntryAggregateRow.vue';
|
import TimeEntryAggregateRow from '@/packages/ui/src/TimeEntry/TimeEntryAggregateRow.vue';
|
||||||
import TimeEntryRowHeading from '@/packages/ui/src/TimeEntry/TimeEntryRowHeading.vue';
|
import TimeEntryRowHeading from '@/packages/ui/src/TimeEntry/TimeEntryRowHeading.vue';
|
||||||
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
|
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
|
||||||
@@ -39,12 +43,24 @@ const props = withDefaults(
|
|||||||
enableEstimatedTime: boolean;
|
enableEstimatedTime: boolean;
|
||||||
canCreateProject: boolean;
|
canCreateProject: boolean;
|
||||||
groupSimilarTimeEntries?: boolean;
|
groupSimilarTimeEntries?: boolean;
|
||||||
|
// Host-provided navigation to the calendar for a break's day (YYYY-MM-DD)
|
||||||
|
fixInCalendar?: (date: string) => void;
|
||||||
}>(),
|
}>(),
|
||||||
{
|
{
|
||||||
groupSimilarTimeEntries: true,
|
groupSimilarTimeEntries: true,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const breakPlacementHints = computed<Record<string, BreakPlacementHint | null>>(() => {
|
||||||
|
const hints: Record<string, BreakPlacementHint | null> = {};
|
||||||
|
for (const entry of props.timeEntries) {
|
||||||
|
if (entry.type === 'break') {
|
||||||
|
hints[entry.id] = getBreakPlacementHint(entry, props.timeEntries);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hints;
|
||||||
|
});
|
||||||
|
|
||||||
const groupedTimeEntries = computed(() => {
|
const groupedTimeEntries = computed(() => {
|
||||||
const groupedEntriesByDay: Record<string, TimeEntry[]> = {};
|
const groupedEntriesByDay: Record<string, TimeEntry[]> = {};
|
||||||
for (const entry of props.timeEntries) {
|
for (const entry of props.timeEntries) {
|
||||||
@@ -75,6 +91,7 @@ const groupedTimeEntries = computed(() => {
|
|||||||
e.project_id === entry.project_id &&
|
e.project_id === entry.project_id &&
|
||||||
e.task_id === entry.task_id &&
|
e.task_id === entry.task_id &&
|
||||||
e.billable === entry.billable &&
|
e.billable === entry.billable &&
|
||||||
|
e.type === entry.type &&
|
||||||
e.description === entry.description
|
e.description === entry.description
|
||||||
);
|
);
|
||||||
if (oldEntriesIndex !== -1 && newDailyEntries[oldEntriesIndex]) {
|
if (oldEntriesIndex !== -1 && newDailyEntries[oldEntriesIndex]) {
|
||||||
@@ -113,13 +130,24 @@ function startTimeEntryFromExisting(entry: TimeEntry) {
|
|||||||
start: getDayJsInstance().utc().format(),
|
start: getDayJsInstance().utc().format(),
|
||||||
end: null,
|
end: null,
|
||||||
billable: entry.billable,
|
billable: entry.billable,
|
||||||
|
type: entry.type,
|
||||||
description: entry.description,
|
description: entry.description,
|
||||||
tags: [...entry.tags],
|
tags: [...entry.tags],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function sumDuration(timeEntries: TimeEntry[]) {
|
function sumDuration(timeEntries: TimeEntry[]) {
|
||||||
return timeEntries.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
|
// Breaks are not working time: the day total only sums work entries,
|
||||||
|
// the break portion is shown separately in the heading
|
||||||
|
return timeEntries
|
||||||
|
.filter((entry) => entry.type !== 'break')
|
||||||
|
.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sumBreakDuration(timeEntries: TimeEntry[]) {
|
||||||
|
return timeEntries
|
||||||
|
.filter((entry) => entry.type === 'break')
|
||||||
|
.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
|
||||||
}
|
}
|
||||||
function selectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
|
function selectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
|
||||||
for (const timeEntry of value) {
|
for (const timeEntry of value) {
|
||||||
@@ -151,6 +179,7 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
|
|||||||
<TimeEntryRowHeading
|
<TimeEntryRowHeading
|
||||||
:date="String(key)"
|
:date="String(key)"
|
||||||
:duration="sumDuration(value)"
|
:duration="sumDuration(value)"
|
||||||
|
:break-duration="sumBreakDuration(value)"
|
||||||
:checked="
|
:checked="
|
||||||
value.every((timeEntry: TimeEntry) => selectedTimeEntries.includes(timeEntry))
|
value.every((timeEntry: TimeEntry) => selectedTimeEntries.includes(timeEntry))
|
||||||
"
|
"
|
||||||
@@ -176,6 +205,8 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
|
|||||||
:create-tag
|
:create-tag
|
||||||
:currency="currency"
|
:currency="currency"
|
||||||
:organization-billable-rate="organizationBillableRate"
|
:organization-billable-rate="organizationBillableRate"
|
||||||
|
:break-placement-hints="breakPlacementHints"
|
||||||
|
:fix-in-calendar="fixInCalendar"
|
||||||
:time-entry="entry"
|
:time-entry="entry"
|
||||||
@selected="
|
@selected="
|
||||||
(timeEntries: TimeEntry[]) => {
|
(timeEntries: TimeEntry[]) => {
|
||||||
@@ -213,6 +244,9 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
|
|||||||
:on-start-stop-click="() => startTimeEntryFromExisting(entry)"
|
:on-start-stop-click="() => startTimeEntryFromExisting(entry)"
|
||||||
:delete-time-entry="() => deleteTimeEntries([entry])"
|
:delete-time-entry="() => deleteTimeEntries([entry])"
|
||||||
:duplicate-time-entry="() => createTimeEntry(entry)"
|
:duplicate-time-entry="() => createTimeEntry(entry)"
|
||||||
|
:create-time-entry="createTimeEntry"
|
||||||
|
:placement-hint="breakPlacementHints[entry.timeEntries[0]!.id] ?? null"
|
||||||
|
:fix-in-calendar="fixInCalendar"
|
||||||
:currency="currency"
|
:currency="currency"
|
||||||
:time-entry="entry.timeEntries[0]!"
|
:time-entry="entry.timeEntries[0]!"
|
||||||
@selected="selectedTimeEntries.push(entry)"
|
@selected="selectedTimeEntries.push(entry)"
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
type UpdateMultipleTimeEntriesChangeset,
|
type UpdateMultipleTimeEntriesChangeset,
|
||||||
} from '@/packages/api/src';
|
} from '@/packages/api/src';
|
||||||
import { Checkbox } from '@/packages/ui/src';
|
import { Checkbox } from '@/packages/ui/src';
|
||||||
import { TagIcon } from '@heroicons/vue/20/solid';
|
import { TagIcon, ExclamationTriangleIcon } from '@heroicons/vue/20/solid';
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
|
||||||
import { Button } from '@/packages/ui/src/Buttons';
|
import { Button } from '@/packages/ui/src/Buttons';
|
||||||
import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
|
import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
|
||||||
@@ -129,6 +129,21 @@ watch(removeAllTags, () => {
|
|||||||
selectedTags.value = [];
|
selectedTags.value = [];
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const selectedBreaksCount = computed(
|
||||||
|
() => props.timeEntries.filter((entry) => entry.type === 'break').length
|
||||||
|
);
|
||||||
|
|
||||||
|
// Mirrors the server-side skip in TimeEntryController::updateMultiple: a break
|
||||||
|
// entry is skipped entirely when the changeset assigns a project, makes it
|
||||||
|
// billable, or adds tags (clearing tags via removeAllTags is fine).
|
||||||
|
const showBreakWarning = computed(
|
||||||
|
() =>
|
||||||
|
selectedBreaksCount.value > 0 &&
|
||||||
|
((projectId.value !== null && projectId.value !== '') ||
|
||||||
|
billable.value === true ||
|
||||||
|
selectedTags.value.length > 0)
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -141,6 +156,20 @@ watch(removeAllTags, () => {
|
|||||||
|
|
||||||
<template #content>
|
<template #content>
|
||||||
<div class="space-y-4">
|
<div class="space-y-4">
|
||||||
|
<div
|
||||||
|
v-if="showBreakWarning"
|
||||||
|
data-testid="mass_update_break_warning"
|
||||||
|
class="flex items-start space-x-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-600 dark:text-amber-400">
|
||||||
|
<ExclamationTriangleIcon class="w-4 h-4 mt-0.5 shrink-0" />
|
||||||
|
<span>
|
||||||
|
{{ selectedBreaksCount }}
|
||||||
|
{{ selectedBreaksCount === 1 ? 'break is' : 'breaks are' }} selected —
|
||||||
|
breaks can not have a project or tags, or be billable, so
|
||||||
|
{{ selectedBreaksCount === 1 ? 'this entry' : 'these entries' }} will be
|
||||||
|
skipped entirely and none of the changes (including the description) will be
|
||||||
|
applied to {{ selectedBreaksCount === 1 ? 'it' : 'them' }}.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel for="description">Description</FieldLabel>
|
<FieldLabel for="description">Description</FieldLabel>
|
||||||
<TextInput
|
<TextInput
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import TimeEntryRowDurationInput from '@/packages/ui/src/TimeEntry/TimeEntryRowD
|
|||||||
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
|
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
|
||||||
import { TimeEntryEditModal } from '@/packages/ui/src';
|
import { TimeEntryEditModal } from '@/packages/ui/src';
|
||||||
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
||||||
|
import { getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
||||||
|
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
import {
|
import {
|
||||||
@@ -29,6 +31,10 @@ import {
|
|||||||
ContextMenuTrigger,
|
ContextMenuTrigger,
|
||||||
} from '@/packages/ui/src';
|
} from '@/packages/ui/src';
|
||||||
import { PlayIcon, PencilIcon, DocumentDuplicateIcon, TrashIcon } from '@heroicons/vue/20/solid';
|
import { PlayIcon, PencilIcon, DocumentDuplicateIcon, TrashIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import BreakLabel from '@/packages/ui/src/TimeEntry/BreakLabel.vue';
|
||||||
|
import BreakPlacementHintButton from '@/packages/ui/src/TimeEntry/BreakPlacementHintButton.vue';
|
||||||
|
import type { BreakPlacementHint } from '@/packages/ui/src/utils/breakPlacement';
|
||||||
|
import type { CreateTimeEntryBody } from '@/packages/api/src';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
timeEntry: TimeEntry;
|
timeEntry: TimeEntry;
|
||||||
@@ -45,6 +51,9 @@ const props = defineProps<{
|
|||||||
deleteTimeEntry: () => void;
|
deleteTimeEntry: () => void;
|
||||||
duplicateTimeEntry?: () => void;
|
duplicateTimeEntry?: () => void;
|
||||||
updateTimeEntry: (timeEntry: TimeEntry) => void;
|
updateTimeEntry: (timeEntry: TimeEntry) => void;
|
||||||
|
createTimeEntry?: (entry: Omit<CreateTimeEntryBody, 'member_id'>) => void;
|
||||||
|
placementHint?: BreakPlacementHint | null;
|
||||||
|
fixInCalendar?: (date: string) => void;
|
||||||
currency: string;
|
currency: string;
|
||||||
organizationBillableRate: number | null;
|
organizationBillableRate: number | null;
|
||||||
showMember?: boolean;
|
showMember?: boolean;
|
||||||
@@ -59,6 +68,20 @@ const emit = defineEmits<{ selected: []; unselected: [] }>();
|
|||||||
|
|
||||||
const showEditModal = ref(false);
|
const showEditModal = ref(false);
|
||||||
|
|
||||||
|
const breaksEnabled = useBreaksEnabled();
|
||||||
|
|
||||||
|
const isBreak = computed(() => props.timeEntry.type === 'break');
|
||||||
|
|
||||||
|
// Continue/Duplicate create a new entry of the same type, which the server
|
||||||
|
// rejects for breaks when breaks are disabled for the organization
|
||||||
|
const canRecreate = computed(() => !isBreak.value || breaksEnabled.value);
|
||||||
|
|
||||||
|
const showPlacementHint = computed(
|
||||||
|
() => isBreak.value && props.placementHint != null && props.placementHint.misplaced
|
||||||
|
);
|
||||||
|
|
||||||
|
const breakFixDate = computed(() => getLocalizedDayJs(props.timeEntry.start).format('YYYY-MM-DD'));
|
||||||
|
|
||||||
function updateTimeEntryDescription(description: string) {
|
function updateTimeEntryDescription(description: string) {
|
||||||
props.updateTimeEntry({ ...props.timeEntry, description });
|
props.updateTimeEntry({ ...props.timeEntry, description });
|
||||||
}
|
}
|
||||||
@@ -131,10 +154,22 @@ async function handleDeleteTimeEntry() {
|
|||||||
<Checkbox :checked="selected" @update:checked="onSelectChange" />
|
<Checkbox :checked="selected" @update:checked="onSelectChange" />
|
||||||
<div v-if="indent === true" class="w-10 h-7"></div>
|
<div v-if="indent === true" class="w-10 h-7"></div>
|
||||||
<TimeEntryDescriptionInput
|
<TimeEntryDescriptionInput
|
||||||
|
v-if="!isBreak"
|
||||||
class="min-w-0 mr-4 shrink"
|
class="min-w-0 mr-4 shrink"
|
||||||
:model-value="timeEntry.description"
|
:model-value="timeEntry.description"
|
||||||
@changed="updateTimeEntryDescription"></TimeEntryDescriptionInput>
|
@changed="updateTimeEntryDescription"></TimeEntryDescriptionInput>
|
||||||
|
<BreakLabel v-if="isBreak" class="pl-1.5 @lg:pl-3 pr-2 shrink-0" />
|
||||||
|
<span
|
||||||
|
v-if="isBreak && timeEntry.description"
|
||||||
|
class="min-w-0 mr-4 shrink truncate text-sm text-text-secondary">
|
||||||
|
{{ timeEntry.description }}
|
||||||
|
</span>
|
||||||
|
<BreakPlacementHintButton
|
||||||
|
v-if="showPlacementHint"
|
||||||
|
:fix-date="breakFixDate"
|
||||||
|
:fix-in-calendar="fixInCalendar" />
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
|
v-if="!isBreak"
|
||||||
class="min-w-0 shrink"
|
class="min-w-0 shrink"
|
||||||
:create-project
|
:create-project
|
||||||
:create-client
|
:create-client
|
||||||
@@ -154,11 +189,13 @@ async function handleDeleteTimeEntry() {
|
|||||||
{{ memberName }}
|
{{ memberName }}
|
||||||
</div>
|
</div>
|
||||||
<TimeEntryRowTagDropdown
|
<TimeEntryRowTagDropdown
|
||||||
|
v-if="!isBreak"
|
||||||
:create-tag
|
:create-tag
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
:model-value="timeEntry.tags"
|
:model-value="timeEntry.tags"
|
||||||
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
||||||
<BillableToggleButton
|
<BillableToggleButton
|
||||||
|
v-if="!isBreak"
|
||||||
:model-value="timeEntry.billable"
|
:model-value="timeEntry.billable"
|
||||||
size="small"
|
size="small"
|
||||||
faded
|
faded
|
||||||
@@ -176,11 +213,13 @@ async function handleDeleteTimeEntry() {
|
|||||||
:is-report="props.isReport"
|
:is-report="props.isReport"
|
||||||
@changed="updateStartEndTime"></TimeEntryRowDurationInput>
|
@changed="updateStartEndTime"></TimeEntryRowDurationInput>
|
||||||
<TimeTrackerStartStop
|
<TimeTrackerStartStop
|
||||||
|
v-if="canRecreate"
|
||||||
:active="!!(timeEntry.start && !timeEntry.end)"
|
:active="!!(timeEntry.start && !timeEntry.end)"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
class="opacity-60 flex focus-visible:opacity-100 group-hover:opacity-100"
|
class="opacity-60 flex focus-visible:opacity-100 group-hover:opacity-100"
|
||||||
@changed="onStartStopClick"></TimeTrackerStartStop>
|
@changed="onStartStopClick"></TimeTrackerStartStop>
|
||||||
<TimeEntryMoreOptionsDropdown
|
<TimeEntryMoreOptionsDropdown
|
||||||
|
:show-duplicate="canRecreate"
|
||||||
@edit="handleEdit"
|
@edit="handleEdit"
|
||||||
@duplicate="duplicateTimeEntry"
|
@duplicate="duplicateTimeEntry"
|
||||||
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
|
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
|
||||||
@@ -190,11 +229,17 @@ async function handleDeleteTimeEntry() {
|
|||||||
<!-- First row: description + duration -->
|
<!-- First row: description + duration -->
|
||||||
<div class="flex items-center justify-between min-w-0">
|
<div class="flex items-center justify-between min-w-0">
|
||||||
<TimeEntryDescriptionInput
|
<TimeEntryDescriptionInput
|
||||||
|
v-if="!isBreak"
|
||||||
class="min-w-0 flex-1"
|
class="min-w-0 flex-1"
|
||||||
:model-value="timeEntry.description"
|
:model-value="timeEntry.description"
|
||||||
@changed="
|
@changed="
|
||||||
updateTimeEntryDescription
|
updateTimeEntryDescription
|
||||||
"></TimeEntryDescriptionInput>
|
"></TimeEntryDescriptionInput>
|
||||||
|
<span
|
||||||
|
v-else
|
||||||
|
class="min-w-0 flex-1 truncate text-sm text-text-secondary pl-1.5">
|
||||||
|
{{ timeEntry.description }}
|
||||||
|
</span>
|
||||||
<TimeEntryRowDurationInput
|
<TimeEntryRowDurationInput
|
||||||
:start="timeEntry.start"
|
:start="timeEntry.start"
|
||||||
:end="timeEntry.end"
|
:end="timeEntry.end"
|
||||||
@@ -203,7 +248,9 @@ async function handleDeleteTimeEntry() {
|
|||||||
</div>
|
</div>
|
||||||
<!-- Second row: project/task - tags - billable - start - more -->
|
<!-- Second row: project/task - tags - billable - start - more -->
|
||||||
<div class="flex items-center justify-between mt-1">
|
<div class="flex items-center justify-between mt-1">
|
||||||
|
<BreakLabel v-if="isBreak" class="pl-1.5 pr-2 min-w-0" />
|
||||||
<TimeTrackerProjectTaskDropdown
|
<TimeTrackerProjectTaskDropdown
|
||||||
|
v-else
|
||||||
class="min-w-0"
|
class="min-w-0"
|
||||||
:create-project
|
:create-project
|
||||||
:create-client
|
:create-client
|
||||||
@@ -221,21 +268,25 @@ async function handleDeleteTimeEntry() {
|
|||||||
"></TimeTrackerProjectTaskDropdown>
|
"></TimeTrackerProjectTaskDropdown>
|
||||||
<div class="flex items-center shrink-0">
|
<div class="flex items-center shrink-0">
|
||||||
<TimeEntryRowTagDropdown
|
<TimeEntryRowTagDropdown
|
||||||
|
v-if="!isBreak"
|
||||||
:create-tag
|
:create-tag
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
:model-value="timeEntry.tags"
|
:model-value="timeEntry.tags"
|
||||||
compact
|
compact
|
||||||
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
|
||||||
<BillableToggleButton
|
<BillableToggleButton
|
||||||
|
v-if="!isBreak"
|
||||||
:model-value="timeEntry.billable"
|
:model-value="timeEntry.billable"
|
||||||
size="small"
|
size="small"
|
||||||
@changed="updateTimeEntryBillable"></BillableToggleButton>
|
@changed="updateTimeEntryBillable"></BillableToggleButton>
|
||||||
<TimeTrackerStartStop
|
<TimeTrackerStartStop
|
||||||
|
v-if="canRecreate"
|
||||||
:active="!!(timeEntry.start && !timeEntry.end)"
|
:active="!!(timeEntry.start && !timeEntry.end)"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
class="ml-2"
|
class="ml-2"
|
||||||
@changed="onStartStopClick"></TimeTrackerStartStop>
|
@changed="onStartStopClick"></TimeTrackerStartStop>
|
||||||
<TimeEntryMoreOptionsDropdown
|
<TimeEntryMoreOptionsDropdown
|
||||||
|
:show-duplicate="canRecreate"
|
||||||
@edit="handleEdit"
|
@edit="handleEdit"
|
||||||
@duplicate="duplicateTimeEntry"
|
@duplicate="duplicateTimeEntry"
|
||||||
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
|
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
|
||||||
@@ -247,7 +298,7 @@ async function handleDeleteTimeEntry() {
|
|||||||
</div>
|
</div>
|
||||||
</ContextMenuTrigger>
|
</ContextMenuTrigger>
|
||||||
<ContextMenuContent class="min-w-[160px]">
|
<ContextMenuContent class="min-w-[160px]">
|
||||||
<ContextMenuItem class="space-x-3" @select="onStartStopClick()">
|
<ContextMenuItem v-if="canRecreate" class="space-x-3" @select="onStartStopClick()">
|
||||||
<PlayIcon class="w-4 h-4 text-icon-default" />
|
<PlayIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Continue</span>
|
<span>Continue</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
@@ -255,7 +306,7 @@ async function handleDeleteTimeEntry() {
|
|||||||
<PencilIcon class="w-4 h-4 text-icon-default" />
|
<PencilIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Edit</span>
|
<span>Edit</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
<ContextMenuItem class="space-x-3" @select="duplicateTimeEntry?.()">
|
<ContextMenuItem v-if="canRecreate" class="space-x-3" @select="duplicateTimeEntry?.()">
|
||||||
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
|
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
|
||||||
<span>Duplicate</span>
|
<span>Duplicate</span>
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
|||||||
@@ -12,11 +12,17 @@ import { CalendarIcon } from '@heroicons/vue/20/solid';
|
|||||||
|
|
||||||
const organization = inject<ComputedRef<Organization>>('organization');
|
const organization = inject<ComputedRef<Organization>>('organization');
|
||||||
|
|
||||||
|
withDefaults(
|
||||||
defineProps<{
|
defineProps<{
|
||||||
date: string;
|
date: string;
|
||||||
duration: number;
|
duration: number;
|
||||||
checked: boolean;
|
checked: boolean;
|
||||||
}>();
|
breakDuration?: number;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
breakDuration: 0,
|
||||||
|
}
|
||||||
|
);
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
selectAll: [];
|
selectAll: [];
|
||||||
unselectAll: [];
|
unselectAll: [];
|
||||||
@@ -55,6 +61,19 @@ function selectUnselectAll(value: boolean) {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-text-primary pr-2 @lg:pr-[92px]">
|
<div class="text-text-primary pr-2 @lg:pr-[92px]">
|
||||||
|
<span
|
||||||
|
v-if="breakDuration > 0"
|
||||||
|
data-testid="day_break_duration"
|
||||||
|
class="text-text-secondary font-normal mr-2">
|
||||||
|
{{
|
||||||
|
formatHumanReadableDuration(
|
||||||
|
breakDuration,
|
||||||
|
organization?.interval_format,
|
||||||
|
organization?.number_format
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
break ·
|
||||||
|
</span>
|
||||||
<span class="font-medium">
|
<span class="font-medium">
|
||||||
{{
|
{{
|
||||||
formatHumanReadableDuration(
|
formatHumanReadableDuration(
|
||||||
|
|||||||
73
resources/js/packages/ui/src/TimeEntry/TimeRangeFields.vue
Normal file
73
resources/js/packages/ui/src/TimeEntry/TimeRangeFields.vue
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { watch } from 'vue';
|
||||||
|
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import { Field, FieldLabel } from '../field';
|
||||||
|
import DatePicker from '@/packages/ui/src/Input/DatePicker.vue';
|
||||||
|
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
|
||||||
|
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
|
||||||
|
import { getLocalizedDayJs } from '@/packages/ui/src/utils/time';
|
||||||
|
|
||||||
|
// Local (user timezone) ISO strings, as produced by getLocalizedDayJs(...).format()
|
||||||
|
const start = defineModel<string>('start', { required: true });
|
||||||
|
const end = defineModel<string>('end', { required: true });
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
showHint?: boolean;
|
||||||
|
datePickerSize?: 'sm';
|
||||||
|
}>();
|
||||||
|
|
||||||
|
// Moving the start to or past the end drags the end along, preserving the
|
||||||
|
// range's previous duration, so the range never collapses or inverts.
|
||||||
|
watch(start, (value, oldValue) => {
|
||||||
|
if (getLocalizedDayJs(end.value).isAfter(getLocalizedDayJs(value))) return;
|
||||||
|
const previousDuration = Math.max(
|
||||||
|
0,
|
||||||
|
getLocalizedDayJs(end.value).diff(getLocalizedDayJs(oldValue), 'second')
|
||||||
|
);
|
||||||
|
end.value = getLocalizedDayJs(value).add(previousDuration, 'second').format();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="grid grid-cols-2 sm:grid-cols-5 gap-4">
|
||||||
|
<Field class="col-span-2 sm:col-span-3">
|
||||||
|
<FieldLabel>Duration</FieldLabel>
|
||||||
|
<div class="space-y-2 flex flex-col">
|
||||||
|
<DurationHumanInput
|
||||||
|
v-model:start="start"
|
||||||
|
v-model:end="end"
|
||||||
|
name="Duration"></DurationHumanInput>
|
||||||
|
<div v-if="showHint" class="text-sm flex space-x-1">
|
||||||
|
<InformationCircleIcon
|
||||||
|
class="w-4 shrink-0 text-text-quaternary"></InformationCircleIcon>
|
||||||
|
<span class="text-text-secondary text-xs">
|
||||||
|
You can type natural language like
|
||||||
|
<span class="font-semibold"> 2h 30m</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Start</FieldLabel>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<TimePickerSimple v-model="start" class="w-full"></TimePickerSimple>
|
||||||
|
<DatePicker
|
||||||
|
v-model="start"
|
||||||
|
:size="datePickerSize"
|
||||||
|
class="w-full"
|
||||||
|
tabindex="1"></DatePicker>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>End</FieldLabel>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<TimePickerSimple v-model="end" class="w-full"></TimePickerSimple>
|
||||||
|
<DatePicker
|
||||||
|
v-model="end"
|
||||||
|
:size="datePickerSize"
|
||||||
|
class="w-full"
|
||||||
|
tabindex="1"></DatePicker>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import TimeTrackerTagDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerTagDropdown.vue';
|
|
||||||
import TimeTrackerStartStop from '@/packages/ui/src/TimeTrackerStartStop.vue';
|
import TimeTrackerStartStop from '@/packages/ui/src/TimeTrackerStartStop.vue';
|
||||||
import TimeTrackerRangeSelector from '@/packages/ui/src/TimeTracker/TimeTrackerRangeSelector.vue';
|
import TimeTrackerRangeSelector from '@/packages/ui/src/TimeTracker/TimeTrackerRangeSelector.vue';
|
||||||
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
import TimeTrackerEntryInput from '@/packages/ui/src/TimeTracker/TimeTrackerEntryInput.vue';
|
||||||
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
import TimeTrackerProjectControls from '@/packages/ui/src/TimeTracker/TimeTrackerProjectControls.vue';
|
||||||
import type {
|
import type {
|
||||||
CreateClientBody,
|
CreateClientBody,
|
||||||
CreateProjectBody,
|
CreateProjectBody,
|
||||||
@@ -13,21 +12,18 @@ import type {
|
|||||||
TimeEntry,
|
TimeEntry,
|
||||||
Client,
|
Client,
|
||||||
} from '@/packages/api/src';
|
} from '@/packages/api/src';
|
||||||
import { computed, nextTick, ref, watch } from 'vue';
|
import { nextTick, ref, watch } from 'vue';
|
||||||
import type { Dayjs } from 'dayjs';
|
import type { Dayjs } from 'dayjs';
|
||||||
import { useFocus } from '@vueuse/core';
|
import { Coffee, Play } from '@lucide/vue';
|
||||||
import { autoUpdate, flip, limitShift, offset, shift, useFloating } from '@floating-ui/vue';
|
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
|
||||||
import TimeTrackerRecentlyTrackedEntry from '@/packages/ui/src/TimeTracker/TimeTrackerRecentlyTrackedEntry.vue';
|
|
||||||
import { useSelectEvents } from '@/packages/ui/src/utils/select';
|
|
||||||
|
|
||||||
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', {
|
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', {
|
||||||
required: true,
|
required: true,
|
||||||
});
|
});
|
||||||
const liveTimer = defineModel<Dayjs | null>('liveTimer', { required: true });
|
const liveTimer = defineModel<Dayjs | null>('liveTimer', { required: true });
|
||||||
|
|
||||||
const currentTimeEntryDescriptionInput = ref<HTMLInputElement | null>(null);
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
const props = defineProps<{
|
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
tasks: Task[];
|
tasks: Task[];
|
||||||
tags: Tag[];
|
tags: Tag[];
|
||||||
@@ -41,7 +37,20 @@ const props = defineProps<{
|
|||||||
organizationBillableRate: number | null;
|
organizationBillableRate: number | null;
|
||||||
enableEstimatedTime: boolean;
|
enableEstimatedTime: boolean;
|
||||||
canCreateProject: boolean;
|
canCreateProject: boolean;
|
||||||
}>();
|
isOnBreak?: boolean;
|
||||||
|
breaksEnabled?: boolean;
|
||||||
|
canResumeAfterBreak?: boolean;
|
||||||
|
resumeDescription?: string | null;
|
||||||
|
timeTrackerMode?: TimeTrackerMode;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
isOnBreak: false,
|
||||||
|
breaksEnabled: false,
|
||||||
|
canResumeAfterBreak: false,
|
||||||
|
resumeDescription: null,
|
||||||
|
timeTrackerMode: 'project',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
startTimer: [];
|
startTimer: [];
|
||||||
@@ -50,251 +59,136 @@ const emit = defineEmits<{
|
|||||||
startLiveTimer: [];
|
startLiveTimer: [];
|
||||||
stopLiveTimer: [];
|
stopLiveTimer: [];
|
||||||
createTimeEntry: [];
|
createTimeEntry: [];
|
||||||
|
startBreak: [];
|
||||||
|
resumeAfterBreak: [];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
function updateProject() {
|
const entryInput = ref<InstanceType<typeof TimeTrackerEntryInput> | null>(null);
|
||||||
setBillableDefaultForProject();
|
|
||||||
emit('updateTimeEntry');
|
|
||||||
}
|
|
||||||
|
|
||||||
function setAndStartTimer(timeEntry: TimeEntry) {
|
|
||||||
setCurrentTimeEntry(timeEntry);
|
|
||||||
if (!props.isActive) {
|
|
||||||
emit('startTimer');
|
|
||||||
} else {
|
|
||||||
emit('updateTimeEntry');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setCurrentTimeEntry(timeEntry: TimeEntry) {
|
|
||||||
currentTimeEntry.value.description = timeEntry.description;
|
|
||||||
currentTimeEntry.value.project_id = timeEntry.project_id;
|
|
||||||
currentTimeEntry.value.task_id = timeEntry.task_id;
|
|
||||||
currentTimeEntry.value.tags = timeEntry.tags;
|
|
||||||
currentTimeEntry.value.billable = timeEntry.billable;
|
|
||||||
}
|
|
||||||
|
|
||||||
function startTimerIfNotActive() {
|
|
||||||
if (highlightedDropdownEntryId.value) {
|
|
||||||
const timeEntry = filteredRecentlyTrackedTimeEntries.value.find(
|
|
||||||
(item) => item.id === highlightedDropdownEntryId.value
|
|
||||||
);
|
|
||||||
if (timeEntry) {
|
|
||||||
setCurrentTimeEntry(timeEntry);
|
|
||||||
showDropdown.value = false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
currentTimeEntry.value.description = tempDescription.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!props.isActive) {
|
|
||||||
emit('startTimer');
|
|
||||||
} else {
|
|
||||||
emit('updateTimeEntry');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function setBillableDefaultForProject() {
|
|
||||||
const project = props.projects.find(
|
|
||||||
(project) => project.id === currentTimeEntry.value.project_id
|
|
||||||
);
|
|
||||||
if (project) {
|
|
||||||
currentTimeEntry.value.billable = project.is_billable;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const blockRefocus = ref(false);
|
|
||||||
|
|
||||||
function onToggleButtonPress(newState: boolean) {
|
function onToggleButtonPress(newState: boolean) {
|
||||||
if (newState) {
|
if (newState) {
|
||||||
emit('startTimer');
|
emit('startTimer');
|
||||||
if (!blockRefocus.value) {
|
entryInput.value?.focusAfterStart();
|
||||||
currentTimeEntryDescriptionInput.value?.focus();
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
emit('stopTimer');
|
emit('stopTimer');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tempDescription = ref(currentTimeEntry.value.description);
|
// Pressing Enter in the range selector starts the timer, same as in the description input.
|
||||||
|
function onRangeEnter() {
|
||||||
|
entryInput.value?.submit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// After a break ends the tracker returns to the idle input; focus it so a fresh
|
||||||
|
// entry is just type + Enter.
|
||||||
watch(
|
watch(
|
||||||
() => currentTimeEntry.value.description,
|
() => props.isOnBreak,
|
||||||
() => {
|
async (isOnBreak, wasOnBreak) => {
|
||||||
tempDescription.value = currentTimeEntry.value.description;
|
if (wasOnBreak && !isOnBreak) {
|
||||||
}
|
await nextTick();
|
||||||
);
|
entryInput.value?.focusAfterStart();
|
||||||
|
|
||||||
function updateTimeEntryDescription() {
|
|
||||||
if (currentTimeEntry.value.description !== tempDescription.value) {
|
|
||||||
currentTimeEntry.value.description = tempDescription.value;
|
|
||||||
emit('updateTimeEntry');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const filteredRecentlyTrackedTimeEntries = computed(() => {
|
|
||||||
// do not include running time entries
|
|
||||||
const finishedTimeEntries = props.timeEntries.filter((item) => item.end !== null);
|
|
||||||
|
|
||||||
// filter out duplicates based on description, task, project, tags and billable
|
|
||||||
const nonDuplicateTimeEntries = finishedTimeEntries.filter((item, index, self) => {
|
|
||||||
return (
|
|
||||||
index ===
|
|
||||||
self.findIndex(
|
|
||||||
(t) =>
|
|
||||||
t.description === item.description &&
|
|
||||||
t.task_id === item.task_id &&
|
|
||||||
t.project_id === item.project_id &&
|
|
||||||
t.tags.length === item.tags.length &&
|
|
||||||
t.tags.every((tag) => item.tags.includes(tag)) &&
|
|
||||||
t.billable === item.billable
|
|
||||||
)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// filter time entries based on current description
|
|
||||||
return nonDuplicateTimeEntries
|
|
||||||
.filter((item) => {
|
|
||||||
return item.description
|
|
||||||
?.toLowerCase()
|
|
||||||
?.includes(tempDescription.value?.toLowerCase()?.trim() || '');
|
|
||||||
})
|
|
||||||
.slice(0, 5);
|
|
||||||
});
|
|
||||||
|
|
||||||
const showDropdown = ref(false);
|
|
||||||
const { focused } = useFocus(currentTimeEntryDescriptionInput);
|
|
||||||
|
|
||||||
watch(focused, (focused) => {
|
|
||||||
nextTick(() => {
|
|
||||||
// make sure the click event on the dropdown does not get interrupted
|
|
||||||
showDropdown.value = focused;
|
|
||||||
|
|
||||||
// make sure that the input does not get refocused after the dropdown is closed
|
|
||||||
if (!focused) {
|
|
||||||
blockRefocus.value = true;
|
|
||||||
setTimeout(() => {
|
|
||||||
blockRefocus.value = false;
|
|
||||||
}, 100);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const floating = ref(null);
|
|
||||||
const { floatingStyles } = useFloating(currentTimeEntryDescriptionInput, floating, {
|
|
||||||
placement: 'bottom-start',
|
|
||||||
whileElementsMounted: autoUpdate,
|
|
||||||
middleware: [
|
|
||||||
offset(10),
|
|
||||||
shift({
|
|
||||||
limiter: limitShift({
|
|
||||||
offset: 5,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
flip({
|
|
||||||
fallbackAxisSideDirection: 'start',
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
const highlightedDropdownEntryId = ref<string | null>(null);
|
|
||||||
|
|
||||||
useSelectEvents(
|
|
||||||
filteredRecentlyTrackedTimeEntries,
|
|
||||||
highlightedDropdownEntryId,
|
|
||||||
(item) => item.id,
|
|
||||||
showDropdown
|
|
||||||
);
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex items-center relative @container" data-testid="dashboard_timer">
|
<div class="flex items-center relative @container" data-testid="dashboard_timer">
|
||||||
<div
|
<div
|
||||||
class="flex flex-col @2xl:flex-row w-full justify-between rounded-lg bg-card-background border-card-border border transition shadow-card">
|
class="flex flex-col @2xl:flex-row w-full justify-between rounded-lg border transition shadow-card"
|
||||||
|
:class="
|
||||||
|
isOnBreak
|
||||||
|
? 'bg-amber-500/10 border-amber-500/30'
|
||||||
|
: 'bg-card-background border-card-border'
|
||||||
|
">
|
||||||
<div class="flex flex-1 items-center relative">
|
<div class="flex flex-1 items-center relative">
|
||||||
<input
|
<div
|
||||||
ref="currentTimeEntryDescriptionInput"
|
v-if="isOnBreak"
|
||||||
v-model="tempDescription"
|
class="flex w-full items-center gap-2 py-4 sm:py-2.5 px-3.5 @2xl:px-4 text-base font-medium text-amber-600 dark:text-amber-400">
|
||||||
placeholder="What are you working on?"
|
<Coffee class="w-5 h-5 shrink-0" />
|
||||||
data-testid="time_entry_description"
|
<span>On break</span>
|
||||||
class="w-full rounded-l-lg py-4 sm:py-2.5 px-3.5 border-b border-b-card-background-separator @2xl:px-4 text-base text-text-primary bg-transparent border-none placeholder-text-secondary focus:ring-0 transition"
|
|
||||||
type="text"
|
|
||||||
@keydown.enter="startTimerIfNotActive"
|
|
||||||
@keydown.esc="showDropdown = false"
|
|
||||||
@blur="updateTimeEntryDescription" />
|
|
||||||
<div class="@2xl:hidden pr-3 shrink-0">
|
|
||||||
<TimeTrackerStartStop
|
|
||||||
:active="isActive"
|
|
||||||
@changed="onToggleButtonPress"></TimeTrackerStartStop>
|
|
||||||
</div>
|
</div>
|
||||||
<div
|
<TimeTrackerEntryInput
|
||||||
v-if="showDropdown && filteredRecentlyTrackedTimeEntries.length > 0"
|
v-else
|
||||||
ref="floating"
|
ref="entryInput"
|
||||||
class="z-50 w-[min(640px,100vw-2rem)]"
|
v-model:current-time-entry="currentTimeEntry"
|
||||||
:style="floatingStyles">
|
:time-entries="timeEntries"
|
||||||
<div
|
|
||||||
class="rounded-lg w-full border border-card-border overflow-hidden shadow-dropdown bg-card-background">
|
|
||||||
<div
|
|
||||||
class="text-text-tertiary text-xs font-semibold border-b border-border-tertiary px-2 py-1.5">
|
|
||||||
Recently Tracked Time Entries
|
|
||||||
</div>
|
|
||||||
<div class="text-text-secondary py-1 px-1.5">
|
|
||||||
<TimeTrackerRecentlyTrackedEntry
|
|
||||||
v-for="timeEntry in filteredRecentlyTrackedTimeEntries"
|
|
||||||
:key="timeEntry.id"
|
|
||||||
:time-entry="timeEntry"
|
|
||||||
:highlighted="highlightedDropdownEntryId === timeEntry.id"
|
|
||||||
:projects="projects"
|
:projects="projects"
|
||||||
:tasks="tasks"
|
:tasks="tasks"
|
||||||
@mousedown="setAndStartTimer(timeEntry)"
|
:is-active="isActive"
|
||||||
@mouseenter="
|
@start-timer="emit('startTimer')"
|
||||||
highlightedDropdownEntryId = timeEntry.id
|
@update-time-entry="emit('updateTimeEntry')"></TimeTrackerEntryInput>
|
||||||
"></TimeTrackerRecentlyTrackedEntry>
|
<div class="@2xl:hidden pr-3 shrink-0 flex items-center space-x-2">
|
||||||
</div>
|
<button
|
||||||
</div>
|
v-if="breaksEnabled && !isOnBreak && isActive"
|
||||||
|
type="button"
|
||||||
|
title="Take a break"
|
||||||
|
aria-label="Take a break"
|
||||||
|
class="flex items-center justify-center w-8 h-8 rounded-full bg-quaternary text-text-tertiary hover:text-amber-500 focus:ring-2 focus:ring-border-tertiary transition"
|
||||||
|
@click="emit('startBreak')">
|
||||||
|
<Coffee class="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<TimeTrackerStartStop
|
||||||
|
:active="isActive"
|
||||||
|
:variant="isOnBreak ? 'break' : 'primary'"
|
||||||
|
@changed="onToggleButtonPress"></TimeTrackerStartStop>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center justify-between pl-2 shrink min-w-0">
|
<div class="flex items-center justify-between pl-2 shrink min-w-0">
|
||||||
<div class="flex items-center w-[130px] @2xl:w-auto shrink min-w-0">
|
<TimeTrackerProjectControls
|
||||||
<TimeTrackerProjectTaskDropdown
|
v-if="!isOnBreak && timeTrackerMode !== 'simple'"
|
||||||
v-model:project="currentTimeEntry.project_id"
|
v-model:current-time-entry="currentTimeEntry"
|
||||||
v-model:task="currentTimeEntry.task_id"
|
|
||||||
variant="outline"
|
|
||||||
:create-client
|
|
||||||
:can-create-project
|
|
||||||
:clients
|
|
||||||
:create-project
|
|
||||||
:currency="currency"
|
|
||||||
:organization-billable-rate="organizationBillableRate"
|
|
||||||
:projects="projects"
|
:projects="projects"
|
||||||
:tasks="tasks"
|
:tasks="tasks"
|
||||||
:enable-estimated-time="enableEstimatedTime"
|
|
||||||
@changed="updateProject"></TimeTrackerProjectTaskDropdown>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center space-x-0 @4xl:space-x-2 px-2 @4xl:px-4 shrink-0">
|
|
||||||
<TimeTrackerTagDropdown
|
|
||||||
v-model="currentTimeEntry.tags"
|
|
||||||
:create-tag
|
|
||||||
:tags="tags"
|
:tags="tags"
|
||||||
@changed="$emit('updateTimeEntry')"></TimeTrackerTagDropdown>
|
:clients="clients"
|
||||||
<BillableToggleButton
|
:create-tag="createTag"
|
||||||
v-model="currentTimeEntry.billable"
|
:create-project="createProject"
|
||||||
@changed="$emit('updateTimeEntry')"></BillableToggleButton>
|
:create-client="createClient"
|
||||||
</div>
|
:currency="currency"
|
||||||
<div class="border-l border-card-border">
|
:organization-billable-rate="organizationBillableRate"
|
||||||
|
:enable-estimated-time="enableEstimatedTime"
|
||||||
|
:can-create-project="canCreateProject"
|
||||||
|
@update-time-entry="emit('updateTimeEntry')"></TimeTrackerProjectControls>
|
||||||
|
<button
|
||||||
|
v-if="isOnBreak && canResumeAfterBreak"
|
||||||
|
type="button"
|
||||||
|
class="mx-2 flex min-w-0 shrink items-center gap-1.5 h-8 px-3 rounded-md bg-transparent border border-amber-500/40 hover:bg-amber-500/15 text-sm font-medium text-amber-600 dark:text-amber-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 transition"
|
||||||
|
@click="emit('resumeAfterBreak')">
|
||||||
|
<Play class="w-4 h-4 shrink-0" />
|
||||||
|
<span class="truncate">{{
|
||||||
|
resumeDescription ? `Resume "${resumeDescription}"` : 'Resume'
|
||||||
|
}}</span>
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
class="border-l"
|
||||||
|
:class="isOnBreak ? 'border-amber-500/40' : 'border-card-border'">
|
||||||
<TimeTrackerRangeSelector
|
<TimeTrackerRangeSelector
|
||||||
v-model:current-time-entry="currentTimeEntry"
|
v-model:current-time-entry="currentTimeEntry"
|
||||||
v-model:live-timer="liveTimer"
|
v-model:live-timer="liveTimer"
|
||||||
|
:is-on-break="isOnBreak"
|
||||||
@start-live-timer="emit('startLiveTimer')"
|
@start-live-timer="emit('startLiveTimer')"
|
||||||
@stop-live-timer="emit('stopLiveTimer')"
|
@stop-live-timer="emit('stopLiveTimer')"
|
||||||
@update-timer="emit('updateTimeEntry')"
|
@update-timer="emit('updateTimeEntry')"
|
||||||
@start-timer="emit('startTimer')"
|
@start-timer="emit('startTimer')"
|
||||||
@create-time-entry="emit('createTimeEntry')"
|
@create-time-entry="emit('createTimeEntry')"
|
||||||
@keydown.enter="startTimerIfNotActive"></TimeTrackerRangeSelector>
|
@keydown.enter="onRangeEnter"></TimeTrackerRangeSelector>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pl-4 @2xl:pl-6 pr-3 hidden @2xl:block">
|
<div class="pl-4 @2xl:pl-6 pr-3 hidden @2xl:flex items-center space-x-3">
|
||||||
|
<button
|
||||||
|
v-if="breaksEnabled && !isOnBreak && isActive"
|
||||||
|
type="button"
|
||||||
|
title="Take a break"
|
||||||
|
aria-label="Take a break"
|
||||||
|
class="flex items-center justify-center w-9 h-9 rounded-full bg-quaternary text-text-tertiary hover:text-amber-500 focus:ring-2 focus:ring-border-tertiary transition"
|
||||||
|
@click="emit('startBreak')">
|
||||||
|
<Coffee class="w-5 h-5" />
|
||||||
|
</button>
|
||||||
<TimeTrackerStartStop
|
<TimeTrackerStartStop
|
||||||
:active="isActive"
|
:active="isActive"
|
||||||
|
:variant="isOnBreak ? 'break' : 'primary'"
|
||||||
size="large"
|
size="large"
|
||||||
@changed="onToggleButtonPress"></TimeTrackerStartStop>
|
@changed="onToggleButtonPress"></TimeTrackerStartStop>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, ref, watch } from 'vue';
|
||||||
|
import { useFocus } from '@vueuse/core';
|
||||||
|
import { autoUpdate, flip, limitShift, offset, shift, useFloating } from '@floating-ui/vue';
|
||||||
|
import TimeTrackerRecentlyTrackedEntry from '@/packages/ui/src/TimeTracker/TimeTrackerRecentlyTrackedEntry.vue';
|
||||||
|
import { useSelectEvents } from '@/packages/ui/src/utils/select';
|
||||||
|
import type { Project, Task, TimeEntry } from '@/packages/api/src';
|
||||||
|
|
||||||
|
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', { required: true });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
timeEntries: TimeEntry[];
|
||||||
|
projects: Project[];
|
||||||
|
tasks: Task[];
|
||||||
|
isActive: boolean;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{ startTimer: []; updateTimeEntry: [] }>();
|
||||||
|
|
||||||
|
const currentTimeEntryDescriptionInput = ref<HTMLInputElement | null>(null);
|
||||||
|
|
||||||
|
const tempDescription = ref(currentTimeEntry.value.description);
|
||||||
|
watch(
|
||||||
|
() => currentTimeEntry.value.description,
|
||||||
|
() => {
|
||||||
|
tempDescription.value = currentTimeEntry.value.description;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
function updateTimeEntryDescription() {
|
||||||
|
if (currentTimeEntry.value.description !== tempDescription.value) {
|
||||||
|
currentTimeEntry.value.description = tempDescription.value;
|
||||||
|
emit('updateTimeEntry');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setCurrentTimeEntry(timeEntry: TimeEntry) {
|
||||||
|
currentTimeEntry.value.description = timeEntry.description;
|
||||||
|
currentTimeEntry.value.project_id = timeEntry.project_id;
|
||||||
|
currentTimeEntry.value.task_id = timeEntry.task_id;
|
||||||
|
currentTimeEntry.value.tags = timeEntry.tags;
|
||||||
|
currentTimeEntry.value.billable = timeEntry.billable;
|
||||||
|
currentTimeEntry.value.type = timeEntry.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setAndStartTimer(timeEntry: TimeEntry) {
|
||||||
|
setCurrentTimeEntry(timeEntry);
|
||||||
|
if (!props.isActive) {
|
||||||
|
emit('startTimer');
|
||||||
|
} else {
|
||||||
|
emit('updateTimeEntry');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Starts the timer from the description input / range selector Enter: picks the highlighted
|
||||||
|
// recently-tracked entry if one is active, otherwise commits the typed description.
|
||||||
|
function submit() {
|
||||||
|
if (highlightedDropdownEntryId.value) {
|
||||||
|
const timeEntry = filteredRecentlyTrackedTimeEntries.value.find(
|
||||||
|
(item) => item.id === highlightedDropdownEntryId.value
|
||||||
|
);
|
||||||
|
if (timeEntry) {
|
||||||
|
setCurrentTimeEntry(timeEntry);
|
||||||
|
showDropdown.value = false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentTimeEntry.value.description = tempDescription.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!props.isActive) {
|
||||||
|
emit('startTimer');
|
||||||
|
} else {
|
||||||
|
emit('updateTimeEntry');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const filteredRecentlyTrackedTimeEntries = computed(() => {
|
||||||
|
// do not include running time entries and breaks (breaks are started via the break button)
|
||||||
|
const finishedTimeEntries = props.timeEntries.filter(
|
||||||
|
(item) => item.end !== null && item.type !== 'break'
|
||||||
|
);
|
||||||
|
|
||||||
|
// filter out duplicates based on description, task, project, tags and billable
|
||||||
|
const nonDuplicateTimeEntries = finishedTimeEntries.filter((item, index, self) => {
|
||||||
|
return (
|
||||||
|
index ===
|
||||||
|
self.findIndex(
|
||||||
|
(t) =>
|
||||||
|
t.description === item.description &&
|
||||||
|
t.task_id === item.task_id &&
|
||||||
|
t.project_id === item.project_id &&
|
||||||
|
t.tags.length === item.tags.length &&
|
||||||
|
t.tags.every((tag) => item.tags.includes(tag)) &&
|
||||||
|
t.billable === item.billable
|
||||||
|
)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// filter time entries based on current description
|
||||||
|
return nonDuplicateTimeEntries
|
||||||
|
.filter((item) => {
|
||||||
|
return item.description
|
||||||
|
?.toLowerCase()
|
||||||
|
?.includes(tempDescription.value?.toLowerCase()?.trim() || '');
|
||||||
|
})
|
||||||
|
.slice(0, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
const showDropdown = ref(false);
|
||||||
|
const blockRefocus = ref(false);
|
||||||
|
const { focused } = useFocus(currentTimeEntryDescriptionInput);
|
||||||
|
|
||||||
|
watch(focused, (focused) => {
|
||||||
|
nextTick(() => {
|
||||||
|
// make sure the click event on the dropdown does not get interrupted
|
||||||
|
showDropdown.value = focused;
|
||||||
|
|
||||||
|
// make sure that the input does not get refocused after the dropdown is closed
|
||||||
|
if (!focused) {
|
||||||
|
blockRefocus.value = true;
|
||||||
|
setTimeout(() => {
|
||||||
|
blockRefocus.value = false;
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const floating = ref(null);
|
||||||
|
const { floatingStyles } = useFloating(currentTimeEntryDescriptionInput, floating, {
|
||||||
|
placement: 'bottom-start',
|
||||||
|
whileElementsMounted: autoUpdate,
|
||||||
|
middleware: [
|
||||||
|
offset(10),
|
||||||
|
shift({
|
||||||
|
limiter: limitShift({
|
||||||
|
offset: 5,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
flip({
|
||||||
|
fallbackAxisSideDirection: 'start',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const highlightedDropdownEntryId = ref<string | null>(null);
|
||||||
|
|
||||||
|
useSelectEvents(
|
||||||
|
filteredRecentlyTrackedTimeEntries,
|
||||||
|
highlightedDropdownEntryId,
|
||||||
|
(item) => item.id,
|
||||||
|
showDropdown
|
||||||
|
);
|
||||||
|
|
||||||
|
// Called by the shell after the start/stop button starts a timer, so typing can continue.
|
||||||
|
function focusAfterStart() {
|
||||||
|
if (!blockRefocus.value) {
|
||||||
|
currentTimeEntryDescriptionInput.value?.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ submit, focusAfterStart });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<input
|
||||||
|
ref="currentTimeEntryDescriptionInput"
|
||||||
|
v-model="tempDescription"
|
||||||
|
placeholder="What are you working on?"
|
||||||
|
data-testid="time_entry_description"
|
||||||
|
class="w-full rounded-l-lg py-4 sm:py-2.5 px-3.5 border-b border-b-card-background-separator @2xl:px-4 text-base text-text-primary bg-transparent border-none placeholder-text-secondary focus:ring-0 transition"
|
||||||
|
type="text"
|
||||||
|
@keydown.enter="submit"
|
||||||
|
@keydown.esc="showDropdown = false"
|
||||||
|
@blur="updateTimeEntryDescription" />
|
||||||
|
<div
|
||||||
|
v-if="showDropdown && filteredRecentlyTrackedTimeEntries.length > 0"
|
||||||
|
ref="floating"
|
||||||
|
class="z-50 w-[min(640px,100vw-2rem)]"
|
||||||
|
:style="floatingStyles">
|
||||||
|
<div
|
||||||
|
class="rounded-lg w-full border border-card-border overflow-hidden shadow-dropdown bg-card-background">
|
||||||
|
<div
|
||||||
|
class="text-text-tertiary text-xs font-semibold border-b border-border-tertiary px-2 py-1.5">
|
||||||
|
Recently Tracked Time Entries
|
||||||
|
</div>
|
||||||
|
<div class="text-text-secondary py-1 px-1.5">
|
||||||
|
<TimeTrackerRecentlyTrackedEntry
|
||||||
|
v-for="timeEntry in filteredRecentlyTrackedTimeEntries"
|
||||||
|
:key="timeEntry.id"
|
||||||
|
:time-entry="timeEntry"
|
||||||
|
:highlighted="highlightedDropdownEntryId === timeEntry.id"
|
||||||
|
:projects="projects"
|
||||||
|
:tasks="tasks"
|
||||||
|
@mousedown="setAndStartTimer(timeEntry)"
|
||||||
|
@mouseenter="
|
||||||
|
highlightedDropdownEntryId = timeEntry.id
|
||||||
|
"></TimeTrackerRecentlyTrackedEntry>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,14 +1,28 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { PlusIcon, XMarkIcon } from '@heroicons/vue/20/solid';
|
import { PlusIcon, XMarkIcon, ClockIcon } from '@heroicons/vue/20/solid';
|
||||||
|
import { Coffee } from '@lucide/vue';
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '..';
|
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '..';
|
||||||
|
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
hasActiveTimer: boolean;
|
hasActiveTimer: boolean;
|
||||||
}>();
|
timeTrackerMode?: TimeTrackerMode;
|
||||||
|
breaksEnabled?: boolean;
|
||||||
|
isOnBreak?: boolean;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
timeTrackerMode: 'project',
|
||||||
|
breaksEnabled: false,
|
||||||
|
isOnBreak: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
manualEntry: [];
|
manualEntry: [];
|
||||||
|
startBreak: [];
|
||||||
discard: [];
|
discard: [];
|
||||||
|
toggleTimeTrackerMode: [];
|
||||||
}>();
|
}>();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -39,6 +53,23 @@ const emit = defineEmits<{
|
|||||||
<PlusIcon class="w-5" />
|
<PlusIcon class="w-5" />
|
||||||
<span>Manual time entry</span>
|
<span>Manual time entry</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
v-if="props.breaksEnabled && !props.isOnBreak"
|
||||||
|
class="flex items-center space-x-3 cursor-pointer"
|
||||||
|
@click="emit('startBreak')">
|
||||||
|
<Coffee class="w-5" />
|
||||||
|
<span>Start Break</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
class="flex items-center space-x-3 cursor-pointer"
|
||||||
|
@click="emit('toggleTimeTrackerMode')">
|
||||||
|
<ClockIcon class="w-5" />
|
||||||
|
<span>{{
|
||||||
|
props.timeTrackerMode === 'simple'
|
||||||
|
? 'Switch to project mode'
|
||||||
|
: 'Switch to simple mode'
|
||||||
|
}}</span>
|
||||||
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
v-if="props.hasActiveTimer"
|
v-if="props.hasActiveTimer"
|
||||||
class="flex items-center space-x-3 cursor-pointer text-destructive focus:text-destructive"
|
class="flex items-center space-x-3 cursor-pointer text-destructive focus:text-destructive"
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { shallowMount } from '@vue/test-utils';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { nextTick } from 'vue';
|
||||||
|
import TimeTrackerProjectControls from './TimeTrackerProjectControls.vue';
|
||||||
|
import TimeTrackerProjectTaskDropdown from './TimeTrackerProjectTaskDropdown.vue';
|
||||||
|
import type { Project, TimeEntry } from '@/packages/api/src';
|
||||||
|
|
||||||
|
function timeEntry(overrides: Partial<TimeEntry> = {}): TimeEntry {
|
||||||
|
return {
|
||||||
|
id: 'te-1',
|
||||||
|
description: '',
|
||||||
|
start: '2026-07-14T09:00:00Z',
|
||||||
|
end: null,
|
||||||
|
duration: null,
|
||||||
|
project_id: null,
|
||||||
|
task_id: null,
|
||||||
|
organization_id: 'org-1',
|
||||||
|
user_id: 'user-1',
|
||||||
|
tags: [],
|
||||||
|
billable: false,
|
||||||
|
type: 'work',
|
||||||
|
...overrides,
|
||||||
|
} as TimeEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('TimeTrackerProjectControls', () => {
|
||||||
|
it('adopts the billable default of a newly selected project', async () => {
|
||||||
|
const current = timeEntry({ project_id: null, billable: false });
|
||||||
|
const billableProject = { id: 'p-1', is_billable: true } as Project;
|
||||||
|
const wrapper = shallowMount(TimeTrackerProjectControls, {
|
||||||
|
props: {
|
||||||
|
currentTimeEntry: current,
|
||||||
|
projects: [billableProject],
|
||||||
|
tasks: [],
|
||||||
|
tags: [],
|
||||||
|
clients: [],
|
||||||
|
createTag: vi.fn(),
|
||||||
|
createProject: vi.fn(),
|
||||||
|
createClient: vi.fn(),
|
||||||
|
currency: 'EUR',
|
||||||
|
organizationBillableRate: null,
|
||||||
|
enableEstimatedTime: false,
|
||||||
|
canCreateProject: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const dropdown = wrapper.findComponent(TimeTrackerProjectTaskDropdown);
|
||||||
|
// The dropdown sets the project via v-model, then emits `changed`.
|
||||||
|
dropdown.vm.$emit('update:project', 'p-1');
|
||||||
|
dropdown.vm.$emit('changed');
|
||||||
|
await nextTick();
|
||||||
|
|
||||||
|
expect(current.billable).toBe(true);
|
||||||
|
expect(wrapper.emitted('updateTimeEntry')).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
|
||||||
|
import TimeTrackerTagDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerTagDropdown.vue';
|
||||||
|
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
|
||||||
|
import type {
|
||||||
|
Client,
|
||||||
|
CreateClientBody,
|
||||||
|
CreateProjectBody,
|
||||||
|
Project,
|
||||||
|
Tag,
|
||||||
|
Task,
|
||||||
|
TimeEntry,
|
||||||
|
} from '@/packages/api/src';
|
||||||
|
|
||||||
|
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', { required: true });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
projects: Project[];
|
||||||
|
tasks: Task[];
|
||||||
|
tags: Tag[];
|
||||||
|
clients: Client[];
|
||||||
|
createTag: (name: string) => Promise<Tag | undefined>;
|
||||||
|
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
|
||||||
|
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
|
||||||
|
currency: string;
|
||||||
|
organizationBillableRate: number | null;
|
||||||
|
enableEstimatedTime: boolean;
|
||||||
|
canCreateProject: boolean;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{ updateTimeEntry: [] }>();
|
||||||
|
|
||||||
|
function updateProject() {
|
||||||
|
// Adopt the project's billable default when a project is picked.
|
||||||
|
const project = props.projects.find((p) => p.id === currentTimeEntry.value.project_id);
|
||||||
|
if (project) {
|
||||||
|
currentTimeEntry.value.billable = project.is_billable;
|
||||||
|
}
|
||||||
|
emit('updateTimeEntry');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex items-center w-[130px] @2xl:w-auto shrink min-w-0">
|
||||||
|
<TimeTrackerProjectTaskDropdown
|
||||||
|
v-model:project="currentTimeEntry.project_id"
|
||||||
|
v-model:task="currentTimeEntry.task_id"
|
||||||
|
variant="outline"
|
||||||
|
:create-client="createClient"
|
||||||
|
:can-create-project="canCreateProject"
|
||||||
|
:clients="clients"
|
||||||
|
:create-project="createProject"
|
||||||
|
:currency="currency"
|
||||||
|
:organization-billable-rate="organizationBillableRate"
|
||||||
|
:projects="projects"
|
||||||
|
:tasks="tasks"
|
||||||
|
:enable-estimated-time="enableEstimatedTime"
|
||||||
|
@changed="updateProject"></TimeTrackerProjectTaskDropdown>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center space-x-0 @4xl:space-x-2 px-2 @4xl:px-4 shrink-0">
|
||||||
|
<TimeTrackerTagDropdown
|
||||||
|
v-model="currentTimeEntry.tags"
|
||||||
|
:create-tag="createTag"
|
||||||
|
:tags="tags"
|
||||||
|
@changed="emit('updateTimeEntry')"></TimeTrackerTagDropdown>
|
||||||
|
<BillableToggleButton
|
||||||
|
v-model="currentTimeEntry.billable"
|
||||||
|
@changed="emit('updateTimeEntry')"></BillableToggleButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -694,8 +694,8 @@ const showCreateProject = ref(false);
|
|||||||
class="flex items-center space-x-2 w-full px-5 py-1.5 text-start text-xs font-semibold leading-5 text-text-primary focus:outline-none transition duration-150 ease-in-out"
|
class="flex items-center space-x-2 w-full px-5 py-1.5 text-start text-xs font-semibold leading-5 text-text-primary focus:outline-none transition duration-150 ease-in-out"
|
||||||
:class="
|
:class="
|
||||||
row.task.id === highlightedItemId
|
row.task.id === highlightedItemId
|
||||||
? 'bg-card-background-active'
|
? 'bg-quaternary dark:bg-tertiary'
|
||||||
: 'bg-quaternary'
|
: 'bg-tertiary dark:bg-quaternary'
|
||||||
"
|
"
|
||||||
@click="selectTask(row.task.id)"
|
@click="selectTask(row.task.id)"
|
||||||
@mouseenter="setHighlightItemId(row.task.id)">
|
@mouseenter="setHighlightItemId(row.task.id)">
|
||||||
|
|||||||
@@ -11,6 +11,15 @@ const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', {
|
|||||||
});
|
});
|
||||||
const now = defineModel<null | Dayjs>('liveTimer');
|
const now = defineModel<null | Dayjs>('liveTimer');
|
||||||
|
|
||||||
|
withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
isOnBreak?: boolean;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
isOnBreak: false,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
startLiveTimer: [];
|
startLiveTimer: [];
|
||||||
stopLiveTimer: [];
|
stopLiveTimer: [];
|
||||||
@@ -154,7 +163,12 @@ function closeAndFocusInput() {
|
|||||||
v-model="currentTime"
|
v-model="currentTime"
|
||||||
placeholder="00:00:00"
|
placeholder="00:00:00"
|
||||||
data-testid="time_entry_time"
|
data-testid="time_entry_time"
|
||||||
class="w-[110px] lg:w-[120px] h-full text-text-primary py-2.5 rounded-lg border-border-secondary border text-center px-4 text-base font-semibold bg-card-background border-none placeholder-text-tertiary focus:ring-0 transition"
|
class="w-[110px] lg:w-[120px] h-full py-2.5 rounded-lg text-center px-4 text-base font-semibold placeholder-text-tertiary focus:ring-0 transition"
|
||||||
|
:class="
|
||||||
|
isOnBreak
|
||||||
|
? 'text-amber-600 dark:text-amber-400 bg-transparent border-none'
|
||||||
|
: 'text-text-primary bg-card-background border-border-secondary border border-none'
|
||||||
|
"
|
||||||
type="text"
|
type="text"
|
||||||
@focusin="openModalOnTab"
|
@focusin="openModalOnTab"
|
||||||
@click="openModalOnClick"
|
@click="openModalOnClick"
|
||||||
|
|||||||
6
resources/js/packages/ui/src/TimeTracker/types.ts
Normal file
6
resources/js/packages/ui/src/TimeTracker/types.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
/**
|
||||||
|
* How the time tracker presents its controls. `project` shows the full
|
||||||
|
* project/task/tag/billable controls; `simple` hides them for plain
|
||||||
|
* description-only tracking. Persisted client-side as a UI preference.
|
||||||
|
*/
|
||||||
|
export type TimeTrackerMode = 'project' | 'simple';
|
||||||
@@ -11,6 +11,7 @@ const timeTrackerVariants = cva(
|
|||||||
'text-white ring-accent-200/10 focus-visible:ring-ring focus-visible:ring-2 ring-4 sm:ring-[6px]',
|
'text-white ring-accent-200/10 focus-visible:ring-ring focus-visible:ring-2 ring-4 sm:ring-[6px]',
|
||||||
secondary:
|
secondary:
|
||||||
'bg-quaternary text-text-tertiary hover:text-text-primary focus:ring-2 focus:ring-border-tertiary',
|
'bg-quaternary text-text-tertiary hover:text-text-primary focus:ring-2 focus:ring-border-tertiary',
|
||||||
|
break: 'text-white ring-amber-200/10 focus-visible:ring-ring focus-visible:ring-2 ring-4 sm:ring-[6px]',
|
||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
small: 'w-6 h-6',
|
small: 'w-6 h-6',
|
||||||
@@ -33,6 +34,16 @@ const timeTrackerVariants = cva(
|
|||||||
active: false,
|
active: false,
|
||||||
class: 'bg-accent-300/70 hover:bg-accent-400/70 focus:bg-accent-700',
|
class: 'bg-accent-300/70 hover:bg-accent-400/70 focus:bg-accent-700',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
variant: 'break',
|
||||||
|
active: true,
|
||||||
|
class: 'bg-amber-500/80 hover:bg-amber-600/80 focus:bg-amber-600/80',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variant: 'break',
|
||||||
|
active: false,
|
||||||
|
class: 'bg-accent-300/70 hover:bg-accent-400/70 focus:bg-accent-700',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
defaultVariants: {
|
defaultVariants: {
|
||||||
variant: 'primary',
|
variant: 'primary',
|
||||||
|
|||||||
57
resources/js/packages/ui/src/utils/breakPlacement.test.ts
Normal file
57
resources/js/packages/ui/src/utils/breakPlacement.test.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { TimeEntry } from '@/packages/api/src';
|
||||||
|
import {
|
||||||
|
findMisplacedBreak,
|
||||||
|
type BreakPlacementHint,
|
||||||
|
} from '@/packages/ui/src/utils/breakPlacement';
|
||||||
|
|
||||||
|
// Decision logic behind the aggregate (collapsed grouped-break) row's placement
|
||||||
|
// warning: the row shows the hint — and navigates the calendar — based on the
|
||||||
|
// first misplaced break in the group.
|
||||||
|
function breakEntry(id: string): TimeEntry {
|
||||||
|
return { id, type: 'break', start: '2026-07-14T10:00:00Z' } as TimeEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hint(misplaced: boolean): BreakPlacementHint {
|
||||||
|
return {
|
||||||
|
misplaced,
|
||||||
|
previousWorkEnd: null,
|
||||||
|
nextWorkStart: null,
|
||||||
|
gapBeforeSeconds: null,
|
||||||
|
gapAfterSeconds: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('findMisplacedBreak', () => {
|
||||||
|
it('returns the first misplaced break in a group', () => {
|
||||||
|
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||||
|
const result = findMisplacedBreak(entries, {
|
||||||
|
'break-a': hint(false),
|
||||||
|
'break-b': hint(true),
|
||||||
|
});
|
||||||
|
expect(result?.id).toBe('break-b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when no break in the group is misplaced', () => {
|
||||||
|
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||||
|
const result = findMisplacedBreak(entries, {
|
||||||
|
'break-a': hint(false),
|
||||||
|
'break-b': hint(false),
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the group has no placement hints', () => {
|
||||||
|
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||||
|
expect(findMisplacedBreak(entries, {})).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores hints for entries that are not in the group', () => {
|
||||||
|
const entries = [breakEntry('break-a')];
|
||||||
|
const result = findMisplacedBreak(entries, {
|
||||||
|
'break-a': hint(false),
|
||||||
|
'break-elsewhere': hint(true),
|
||||||
|
});
|
||||||
|
expect(result).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
102
resources/js/packages/ui/src/utils/breakPlacement.ts
Normal file
102
resources/js/packages/ui/src/utils/breakPlacement.ts
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
import type { TimeEntry } from '@/packages/api/src';
|
||||||
|
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||||
|
|
||||||
|
export interface BreakPlacementHint {
|
||||||
|
misplaced: boolean;
|
||||||
|
// Closest work end at or before the break start (null if none is known)
|
||||||
|
previousWorkEnd: string | null;
|
||||||
|
// Closest work start at or after the break end (null if none is known)
|
||||||
|
nextWorkStart: string | null;
|
||||||
|
gapBeforeSeconds: number | null;
|
||||||
|
gapAfterSeconds: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// How far a break may sit from the nearest work entry before it gets a placement hint
|
||||||
|
export const BREAK_GAP_TOLERANCE_MINUTES = 30;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grouped breaks collapse into a single summary row, so the row needs to know
|
||||||
|
* whether any break in the group is misplaced (to show the warning) and which
|
||||||
|
* one to navigate to (all grouped entries share the same day). Returns the first
|
||||||
|
* misplaced break in the group, or null when none is flagged.
|
||||||
|
*/
|
||||||
|
export function findMisplacedBreak(
|
||||||
|
entries: TimeEntry[],
|
||||||
|
hints: Record<string, BreakPlacementHint | null>
|
||||||
|
): TimeEntry | null {
|
||||||
|
return entries.find((entry) => hints[entry.id]?.misplaced) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A break only means something between work. This computes how far a break
|
||||||
|
* sits from the nearest work entry on either side — everything non-work
|
||||||
|
* (untracked gaps and other breaks) counts as distance. If either side has
|
||||||
|
* more than the tolerated gap (or no work at all), the break gets a hint.
|
||||||
|
*
|
||||||
|
* Non-blocking by design: placement can not be validated at write time
|
||||||
|
* (it depends on entries that may not exist yet), so it is derived at read
|
||||||
|
* time from the loaded entries.
|
||||||
|
*/
|
||||||
|
export function getBreakPlacementHint(
|
||||||
|
breakEntry: TimeEntry,
|
||||||
|
allEntries: TimeEntry[]
|
||||||
|
): BreakPlacementHint | null {
|
||||||
|
if (breakEntry.type !== 'break') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const breakStart = dayjs.utc(breakEntry.start);
|
||||||
|
const breakEnd = breakEntry.end === null ? dayjs.utc() : dayjs.utc(breakEntry.end);
|
||||||
|
const toleranceSeconds = BREAK_GAP_TOLERANCE_MINUTES * 60;
|
||||||
|
|
||||||
|
let previousWorkEnd: ReturnType<typeof dayjs> | null = null;
|
||||||
|
let nextWorkStart: ReturnType<typeof dayjs> | null = null;
|
||||||
|
|
||||||
|
for (const entry of allEntries) {
|
||||||
|
if (entry.type === 'break' || entry.id === breakEntry.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const entryStart = dayjs.utc(entry.start);
|
||||||
|
const entryEnd = entry.end === null ? dayjs.utc() : dayjs.utc(entry.end);
|
||||||
|
|
||||||
|
// Work overlapping the break counts as touching on both sides
|
||||||
|
if (entryEnd.isAfter(breakStart) && entryStart.isBefore(breakEnd)) {
|
||||||
|
return {
|
||||||
|
misplaced: false,
|
||||||
|
previousWorkEnd: entryEnd.format(),
|
||||||
|
nextWorkStart: entryStart.format(),
|
||||||
|
gapBeforeSeconds: 0,
|
||||||
|
gapAfterSeconds: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!entryEnd.isAfter(breakStart)) {
|
||||||
|
if (previousWorkEnd === null || entryEnd.isAfter(previousWorkEnd)) {
|
||||||
|
previousWorkEnd = entryEnd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!entryStart.isBefore(breakEnd)) {
|
||||||
|
if (nextWorkStart === null || entryStart.isBefore(nextWorkStart)) {
|
||||||
|
nextWorkStart = entryStart;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const gapBeforeSeconds =
|
||||||
|
previousWorkEnd !== null ? breakStart.diff(previousWorkEnd, 'second') : null;
|
||||||
|
const gapAfterSeconds = nextWorkStart !== null ? nextWorkStart.diff(breakEnd, 'second') : null;
|
||||||
|
|
||||||
|
// A running break has no "after" side yet — only judge the before side
|
||||||
|
const isRunning = breakEntry.end === null;
|
||||||
|
|
||||||
|
const beforeMisplaced = gapBeforeSeconds === null || gapBeforeSeconds > toleranceSeconds;
|
||||||
|
const afterMisplaced =
|
||||||
|
!isRunning && (gapAfterSeconds === null || gapAfterSeconds > toleranceSeconds);
|
||||||
|
|
||||||
|
return {
|
||||||
|
misplaced: beforeMisplaced || afterMisplaced,
|
||||||
|
previousWorkEnd: previousWorkEnd?.format() ?? null,
|
||||||
|
nextWorkStart: nextWorkStart?.format() ?? null,
|
||||||
|
gapBeforeSeconds,
|
||||||
|
gapAfterSeconds,
|
||||||
|
};
|
||||||
|
}
|
||||||
19
resources/js/packages/ui/src/utils/useBreaksEnabled.ts
Normal file
19
resources/js/packages/ui/src/utils/useBreaksEnabled.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { computed, inject, type ComputedRef } from 'vue';
|
||||||
|
import type { Organization } from '@/packages/api/src';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether break tracking is enabled for the current organization.
|
||||||
|
*
|
||||||
|
* Components below the app layout can call this with no argument (the layout
|
||||||
|
* provides `organization`); pages that sit above the layout pass their own
|
||||||
|
* organization ref. Without an organization (e.g. public report views) breaks
|
||||||
|
* count as disabled.
|
||||||
|
*/
|
||||||
|
export function useBreaksEnabled(organization?: {
|
||||||
|
value: Organization | undefined | null;
|
||||||
|
}): ComputedRef<boolean> {
|
||||||
|
const org =
|
||||||
|
organization ??
|
||||||
|
inject<ComputedRef<Organization | undefined> | undefined>('organization', undefined);
|
||||||
|
return computed(() => org?.value?.breaks_enabled ?? false);
|
||||||
|
}
|
||||||
@@ -88,8 +88,8 @@
|
|||||||
--theme-shadow-card: lch(0 0 0 / 0.022) 0px 3px 6px -2px, lch(0 0 0 / 0.044) 0px 1px 1px;
|
--theme-shadow-card: lch(0 0 0 / 0.022) 0px 3px 6px -2px, lch(0 0 0 / 0.044) 0px 1px 1px;
|
||||||
--theme-shadow-dropdown: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
|
--theme-shadow-dropdown: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
|
||||||
|
|
||||||
--theme-color-row-background: var(--theme-color-primary);
|
--theme-color-row-background: var(--color-bg-primary);
|
||||||
--theme-color-row-heading-background: var(--theme-color-primary);
|
--theme-color-row-heading-background: var(--color-bg-primary);
|
||||||
--theme-color-row-heading-border: var(--color-border-tertiary);
|
--theme-color-row-heading-border: var(--color-border-tertiary);
|
||||||
--theme-color-icon-default: var(--color-text-quaternary);
|
--theme-color-icon-default: var(--color-text-quaternary);
|
||||||
|
|
||||||
|
|||||||
@@ -91,12 +91,13 @@ function prefetchDashboard(queryClient: QueryClient) {
|
|||||||
prefetchTasks(queryClient);
|
prefetchTasks(queryClient);
|
||||||
|
|
||||||
// Prefetch all dashboard card data
|
// Prefetch all dashboard card data
|
||||||
|
// Must match the query in RecentlyTrackedTasksCard exactly — same key, same params
|
||||||
queryClient.prefetchQuery({
|
queryClient.prefetchQuery({
|
||||||
queryKey: ['timeEntries', organizationId],
|
queryKey: ['timeEntries', organizationId],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
api.getTimeEntries({
|
api.getTimeEntries({
|
||||||
params: { organization: organizationId },
|
params: { organization: organizationId },
|
||||||
queries: { limit: 10, offset: 0, only_full_dates: 'true' },
|
queries: { member_id: getCurrentMembershipId(), type: 'work' },
|
||||||
}),
|
}),
|
||||||
staleTime: 30000,
|
staleTime: 30000,
|
||||||
});
|
});
|
||||||
|
|||||||
490
resources/js/utils/timesheet/breakPlacementMath.test.ts
Normal file
490
resources/js/utils/timesheet/breakPlacementMath.test.ts
Normal file
@@ -0,0 +1,490 @@
|
|||||||
|
import dayjs from 'dayjs';
|
||||||
|
import utc from 'dayjs/plugin/utc';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
BREAK_GAP_TOLERANCE_SECONDS,
|
||||||
|
buildDayPlacementContext,
|
||||||
|
findValidBreakGap,
|
||||||
|
findValidBreakGapNear,
|
||||||
|
planMoveInsert,
|
||||||
|
planSplitEntry,
|
||||||
|
suggestMovePlan,
|
||||||
|
type MovableInterval,
|
||||||
|
} from './breakPlacementMath';
|
||||||
|
|
||||||
|
dayjs.extend(utc);
|
||||||
|
|
||||||
|
const HALF_HOUR = 1800;
|
||||||
|
const HOUR = 3600;
|
||||||
|
const DAY = '2026-07-14';
|
||||||
|
const dayStart = `${DAY}T00:00:00Z`;
|
||||||
|
const dayEnd = `${DAY}T24:00:00Z`;
|
||||||
|
|
||||||
|
function iv(startH: number, endH: number) {
|
||||||
|
const h = (n: number) => {
|
||||||
|
const totalMin = Math.round(n * 60);
|
||||||
|
const hh = Math.floor(totalMin / 60);
|
||||||
|
const mm = totalMin % 60;
|
||||||
|
return `${DAY}T${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:00Z`;
|
||||||
|
};
|
||||||
|
return { start: h(startH), end: h(endH) };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('findValidBreakGap', () => {
|
||||||
|
it('centers the break in a gap that fits within tolerance', () => {
|
||||||
|
// 09-12 and 13-17 → 1h gap, 30m break → centered at 12:15-12:45
|
||||||
|
const gap = findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR);
|
||||||
|
expect(gap).toEqual({ start: `${DAY}T12:15:00Z`, end: `${DAY}T12:45:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a gap that is too small for the break', () => {
|
||||||
|
// 09-12 and 12:15-17 → 15m gap, 30m break does not fit
|
||||||
|
expect(findValidBreakGap([iv(9, 12), iv(12.25, 17)], HALF_HOUR)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('places the break flush after work in an oversized gap instead of rejecting it', () => {
|
||||||
|
// 09-12 and 14-17 → 2h gap. No placement keeps both sides within tolerance,
|
||||||
|
// but the gap easily holds the break — place it flush after the first entry
|
||||||
|
// and leave the gap otherwise untouched (distance to work is only a soft hint).
|
||||||
|
expect(findValidBreakGap([iv(9, 12), iv(14, 17)], HALF_HOUR)).toEqual({
|
||||||
|
start: `${DAY}T12:00:00Z`,
|
||||||
|
end: `${DAY}T12:30:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prefers a within-tolerance gap over an earlier oversized gap', () => {
|
||||||
|
// 09-10, 13-14, 15-16: the first gap (3h) is oversized, the second (1h) is
|
||||||
|
// valid → center in the second instead of going flush-left in the first.
|
||||||
|
expect(findValidBreakGap([iv(9, 10), iv(13, 14), iv(15, 16)], HALF_HOUR)).toEqual({
|
||||||
|
start: `${DAY}T14:15:00Z`,
|
||||||
|
end: `${DAY}T14:45:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('slides past an obstacle when placing into an oversized gap', () => {
|
||||||
|
// 09-12 and 16-17 with an existing break flush at 12:00 → the new break
|
||||||
|
// lands right after that break.
|
||||||
|
expect(findValidBreakGap([iv(9, 12), iv(16, 17)], HALF_HOUR, [iv(12, 12.75)])).toEqual({
|
||||||
|
start: `${DAY}T12:45:00Z`,
|
||||||
|
end: `${DAY}T13:15:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not fabricate a gap from an entry contained in a longer one', () => {
|
||||||
|
// 10-11 sits inside 09-17; the only real gap is 17:00-18:00 → centered there.
|
||||||
|
expect(findValidBreakGap([iv(9, 17), iv(10, 11), iv(18, 19)], HALF_HOUR)).toEqual({
|
||||||
|
start: `${DAY}T17:15:00Z`,
|
||||||
|
end: `${DAY}T17:45:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts a gap exactly at duration + 2*tolerance', () => {
|
||||||
|
const gapEnd = 12 + (HALF_HOUR + 2 * BREAK_GAP_TOLERANCE_SECONDS) / HOUR;
|
||||||
|
const gap = findValidBreakGap([iv(9, 12), iv(gapEnd, gapEnd + 1)], HALF_HOUR);
|
||||||
|
expect(gap).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when there is only one work entry', () => {
|
||||||
|
expect(findValidBreakGap([iv(9, 17)], HALF_HOUR)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips a gap already occupied by another break', () => {
|
||||||
|
// The only valid gap (12:15–12:45) is taken by an existing break → no auto placement
|
||||||
|
expect(
|
||||||
|
findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR, [
|
||||||
|
{ start: `${DAY}T12:15:00Z`, end: `${DAY}T12:45:00Z` },
|
||||||
|
])
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores obstacles that fall outside the chosen gap', () => {
|
||||||
|
expect(findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR, [iv(20, 21)])).toEqual({
|
||||||
|
start: `${DAY}T12:15:00Z`,
|
||||||
|
end: `${DAY}T12:45:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('planSplitEntry', () => {
|
||||||
|
it('splits a single entry and centers the break', () => {
|
||||||
|
const plan = planSplitEntry(iv(9, 17), HALF_HOUR);
|
||||||
|
expect(plan).not.toBeNull();
|
||||||
|
expect(plan!.firstHalf.start).toBe(`${DAY}T09:00:00Z`);
|
||||||
|
expect(plan!.breakSlot.start).toBe(plan!.firstHalf.end);
|
||||||
|
expect(plan!.secondHalf.start).toBe(plan!.breakSlot.end);
|
||||||
|
expect(plan!.secondHalf.end).toBe(`${DAY}T17:00:00Z`);
|
||||||
|
// break is 30m and centered → 12:45-13:15
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:45:00Z`, end: `${DAY}T13:15:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('honors an explicit break start', () => {
|
||||||
|
const plan = planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T10:00:00Z`);
|
||||||
|
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T10:00:00Z` });
|
||||||
|
expect(plan!.secondHalf.start).toBe(`${DAY}T10:30:00Z`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the entry is too short to leave work on both sides', () => {
|
||||||
|
expect(planSplitEntry(iv(9, 9.25), HALF_HOUR)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an explicit break start before the entry instead of clamping it', () => {
|
||||||
|
// 07:00 lies before the 09:00-17:00 entry — relocating it silently would
|
||||||
|
// leave a hair-thin first fragment at a time the user never picked.
|
||||||
|
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T07:00:00Z`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an explicit break start whose break would reach past the entry end', () => {
|
||||||
|
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T16:45:00Z`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an explicit break start that leaves less than the minimum fragment', () => {
|
||||||
|
// 09:00:30 would leave only 30s of work before the break.
|
||||||
|
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T09:00:30Z`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts an explicit break start leaving exactly the minimum fragment on each side', () => {
|
||||||
|
// 09:01 leaves 60s before; on a 09:00-09:32 entry a 30m break also leaves 60s after.
|
||||||
|
const plan = planSplitEntry(iv(9, 9 + 32 / 60), HALF_HOUR, `${DAY}T09:01:00Z`);
|
||||||
|
expect(plan).not.toBeNull();
|
||||||
|
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T09:01:00Z` });
|
||||||
|
expect(plan!.secondHalf).toEqual({ start: `${DAY}T09:31:00Z`, end: `${DAY}T09:32:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the entry cannot hold the break plus a minimum fragment per side', () => {
|
||||||
|
// 31 minutes of work cannot hold a 30m break with 60s of work on each side.
|
||||||
|
expect(planSplitEntry(iv(9, 9 + 31 / 60), HALF_HOUR)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('planMoveInsert', () => {
|
||||||
|
const movable = (id: string, startH: number, endH: number): MovableInterval => ({
|
||||||
|
id,
|
||||||
|
...iv(startH, endH),
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pushes the right block later to open a slot for the break', () => {
|
||||||
|
// Back-to-back 09-12 and 12-17. Insert 30m break at 12:00.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 12, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T12:00:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan).not.toBeNull();
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||||
|
// 'a' untouched (not in shifted), 'b' shifted +30m
|
||||||
|
expect(plan!.shifted).toEqual([
|
||||||
|
{ id: 'b', start: `${DAY}T12:30:00Z`, end: `${DAY}T17:30:00Z` },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves an oversized gap alone instead of pulling the right block flush', () => {
|
||||||
|
// 09-12 and 15-17 (3h gap). Break flush after first at 12:00 fits in the gap
|
||||||
|
// → nothing moves; the user's gap is preserved.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T12:00:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||||
|
expect(plan!.shifted).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not drag entries flush when the break sits mid-gap', () => {
|
||||||
|
// Break at 13:00 in the middle of the 12:00-15:00 gap → neither side moves.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T13:00:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan!.shifted).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shifts each side only as much as needed to clear the slot', () => {
|
||||||
|
// Break 14:45-15:15 overlaps only the start of 'b' → 'b' pushed 15m later,
|
||||||
|
// 'a' untouched.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T14:45:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan!.shifted).toEqual([
|
||||||
|
{ id: 'b', start: `${DAY}T15:15:00Z`, end: `${DAY}T17:15:00Z` },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pulls the left block earlier only when it overlaps the slot', () => {
|
||||||
|
// Break 11:45-12:15 overlaps the end of 'a' → 'a' pulled 15m earlier;
|
||||||
|
// 'b' (15-17) already clears the slot and stays put.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T11:45:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan!.shifted).toEqual([
|
||||||
|
{ id: 'a', start: `${DAY}T08:45:00Z`, end: `${DAY}T11:45:00Z` },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shifts the left block earlier when the right block cannot move within the day', () => {
|
||||||
|
// Right entry ends at 23:50; pushing it later would cross midnight, so the
|
||||||
|
// left block must move earlier instead.
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 12, 23 + 50 / 60)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T12:00:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
// Not feasible by pushing right; solver returns null (caller lets the user pick another spot)
|
||||||
|
expect(plan).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the break itself would fall outside the day', () => {
|
||||||
|
expect(
|
||||||
|
planMoveInsert([movable('a', 9, 12)], dayStart, dayEnd, `${DAY}T23:50:00Z`, HALF_HOUR)
|
||||||
|
).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('places a break between entries without shifting when they already have exactly the gap', () => {
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[movable('a', 9, 12), movable('b', 12.5, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
`${DAY}T12:00:00Z`,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
// gap is exactly 30m → 'b' already starts at break end, nothing to shift
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||||
|
expect(plan!.shifted).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('suggestMovePlan', () => {
|
||||||
|
const movable = (id: string, startH: number, endH: number): MovableInterval => ({
|
||||||
|
id,
|
||||||
|
...iv(startH, endH),
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds a flush-after placement for back-to-back entries', () => {
|
||||||
|
const plan = suggestMovePlan(
|
||||||
|
[movable('a', 9, 12), movable('b', 12, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to a flush-before placement when the day is nearly full at the end', () => {
|
||||||
|
// 09-12 and 12-23:50: pushing right past midnight is impossible, so the break
|
||||||
|
// is placed just before the second entry, pulling the first entry earlier.
|
||||||
|
const plan = suggestMovePlan(
|
||||||
|
[movable('a', 9, 12), movable('b', 12, 23 + 50 / 60)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
HALF_HOUR
|
||||||
|
);
|
||||||
|
expect(plan).not.toBeNull();
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T11:30:00Z`, end: `${DAY}T12:00:00Z` });
|
||||||
|
// first entry pulled 30m earlier, second untouched
|
||||||
|
expect(plan!.shifted.find((s) => s.id === 'a')).toEqual({
|
||||||
|
id: 'a',
|
||||||
|
start: `${DAY}T08:30:00Z`,
|
||||||
|
end: `${DAY}T11:30:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the day is completely full', () => {
|
||||||
|
const plan = suggestMovePlan([movable('a', 0, 24)], dayStart, dayEnd, HALF_HOUR);
|
||||||
|
expect(plan).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves existing breaks along with the surrounding work', () => {
|
||||||
|
// Fully packed day: work 09-12, break 12-12:30, work 12:30-17. Opening a
|
||||||
|
// slot after the morning work pushes the existing break and the afternoon
|
||||||
|
// work later together — the plan never lands on top of the break.
|
||||||
|
const plan = suggestMovePlan(
|
||||||
|
[movable('a', 9, 12), movable('c', 12.5, 17)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
HALF_HOUR,
|
||||||
|
[movable('x', 12, 12.5)]
|
||||||
|
);
|
||||||
|
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||||
|
expect([...plan!.shifted].sort((a, b) => a.id.localeCompare(b.id))).toEqual([
|
||||||
|
{ id: 'c', start: `${DAY}T13:00:00Z`, end: `${DAY}T17:30:00Z` },
|
||||||
|
{ id: 'x', start: `${DAY}T12:30:00Z`, end: `${DAY}T13:00:00Z` },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildDayPlacementContext', () => {
|
||||||
|
const PREV_DAY = '2026-07-13';
|
||||||
|
const entry = (id: string, start: string, end: string | null, type = 'work') => ({
|
||||||
|
id,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
type,
|
||||||
|
});
|
||||||
|
|
||||||
|
it('separates movable work and breaks fully inside the day', () => {
|
||||||
|
const ctx = buildDayPlacementContext(
|
||||||
|
[
|
||||||
|
entry('w1', `${DAY}T09:00:00Z`, `${DAY}T12:00:00Z`),
|
||||||
|
entry('b1', `${DAY}T12:00:00Z`, `${DAY}T12:30:00Z`, 'break'),
|
||||||
|
entry('w2', `${DAY}T13:00:00Z`, `${DAY}T17:00:00Z`),
|
||||||
|
],
|
||||||
|
dayStart,
|
||||||
|
dayEnd
|
||||||
|
);
|
||||||
|
expect(ctx.work.map((e) => e.id)).toEqual(['w1', 'w2']);
|
||||||
|
expect(ctx.breaks.map((e) => e.id)).toEqual(['b1']);
|
||||||
|
expect(ctx.dayStart).toBe(`${DAY}T00:00:00Z`);
|
||||||
|
// `T24:00` normalizes to the next day's midnight
|
||||||
|
expect(ctx.dayEnd).toBe(`2026-07-15T00:00:00Z`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('excludes the break being re-placed', () => {
|
||||||
|
const ctx = buildDayPlacementContext(
|
||||||
|
[entry('b1', `${DAY}T12:00:00Z`, `${DAY}T12:30:00Z`, 'break')],
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
'b1'
|
||||||
|
);
|
||||||
|
expect(ctx.breaks).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turns entries crossing midnight into walls that shrink the day window', () => {
|
||||||
|
// 22:00 (prev day) - 02:00 spills in; 23:00 - 01:00 (next day) spills out.
|
||||||
|
const ctx = buildDayPlacementContext(
|
||||||
|
[
|
||||||
|
entry('overnight', `${PREV_DAY}T22:00:00Z`, `${DAY}T02:00:00Z`),
|
||||||
|
entry('w1', `${DAY}T09:00:00Z`, `${DAY}T17:00:00Z`),
|
||||||
|
entry('late', `${DAY}T23:00:00Z`, `2026-07-15T01:00:00Z`),
|
||||||
|
],
|
||||||
|
dayStart,
|
||||||
|
dayEnd
|
||||||
|
);
|
||||||
|
// Boundary-crossers are not movable...
|
||||||
|
expect(ctx.work.map((e) => e.id)).toEqual(['w1']);
|
||||||
|
// ...but clamp the usable window so nothing can be shifted into them.
|
||||||
|
expect(ctx.dayStart).toBe(`${DAY}T02:00:00Z`);
|
||||||
|
expect(ctx.dayEnd).toBe(`${DAY}T23:00:00Z`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores entries on other days', () => {
|
||||||
|
const ctx = buildDayPlacementContext(
|
||||||
|
[entry('other-day', `${PREV_DAY}T09:00:00Z`, `${PREV_DAY}T10:00:00Z`)],
|
||||||
|
dayStart,
|
||||||
|
dayEnd
|
||||||
|
);
|
||||||
|
expect(ctx.work).toEqual([]);
|
||||||
|
expect(ctx.breaks).toEqual([]);
|
||||||
|
expect(ctx.blocked).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('turns a running entry into a blocker that caps the day window', () => {
|
||||||
|
const ctx = buildDayPlacementContext(
|
||||||
|
[
|
||||||
|
entry('w1', `${DAY}T06:00:00Z`, `${DAY}T08:00:00Z`),
|
||||||
|
entry('running', `${DAY}T09:00:00Z`, null),
|
||||||
|
],
|
||||||
|
dayStart,
|
||||||
|
dayEnd
|
||||||
|
);
|
||||||
|
// The running entry is not movable, blocks the day from its start on,
|
||||||
|
// and nothing can be shifted to or past it.
|
||||||
|
expect(ctx.work.map((e) => e.id)).toEqual(['w1']);
|
||||||
|
expect(ctx.blocked).toEqual([{ start: `${DAY}T09:00:00Z`, end: dayEnd }]);
|
||||||
|
expect(ctx.dayEnd).toBe(`${DAY}T09:00:00Z`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findValidBreakGapNear', () => {
|
||||||
|
// 09-10 and 11:30-12:30 → a 90-min gap (10:00-11:30). A 1h break has a valid
|
||||||
|
// start window of 10:00-10:30; findValidBreakGap would center it at 10:15.
|
||||||
|
const work = [iv(9, 10), iv(11.5, 12.5)];
|
||||||
|
|
||||||
|
it('keeps the break at its current start instead of recentering', () => {
|
||||||
|
const gap = findValidBreakGapNear(work, HOUR, `${DAY}T10:00:00Z`);
|
||||||
|
expect(gap).toEqual({ start: `${DAY}T10:00:00Z`, end: `${DAY}T11:00:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps the anchor into the tolerance window when it sits too late', () => {
|
||||||
|
// Anchored at 11:00 (beyond the window) → clamped back to 10:30.
|
||||||
|
const gap = findValidBreakGapNear(work, HOUR, `${DAY}T11:00:00Z`);
|
||||||
|
expect(gap).toEqual({ start: `${DAY}T10:30:00Z`, end: `${DAY}T11:30:00Z` });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the break in place inside an oversized gap', () => {
|
||||||
|
// 09-10 and 14-15 → 4h gap. The break stays exactly where the user left it;
|
||||||
|
// its distance from work is a soft hint, not a reason to move it.
|
||||||
|
const wideWork = [iv(9, 10), iv(14, 15)];
|
||||||
|
expect(findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T11:00:00Z`)).toEqual({
|
||||||
|
start: `${DAY}T11:00:00Z`,
|
||||||
|
end: `${DAY}T11:30:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clamps the anchor so the break stays inside the gap', () => {
|
||||||
|
// Anchored at 13:50 in the 10:00-14:00 gap → a 30m break would spill into
|
||||||
|
// the next work entry, so it is clamped back to 13:30-14:00.
|
||||||
|
const wideWork = [iv(9, 10), iv(14, 15)];
|
||||||
|
expect(findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T13:50:00Z`)).toEqual({
|
||||||
|
start: `${DAY}T13:30:00Z`,
|
||||||
|
end: `${DAY}T14:00:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when the anchor's gap can't hold the new duration", () => {
|
||||||
|
// 09-10 and 10:30-12:30 → only a 30-min gap; a 1h break no longer fits.
|
||||||
|
const tightWork = [iv(9, 10), iv(10.5, 12.5)];
|
||||||
|
expect(findValidBreakGapNear(tightWork, HOUR, `${DAY}T10:00:00Z`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when the anchor sits outside every inter-work gap', () => {
|
||||||
|
// Anchor before the first work entry — a genuinely misplaced break, which the
|
||||||
|
// caller then re-places via findValidBreakGap instead.
|
||||||
|
expect(findValidBreakGapNear(work, HOUR, `${DAY}T08:00:00Z`)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null when no free window in the gap can hold the break', () => {
|
||||||
|
// Another break occupies 10:00-11:00; the leftover windows (none before,
|
||||||
|
// 30m after) can't hold a 1h break → fall back to findValidBreakGap.
|
||||||
|
expect(findValidBreakGapNear(work, HOUR, `${DAY}T10:00:00Z`, [iv(10, 11)])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('slides past a neighboring break inside the same gap instead of bailing', () => {
|
||||||
|
// Gap 10:00-12:00 between work; another break sits at 10:30-11:00. Growing
|
||||||
|
// the 10:00 break to 45m no longer fits before it, so it settles right
|
||||||
|
// after the neighbor (11:00) — not in a different gap across the day.
|
||||||
|
const wideWork = [iv(9, 10), iv(12, 13)];
|
||||||
|
expect(findValidBreakGapNear(wideWork, 2700, `${DAY}T10:00:00Z`, [iv(10.5, 11)])).toEqual({
|
||||||
|
start: `${DAY}T11:00:00Z`,
|
||||||
|
end: `${DAY}T11:45:00Z`,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('settles in the free window closest to the anchor', () => {
|
||||||
|
// Gap 10:00-13:00 with obstacles 10:45-11:00 and 11:15-12:30. For a 30m
|
||||||
|
// break anchored at 10:50 the candidates are 10:15 (35m away) and 12:30
|
||||||
|
// (100m away); the middle window is too small.
|
||||||
|
const wideWork = [iv(9, 10), iv(13, 14)];
|
||||||
|
expect(
|
||||||
|
findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T10:50:00Z`, [
|
||||||
|
iv(10.75, 11),
|
||||||
|
iv(11.25, 12.5),
|
||||||
|
])
|
||||||
|
).toEqual({ start: `${DAY}T10:15:00Z`, end: `${DAY}T10:45:00Z` });
|
||||||
|
});
|
||||||
|
});
|
||||||
471
resources/js/utils/timesheet/breakPlacementMath.ts
Normal file
471
resources/js/utils/timesheet/breakPlacementMath.ts
Normal file
@@ -0,0 +1,471 @@
|
|||||||
|
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||||
|
import { BREAK_GAP_TOLERANCE_MINUTES } from '@/packages/ui/src/utils/breakPlacement';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Break placement solver for the timesheet.
|
||||||
|
*
|
||||||
|
* A break only means something sitting between work, ideally within a tolerance
|
||||||
|
* of it on both sides (see BREAK_GAP_TOLERANCE_MINUTES). When a break is added
|
||||||
|
* to a day we first try to drop it into an existing gap without touching any
|
||||||
|
* other entry — preferring a gap where the tolerance holds, but accepting any
|
||||||
|
* gap big enough to hold the break. The tolerance is a soft, read-time hint
|
||||||
|
* (see getBreakPlacementHint), never a reason to rearrange entries the user
|
||||||
|
* tracked deliberately. Only when no gap can physically hold the break does the
|
||||||
|
* caller resolve it via a modal that either splits the single work entry or
|
||||||
|
* moves the surrounding entries to open a slot — always keeping everything
|
||||||
|
* inside the day.
|
||||||
|
*
|
||||||
|
* All timestamps are UTC ISO strings. Shift arithmetic is done in epoch
|
||||||
|
* milliseconds so it is DST-safe (a wall-clock day can be 23h or 25h long).
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const BREAK_GAP_TOLERANCE_SECONDS = BREAK_GAP_TOLERANCE_MINUTES * 60;
|
||||||
|
|
||||||
|
export interface Interval {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MovableInterval extends Interval {
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MovePlan {
|
||||||
|
breakSlot: Interval;
|
||||||
|
// Entries whose start/end changed to make room for the break
|
||||||
|
shifted: MovableInterval[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SplitPlan {
|
||||||
|
firstHalf: Interval;
|
||||||
|
breakSlot: Interval;
|
||||||
|
secondHalf: Interval;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A break that could not be auto-placed within tolerance. The timesheet raises
|
||||||
|
* one of these so the page can open the placement modal, where the user either
|
||||||
|
* splits the single work entry or shifts entries to open a slot.
|
||||||
|
*/
|
||||||
|
export interface BreakPlacementRequest {
|
||||||
|
date: string;
|
||||||
|
durationSeconds: number;
|
||||||
|
dayStart: string;
|
||||||
|
dayEnd: string;
|
||||||
|
// Work entries on the day (finished, movable), used to split or shift
|
||||||
|
workEntries: MovableInterval[];
|
||||||
|
// Existing breaks on the day (minus the one being re-placed). They shift
|
||||||
|
// along with the surrounding work in move mode so a plan can never land
|
||||||
|
// on top of them.
|
||||||
|
otherEntries: MovableInterval[];
|
||||||
|
defaultBreakStart: string;
|
||||||
|
// When re-placing an existing break (an edit), the id to update in place
|
||||||
|
replaceBreakId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a request will be resolved: a single work entry is split around the
|
||||||
|
* break; with several, the surrounding entries move to open a slot.
|
||||||
|
*/
|
||||||
|
export function placementMode(request: BreakPlacementRequest): 'split' | 'move' {
|
||||||
|
return request.workEntries.length === 1 ? 'split' : 'move';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The minimal shape of a time entry the day-context builder needs. */
|
||||||
|
export interface DayEntryLike {
|
||||||
|
id: string;
|
||||||
|
start: string;
|
||||||
|
end: string | null;
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything the placement flow needs to know about one local day:
|
||||||
|
* finished work and break entries fully inside the day (both movable), and the
|
||||||
|
* usable day window. Entries that reach across a day boundary belong partly to
|
||||||
|
* another day and must not be moved — they shrink `dayStart`/`dayEnd` instead,
|
||||||
|
* so no plan can shift anything into them.
|
||||||
|
*/
|
||||||
|
export interface DayPlacementContext {
|
||||||
|
work: MovableInterval[];
|
||||||
|
breaks: MovableInterval[];
|
||||||
|
// Immovable blockers: a running entry keeps growing from its start, so it
|
||||||
|
// blocks placement from there through the end of the day.
|
||||||
|
blocked: Interval[];
|
||||||
|
dayStart: string;
|
||||||
|
dayEnd: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildDayPlacementContext(
|
||||||
|
entries: DayEntryLike[],
|
||||||
|
dayStart: string,
|
||||||
|
dayEnd: string,
|
||||||
|
excludeBreakId: string | null = null
|
||||||
|
): DayPlacementContext {
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const dayStartMs = dayjs.utc(dayStart).valueOf();
|
||||||
|
const dayEndMs = dayjs.utc(dayEnd).valueOf();
|
||||||
|
let effStartMs = dayStartMs;
|
||||||
|
let effEndMs = dayEndMs;
|
||||||
|
const work: MovableInterval[] = [];
|
||||||
|
const breaks: MovableInterval[] = [];
|
||||||
|
const blocked: Interval[] = [];
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.id === excludeBreakId) continue;
|
||||||
|
const startMs = dayjs.utc(entry.start).valueOf();
|
||||||
|
// A running entry keeps growing from its start: nothing can be placed
|
||||||
|
// at or after it, so it caps the usable window and blocks the rest of
|
||||||
|
// the day instead of being movable.
|
||||||
|
if (entry.end === null) {
|
||||||
|
if (startMs < dayEndMs) {
|
||||||
|
if (startMs < effEndMs) effEndMs = startMs;
|
||||||
|
blocked.push({ start: entry.start, end: dayEnd });
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const endMs = dayjs.utc(entry.end).valueOf();
|
||||||
|
if (startMs >= dayEndMs || endMs <= dayStartMs) continue;
|
||||||
|
|
||||||
|
const crossesStart = startMs < dayStartMs;
|
||||||
|
const crossesEnd = endMs > dayEndMs;
|
||||||
|
if (crossesStart || crossesEnd) {
|
||||||
|
if (crossesStart && endMs > effStartMs) effStartMs = endMs;
|
||||||
|
if (crossesEnd && startMs < effEndMs) effEndMs = startMs;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const interval = { id: entry.id, start: entry.start, end: entry.end };
|
||||||
|
if (entry.type === 'break') {
|
||||||
|
breaks.push(interval);
|
||||||
|
} else {
|
||||||
|
work.push(interval);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
work: sortByStart(work),
|
||||||
|
breaks: sortByStart(breaks),
|
||||||
|
blocked: sortByStart(blocked),
|
||||||
|
dayStart: dayjs.utc(effStartMs).format(),
|
||||||
|
dayEnd: dayjs.utc(effEndMs).format(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortByStart<T extends Interval>(intervals: T[]): T[] {
|
||||||
|
return [...intervals].sort((a, b) => a.start.localeCompare(b.start));
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IntervalMs {
|
||||||
|
startMs: number;
|
||||||
|
endMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toIntervalMs(interval: Interval): IntervalMs {
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
return {
|
||||||
|
startMs: dayjs.utc(interval.start).valueOf(),
|
||||||
|
endMs: dayjs.utc(interval.end).valueOf(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge overlapping/touching work intervals so the space between two
|
||||||
|
* consecutive merged intervals is genuinely work-free. Without this, an entry
|
||||||
|
* contained in a longer one would fabricate a "gap" that overlaps work.
|
||||||
|
*/
|
||||||
|
function mergedWorkMs(work: Interval[]): IntervalMs[] {
|
||||||
|
const sorted = work.map(toIntervalMs).sort((a, b) => a.startMs - b.startMs);
|
||||||
|
const merged: IntervalMs[] = [];
|
||||||
|
for (const current of sorted) {
|
||||||
|
const last = merged[merged.length - 1];
|
||||||
|
if (last && current.startMs <= last.endMs) {
|
||||||
|
last.endMs = Math.max(last.endMs, current.endMs);
|
||||||
|
} else {
|
||||||
|
merged.push({ ...current });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Work-free gaps between consecutive merged work intervals, in day order. */
|
||||||
|
function workFreeGapsMs(work: Interval[]): IntervalMs[] {
|
||||||
|
const merged = mergedWorkMs(work);
|
||||||
|
const gaps: IntervalMs[] = [];
|
||||||
|
for (let i = 0; i < merged.length - 1; i++) {
|
||||||
|
gaps.push({ startMs: merged[i]!.endMs, endMs: merged[i + 1]!.startMs });
|
||||||
|
}
|
||||||
|
return gaps;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a gap between work entries that can hold a break of `durationSeconds`,
|
||||||
|
* without touching any other entry.
|
||||||
|
*
|
||||||
|
* Preference order: first a gap where the centered break stays within
|
||||||
|
* `toleranceSeconds` of work on both sides. When no such gap exists, any gap
|
||||||
|
* big enough to physically hold the break is accepted — the break is placed
|
||||||
|
* flush after the preceding work (sliding past obstacles such as existing
|
||||||
|
* breaks) and the rest of the gap is left untouched. Such a break may end up
|
||||||
|
* further from work than the tolerance; that is surfaced as a read-time hint
|
||||||
|
* (getBreakPlacementHint), not treated as infeasible. Returns null only when
|
||||||
|
* no work-free gap can hold the break at all.
|
||||||
|
*/
|
||||||
|
export function findValidBreakGap(
|
||||||
|
work: Interval[],
|
||||||
|
durationSeconds: number,
|
||||||
|
obstacles: Interval[] = [],
|
||||||
|
toleranceSeconds: number = BREAK_GAP_TOLERANCE_SECONDS
|
||||||
|
): Interval | null {
|
||||||
|
if (durationSeconds <= 0) return null;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const durationMs = durationSeconds * 1000;
|
||||||
|
const gaps = workFreeGapsMs(work);
|
||||||
|
const obstaclesMs = obstacles.map(toIntervalMs);
|
||||||
|
|
||||||
|
const blockers = (startMs: number): IntervalMs[] =>
|
||||||
|
obstaclesMs.filter((o) => startMs < o.endMs && o.startMs < startMs + durationMs);
|
||||||
|
const slot = (startMs: number): Interval => ({
|
||||||
|
start: dayjs.utc(startMs).format(),
|
||||||
|
end: dayjs.utc(startMs + durationMs).format(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pass 1: a gap where the centered break keeps both sides within tolerance.
|
||||||
|
for (const gap of gaps) {
|
||||||
|
const gapMs = gap.endMs - gap.startMs;
|
||||||
|
if (gapMs < durationMs || gapMs > durationMs + 2 * toleranceSeconds * 1000) continue;
|
||||||
|
const startMs = gap.startMs + Math.floor((gapMs - durationMs) / 2000) * 1000;
|
||||||
|
if (blockers(startMs).length > 0) continue;
|
||||||
|
return slot(startMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 2: any gap that can physically hold the break. Start flush after the
|
||||||
|
// preceding work and slide right past obstacles until the slot is free.
|
||||||
|
for (const gap of gaps) {
|
||||||
|
let startMs = gap.startMs;
|
||||||
|
while (startMs + durationMs <= gap.endMs) {
|
||||||
|
const blocking = blockers(startMs);
|
||||||
|
if (blocking.length === 0) return slot(startMs);
|
||||||
|
startMs = Math.max(...blocking.map((o) => o.endMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-place an existing break as close to `anchorStart` as possible, instead of
|
||||||
|
* jumping to the first gap (which findValidBreakGap does). Only the gap the
|
||||||
|
* anchor currently sits in is considered — the break keeps its position when
|
||||||
|
* that gap can still physically hold the new duration, clamped only to stay
|
||||||
|
* inside the gap (how far it then sits from work is a soft read-time hint, not
|
||||||
|
* a constraint). Obstacles (other breaks) don't evict the break from its gap:
|
||||||
|
* it settles into the free window of the gap closest to the anchor, sliding
|
||||||
|
* just past whatever is in the way. Returns null only when the anchor sits in
|
||||||
|
* no work-free gap or that gap has no free window big enough; the caller then
|
||||||
|
* falls back to findValidBreakGap.
|
||||||
|
*/
|
||||||
|
export function findValidBreakGapNear(
|
||||||
|
work: Interval[],
|
||||||
|
durationSeconds: number,
|
||||||
|
anchorStart: string,
|
||||||
|
obstacles: Interval[] = []
|
||||||
|
): Interval | null {
|
||||||
|
if (durationSeconds <= 0) return null;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const durationMs = durationSeconds * 1000;
|
||||||
|
const anchorMs = dayjs.utc(anchorStart).valueOf();
|
||||||
|
|
||||||
|
for (const gap of workFreeGapsMs(work)) {
|
||||||
|
// The anchor must fall inside this gap for it to be "where the break is".
|
||||||
|
if (anchorMs < gap.startMs || anchorMs >= gap.endMs) continue;
|
||||||
|
if (gap.endMs - gap.startMs < durationMs) return null;
|
||||||
|
|
||||||
|
// Walk the gap's free windows around obstacles and pick the start
|
||||||
|
// closest to the anchor, so the break moves as little as possible
|
||||||
|
// from where the user left it.
|
||||||
|
const blockers = obstacles
|
||||||
|
.map(toIntervalMs)
|
||||||
|
.filter((o) => o.startMs < gap.endMs && o.endMs > gap.startMs)
|
||||||
|
.sort((a, b) => a.startMs - b.startMs);
|
||||||
|
let best: number | null = null;
|
||||||
|
const consider = (winStartMs: number, winEndMs: number) => {
|
||||||
|
if (winEndMs - winStartMs < durationMs) return;
|
||||||
|
const candidate = Math.min(Math.max(anchorMs, winStartMs), winEndMs - durationMs);
|
||||||
|
if (best === null || Math.abs(candidate - anchorMs) < Math.abs(best - anchorMs)) {
|
||||||
|
best = candidate;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let cursor = gap.startMs;
|
||||||
|
for (const blocker of blockers) {
|
||||||
|
consider(cursor, blocker.startMs);
|
||||||
|
cursor = Math.max(cursor, blocker.endMs);
|
||||||
|
}
|
||||||
|
consider(cursor, gap.endMs);
|
||||||
|
|
||||||
|
if (best === null) return null;
|
||||||
|
return { start: dayjs.utc(best).format(), end: dayjs.utc(best + durationMs).format() };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A split must leave a meaningful chunk of work on each side of the break;
|
||||||
|
// hair-thin fragments would only exist to make a bad placement "fit".
|
||||||
|
export const MIN_SPLIT_FRAGMENT_SECONDS = 60;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split a single work entry to insert a break. `breakStart` (UTC ISO) lets the
|
||||||
|
* caller position it; without one the break is centered. Returns null when the
|
||||||
|
* entry is too short to leave at least MIN_SPLIT_FRAGMENT_SECONDS of work on
|
||||||
|
* both sides of the break, or when an explicit `breakStart` would not — an
|
||||||
|
* out-of-range request is rejected rather than clamped, because silently
|
||||||
|
* relocating the break would contradict the time the user picked.
|
||||||
|
*/
|
||||||
|
export function planSplitEntry(
|
||||||
|
entry: Interval,
|
||||||
|
durationSeconds: number,
|
||||||
|
breakStart?: string
|
||||||
|
): SplitPlan | null {
|
||||||
|
if (durationSeconds <= 0) return null;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const entryStart = dayjs.utc(entry.start);
|
||||||
|
const entryEnd = dayjs.utc(entry.end);
|
||||||
|
const total = entryEnd.diff(entryStart, 'second');
|
||||||
|
if (total < durationSeconds + 2 * MIN_SPLIT_FRAGMENT_SECONDS) return null;
|
||||||
|
|
||||||
|
const earliest = entryStart.add(MIN_SPLIT_FRAGMENT_SECONDS, 'second');
|
||||||
|
const latest = entryEnd.subtract(durationSeconds + MIN_SPLIT_FRAGMENT_SECONDS, 'second');
|
||||||
|
|
||||||
|
let bStart = breakStart
|
||||||
|
? dayjs.utc(breakStart)
|
||||||
|
: entryStart.add(Math.floor((total - durationSeconds) / 2), 'second');
|
||||||
|
|
||||||
|
if (breakStart) {
|
||||||
|
if (bStart.isBefore(earliest) || bStart.isAfter(latest)) return null;
|
||||||
|
} else {
|
||||||
|
// Safety net for rounding of the centered position only.
|
||||||
|
if (bStart.isBefore(earliest)) bStart = earliest;
|
||||||
|
if (bStart.isAfter(latest)) bStart = latest;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bEnd = bStart.add(durationSeconds, 'second');
|
||||||
|
if (!bStart.isAfter(entryStart) || !bEnd.isBefore(entryEnd)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
firstHalf: { start: entryStart.format(), end: bStart.format() },
|
||||||
|
breakSlot: { start: bStart.format(), end: bEnd.format() },
|
||||||
|
secondHalf: { start: bEnd.format(), end: entryEnd.format() },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a break at `breakStart`, shifting the surrounding entries only as much
|
||||||
|
* as needed to clear the slot. Entries starting before the break form the left
|
||||||
|
* block: when it reaches into the slot it is translated earlier so its latest
|
||||||
|
* end meets the break start. The rest form the right block: when the slot
|
||||||
|
* reaches into it, it is translated later so its earliest start meets the break
|
||||||
|
* end. Blocks that already clear the slot are left untouched — existing gaps
|
||||||
|
* are preserved, never tightened. Returns null if a required shift would push
|
||||||
|
* an entry outside `[dayStart, dayEnd]`.
|
||||||
|
*/
|
||||||
|
export function planMoveInsert(
|
||||||
|
entries: MovableInterval[],
|
||||||
|
dayStart: string,
|
||||||
|
dayEnd: string,
|
||||||
|
breakStart: string,
|
||||||
|
durationSeconds: number
|
||||||
|
): MovePlan | null {
|
||||||
|
if (durationSeconds <= 0) return null;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const bStartMs = dayjs.utc(breakStart).valueOf();
|
||||||
|
const bEndMs = bStartMs + durationSeconds * 1000;
|
||||||
|
const dayStartMs = dayjs.utc(dayStart).valueOf();
|
||||||
|
const dayEndMs = dayjs.utc(dayEnd).valueOf();
|
||||||
|
if (bStartMs < dayStartMs || bEndMs > dayEndMs) return null;
|
||||||
|
|
||||||
|
const toMs = (iso: string) => dayjs.utc(iso).valueOf();
|
||||||
|
const left = entries.filter((e) => toMs(e.start) < bStartMs);
|
||||||
|
const right = entries.filter((e) => toMs(e.start) >= bStartMs);
|
||||||
|
|
||||||
|
const shifted: MovableInterval[] = [];
|
||||||
|
const translate = (block: MovableInterval[], shiftMs: number) => {
|
||||||
|
for (const e of block) {
|
||||||
|
shifted.push({
|
||||||
|
id: e.id,
|
||||||
|
start: dayjs.utc(toMs(e.start) + shiftMs).format(),
|
||||||
|
end: dayjs.utc(toMs(e.end) + shiftMs).format(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (left.length > 0) {
|
||||||
|
const maxLeftEnd = Math.max(...left.map((e) => toMs(e.end)));
|
||||||
|
const minLeftStart = Math.min(...left.map((e) => toMs(e.start)));
|
||||||
|
// Only pull earlier when the block overlaps the slot, never later.
|
||||||
|
const shift = Math.min(0, bStartMs - maxLeftEnd);
|
||||||
|
if (shift !== 0) {
|
||||||
|
if (minLeftStart + shift < dayStartMs) return null;
|
||||||
|
translate(left, shift);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (right.length > 0) {
|
||||||
|
const minRightStart = Math.min(...right.map((e) => toMs(e.start)));
|
||||||
|
const maxRightEnd = Math.max(...right.map((e) => toMs(e.end)));
|
||||||
|
// Only push later when the slot overlaps the block, never earlier.
|
||||||
|
const shift = Math.max(0, bEndMs - minRightStart);
|
||||||
|
if (shift !== 0) {
|
||||||
|
if (maxRightEnd + shift > dayEndMs) return null;
|
||||||
|
translate(right, shift);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
breakSlot: {
|
||||||
|
start: dayjs.utc(bStartMs).format(),
|
||||||
|
end: dayjs.utc(bEndMs).format(),
|
||||||
|
},
|
||||||
|
shifted,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pick a feasible default break position for the move case — only reached when
|
||||||
|
* no work-free gap can hold the break, so opening a slot requires shifting.
|
||||||
|
* Only boundaries *between* two consecutive work entries are considered, so the
|
||||||
|
* break always ends up flanked by work (a break before the first entry or after
|
||||||
|
* the last one would be misplaced). For each boundary it tries pushing the
|
||||||
|
* right block later first, then pulling the left block earlier, and returns the
|
||||||
|
* first placement whose shifts stay inside the day. `otherEntries` (existing
|
||||||
|
* breaks) shift along with the work around them. Null when nothing fits.
|
||||||
|
*/
|
||||||
|
export function suggestMovePlan(
|
||||||
|
work: MovableInterval[],
|
||||||
|
dayStart: string,
|
||||||
|
dayEnd: string,
|
||||||
|
durationSeconds: number,
|
||||||
|
otherEntries: MovableInterval[] = []
|
||||||
|
): MovePlan | null {
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const sorted = sortByStart(work);
|
||||||
|
const movable = [...work, ...otherEntries];
|
||||||
|
|
||||||
|
for (let i = 0; i < sorted.length - 1; i++) {
|
||||||
|
// Push the right block later: break starts where the earlier entry ends.
|
||||||
|
const pushRight = planMoveInsert(
|
||||||
|
movable,
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
sorted[i]!.end,
|
||||||
|
durationSeconds
|
||||||
|
);
|
||||||
|
if (pushRight) return pushRight;
|
||||||
|
|
||||||
|
// Pull the left block earlier: break ends where the later entry starts.
|
||||||
|
const before = dayjs
|
||||||
|
.utc(sorted[i + 1]!.start)
|
||||||
|
.subtract(durationSeconds, 'second')
|
||||||
|
.format();
|
||||||
|
const pullLeft = planMoveInsert(movable, dayStart, dayEnd, before, durationSeconds);
|
||||||
|
if (pullLeft) return pullLeft;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ interface Interval {
|
|||||||
end: Dayjs;
|
end: Dayjs;
|
||||||
}
|
}
|
||||||
|
|
||||||
function localDayBounds(date: string, tz: string): { dayStart: Dayjs; dayEnd: Dayjs } {
|
export function localDayBounds(date: string, tz: string): { dayStart: Dayjs; dayEnd: Dayjs } {
|
||||||
const dayjs = getDayJsInstance();
|
const dayjs = getDayJsInstance();
|
||||||
// `.add(1, 'day')` on a Dayjs instance advances by a fixed 24h, which is
|
// `.add(1, 'day')` on a Dayjs instance advances by a fixed 24h, which is
|
||||||
// wrong on DST-transition days (the local day is 23h or 25h long). Derive
|
// wrong on DST-transition days (the local day is 23h or 25h long). Derive
|
||||||
|
|||||||
191
resources/js/utils/timesheet/useBreakPlacement.test.ts
Normal file
191
resources/js/utils/timesheet/useBreakPlacement.test.ts
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import { createPinia, setActivePinia } from 'pinia';
|
||||||
|
import { useBreakPlacement, BreakPlacementDeferred } from './useBreakPlacement';
|
||||||
|
import { api } from '@/packages/api/src';
|
||||||
|
import type { TimeEntry } from '@/packages/api/src';
|
||||||
|
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
|
||||||
|
|
||||||
|
const addNotification = vi.fn();
|
||||||
|
|
||||||
|
vi.mock('@/utils/useUser', () => ({
|
||||||
|
getCurrentOrganizationId: vi.fn(() => 'org-1'),
|
||||||
|
getCurrentMembershipId: vi.fn(() => 'mem-1'),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@tanstack/vue-query', () => ({
|
||||||
|
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/utils/notification', () => ({
|
||||||
|
useNotificationsStore: () => ({ addNotification }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/packages/api/src', () => ({
|
||||||
|
api: {
|
||||||
|
createTimeEntry: vi.fn(async () => ({ data: { id: 'new-id' } })),
|
||||||
|
updateTimeEntry: vi.fn(async () => undefined),
|
||||||
|
deleteTimeEntry: vi.fn(async () => undefined),
|
||||||
|
deleteTimeEntries: vi.fn(async () => undefined),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const apiMocks = vi.mocked(api);
|
||||||
|
const DATE = '2026-04-10';
|
||||||
|
const HOUR = 3600;
|
||||||
|
|
||||||
|
function entry(start: string, end: string | null, overrides: Partial<TimeEntry> = {}): TimeEntry {
|
||||||
|
return {
|
||||||
|
id: overrides.id ?? `e-${start}`,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
description: '',
|
||||||
|
member_id: 'mem-1',
|
||||||
|
project_id: 'p-1',
|
||||||
|
task_id: null,
|
||||||
|
billable: false,
|
||||||
|
tags: [],
|
||||||
|
type: 'work',
|
||||||
|
...overrides,
|
||||||
|
} as unknown as TimeEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
const breakRow: TimesheetRow = {
|
||||||
|
key: 'break-row',
|
||||||
|
projectId: null,
|
||||||
|
taskId: null,
|
||||||
|
billable: false,
|
||||||
|
tags: [],
|
||||||
|
type: 'break',
|
||||||
|
cells: new Map(),
|
||||||
|
totalSeconds: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
function setup(allEntries: TimeEntry[]) {
|
||||||
|
const createCell = vi.fn(async () => undefined);
|
||||||
|
const updateEntry = vi.fn(async () => undefined);
|
||||||
|
const bp = useBreakPlacement({
|
||||||
|
weekDays: ref([DATE, '2026-04-11', '2026-04-12']),
|
||||||
|
timeEntries: ref(allEntries),
|
||||||
|
requireOrgId: () => 'org-1',
|
||||||
|
createCell,
|
||||||
|
updateEntry,
|
||||||
|
});
|
||||||
|
return { bp, createCell, updateEntry };
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
apiMocks.createTimeEntry.mockClear();
|
||||||
|
apiMocks.updateTimeEntry.mockClear();
|
||||||
|
addNotification.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useBreakPlacement.placeBreak', () => {
|
||||||
|
it('saves the break directly when it drops into a valid gap', async () => {
|
||||||
|
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', {
|
||||||
|
id: 'morning',
|
||||||
|
});
|
||||||
|
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
|
||||||
|
id: 'afternoon',
|
||||||
|
});
|
||||||
|
const { bp } = setup([morning, afternoon]);
|
||||||
|
|
||||||
|
await bp.placeBreak(breakRow, 0, HOUR); // exactly fills the 12:00-13:00 gap
|
||||||
|
|
||||||
|
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(apiMocks.createTimeEntry.mock.calls[0]![0]).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
start: '2026-04-10T12:00:00Z',
|
||||||
|
end: '2026-04-10T13:00:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(bp.breakPlacementRequest.value).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never places a break over a running entry', async () => {
|
||||||
|
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', { id: 'morning' });
|
||||||
|
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
|
||||||
|
id: 'afternoon',
|
||||||
|
});
|
||||||
|
const running = entry('2026-04-10T12:30:00Z', null, { id: 'running' });
|
||||||
|
const { bp } = setup([morning, afternoon, running]);
|
||||||
|
|
||||||
|
// Centered placement (12:15-12:45) would overlap the running entry, so
|
||||||
|
// the break slides to the free part of the gap instead.
|
||||||
|
await bp.placeBreak(breakRow, 0, HOUR / 2);
|
||||||
|
|
||||||
|
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(apiMocks.createTimeEntry.mock.calls[0]![0]).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
start: '2026-04-10T12:00:00Z',
|
||||||
|
end: '2026-04-10T12:30:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defers to the split modal when a single work entry blocks every gap', async () => {
|
||||||
|
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||||
|
const { bp } = setup([work]);
|
||||||
|
|
||||||
|
await expect(bp.placeBreak(breakRow, 0, HOUR)).rejects.toBeInstanceOf(
|
||||||
|
BreakPlacementDeferred
|
||||||
|
);
|
||||||
|
expect(bp.breakPlacementRequest.value).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
durationSeconds: HOUR,
|
||||||
|
replaceBreakId: null,
|
||||||
|
workEntries: [expect.objectContaining({ id: 'w1' })],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useBreakPlacement.applyBreakPlacement (split)', () => {
|
||||||
|
it('shrinks the original, creates the second half, and saves the break', async () => {
|
||||||
|
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||||
|
const { bp, updateEntry } = setup([work]);
|
||||||
|
|
||||||
|
// Open the placement request, then commit the break at noon.
|
||||||
|
await bp.placeBreak(breakRow, 0, HOUR).catch(() => undefined);
|
||||||
|
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
|
||||||
|
|
||||||
|
// Original work shrunk to its first half.
|
||||||
|
expect(updateEntry).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'w1',
|
||||||
|
start: '2026-04-10T09:00:00Z',
|
||||||
|
end: '2026-04-10T12:00:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// Second half of work + the break both created.
|
||||||
|
const created = apiMocks.createTimeEntry.mock.calls.map((c) => c[0]);
|
||||||
|
expect(created).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'work',
|
||||||
|
start: '2026-04-10T13:00:00Z',
|
||||||
|
end: '2026-04-10T17:00:00Z',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: 'break',
|
||||||
|
start: '2026-04-10T12:00:00Z',
|
||||||
|
end: '2026-04-10T13:00:00Z',
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
// Request cleared and a success toast surfaced.
|
||||||
|
expect(bp.breakPlacementRequest.value).toBeNull();
|
||||||
|
expect(addNotification).toHaveBeenCalledWith('success', 'Break added', expect.any(String));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does nothing when there is no pending placement request', async () => {
|
||||||
|
const { bp, updateEntry } = setup([]);
|
||||||
|
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
|
||||||
|
expect(updateEntry).not.toHaveBeenCalled();
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
323
resources/js/utils/timesheet/useBreakPlacement.ts
Normal file
323
resources/js/utils/timesheet/useBreakPlacement.ts
Normal file
@@ -0,0 +1,323 @@
|
|||||||
|
import { ref, type Ref } from 'vue';
|
||||||
|
import { useQueryClient } from '@tanstack/vue-query';
|
||||||
|
import { api, type TimeEntry } from '@/packages/api/src';
|
||||||
|
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||||
|
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
|
||||||
|
import { getCurrentMembershipId } from '@/utils/useUser';
|
||||||
|
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
|
||||||
|
import { useNotificationsStore } from '@/utils/notification';
|
||||||
|
import { localDayBounds, NoFreeWindowError } from './cellMath';
|
||||||
|
import {
|
||||||
|
buildDayPlacementContext,
|
||||||
|
findValidBreakGap,
|
||||||
|
findValidBreakGapNear,
|
||||||
|
placementMode,
|
||||||
|
planMoveInsert,
|
||||||
|
planSplitEntry,
|
||||||
|
suggestMovePlan,
|
||||||
|
type BreakPlacementRequest,
|
||||||
|
type DayPlacementContext,
|
||||||
|
} from './breakPlacementMath';
|
||||||
|
|
||||||
|
/** Signals the caller that a break create/edit is waiting on the placement modal. */
|
||||||
|
export class BreakPlacementDeferred extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('Break placement deferred to modal');
|
||||||
|
this.name = 'BreakPlacementDeferred';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generic entry primitives the break subsystem borrows from the cell-mutation
|
||||||
|
* layer. `createCell` drops an entry in the first free window (used when there
|
||||||
|
* is no work to anchor a break to); `updateEntry`/`requireOrgId` are the shared
|
||||||
|
* API helpers. Keeping them injected avoids a circular dependency and makes the
|
||||||
|
* break flow unit-testable in isolation.
|
||||||
|
*/
|
||||||
|
export interface BreakPlacementDeps {
|
||||||
|
weekDays: Ref<string[]>;
|
||||||
|
timeEntries: Ref<TimeEntry[]>;
|
||||||
|
requireOrgId: () => string;
|
||||||
|
createCell: (
|
||||||
|
row: TimesheetRow,
|
||||||
|
dayIndex: number,
|
||||||
|
totalSeconds: number,
|
||||||
|
afterCursor?: string
|
||||||
|
) => Promise<void>;
|
||||||
|
updateEntry: (entry: TimeEntry) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Break-placement subsystem for the timesheet. Owns the placement-modal request
|
||||||
|
* state and everything that positions a break relative to work — auto-placing it
|
||||||
|
* into a valid gap when one exists, or deferring to the split/move modal when the
|
||||||
|
* day has to be rearranged.
|
||||||
|
*/
|
||||||
|
export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||||
|
const { weekDays, timeEntries, requireOrgId, createCell, updateEntry } = deps;
|
||||||
|
const dayjs = getDayJsInstance();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const notifications = useNotificationsStore();
|
||||||
|
|
||||||
|
// Set when a break needs manual placement; the page shows the modal for it.
|
||||||
|
const breakPlacementRequest = ref<BreakPlacementRequest | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Movable work/breaks on the target local day plus the usable day window.
|
||||||
|
* Entries crossing a day boundary shrink the window instead of being
|
||||||
|
* movable (see buildDayPlacementContext) — the padded timesheet fetch
|
||||||
|
* makes them visible even at the week edges.
|
||||||
|
*/
|
||||||
|
function dayPlacementContext(
|
||||||
|
date: string,
|
||||||
|
tz: string,
|
||||||
|
excludeBreakId?: string
|
||||||
|
): DayPlacementContext {
|
||||||
|
const { dayStart, dayEnd } = localDayBounds(date, tz);
|
||||||
|
return buildDayPlacementContext(
|
||||||
|
timeEntries.value,
|
||||||
|
dayStart.format(),
|
||||||
|
dayEnd.format(),
|
||||||
|
excludeBreakId ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createBreakEntry(start: string, end: string, memberId?: string): Promise<void> {
|
||||||
|
const orgId = requireOrgId();
|
||||||
|
const member = memberId ?? getCurrentMembershipId();
|
||||||
|
if (!member) throw new Error('No member context');
|
||||||
|
await api.createTimeEntry(
|
||||||
|
{
|
||||||
|
member_id: member,
|
||||||
|
project_id: null,
|
||||||
|
task_id: null,
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
billable: false,
|
||||||
|
type: 'break',
|
||||||
|
description: null,
|
||||||
|
tags: [],
|
||||||
|
},
|
||||||
|
{ params: { organization: orgId } }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveBreakEntry(
|
||||||
|
start: string,
|
||||||
|
end: string,
|
||||||
|
replaceBreakId?: string,
|
||||||
|
memberId?: string
|
||||||
|
): Promise<void> {
|
||||||
|
if (replaceBreakId) {
|
||||||
|
const existing = timeEntries.value.find((entry) => entry.id === replaceBreakId);
|
||||||
|
if (!existing) throw new Error('Break to update no longer exists');
|
||||||
|
|
||||||
|
await updateEntry({ ...existing, start, end });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await createBreakEntry(start, end, memberId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Place a break on the day (new, or re-placing an existing one when `replaceBreakId`
|
||||||
|
* is given). Prefers a gap that already satisfies the placement tolerance; otherwise
|
||||||
|
* raises BreakPlacementDeferred so the page opens the modal. With no work to anchor to,
|
||||||
|
* the break is just dropped in / resized in the first free window.
|
||||||
|
*/
|
||||||
|
async function placeBreak(
|
||||||
|
row: TimesheetRow,
|
||||||
|
dayIndex: number,
|
||||||
|
durationSeconds: number,
|
||||||
|
replaceBreakId?: string
|
||||||
|
): Promise<void> {
|
||||||
|
const date = weekDays.value[dayIndex]!;
|
||||||
|
const tz = getUserTimezone();
|
||||||
|
const { work, breaks, blocked, dayStart, dayEnd } = dayPlacementContext(
|
||||||
|
date,
|
||||||
|
tz,
|
||||||
|
replaceBreakId
|
||||||
|
);
|
||||||
|
// Existing breaks block auto-placement into a gap (obstacles), but move
|
||||||
|
// along with the surrounding work when a move plan shifts entries.
|
||||||
|
// Running entries block everything from their start (never movable).
|
||||||
|
const obstacles = [...breaks, ...blocked];
|
||||||
|
|
||||||
|
// On edit, keep the break where it is when its current gap still fits it; only
|
||||||
|
// fall back to the first-gap-centered placement when it can't stay put.
|
||||||
|
const anchorStart = replaceBreakId
|
||||||
|
? (timeEntries.value.find((e) => e.id === replaceBreakId)?.start ?? null)
|
||||||
|
: null;
|
||||||
|
const validGap =
|
||||||
|
(anchorStart !== null
|
||||||
|
? findValidBreakGapNear(work, durationSeconds, anchorStart, obstacles)
|
||||||
|
: null) ?? findValidBreakGap(work, durationSeconds, obstacles);
|
||||||
|
if (validGap) {
|
||||||
|
await saveBreakEntry(validGap.start, validGap.end, replaceBreakId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (work.length === 0) {
|
||||||
|
// No work to sit between: for an edit, resize the break in place; for a new
|
||||||
|
// break, drop it in the first free window. Nothing to align to either way.
|
||||||
|
if (replaceBreakId) {
|
||||||
|
const existing = timeEntries.value.find((e) => e.id === replaceBreakId);
|
||||||
|
if (existing) {
|
||||||
|
const newEnd = dayjs
|
||||||
|
.utc(existing.start)
|
||||||
|
.add(durationSeconds, 'second')
|
||||||
|
.format();
|
||||||
|
await updateEntry({ ...existing, end: newEnd });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await createCell(row, dayIndex, durationSeconds);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode: 'split' | 'move' = work.length === 1 ? 'split' : 'move';
|
||||||
|
const defaultBreakStart =
|
||||||
|
mode === 'split'
|
||||||
|
? (planSplitEntry(work[0]!, durationSeconds)?.breakSlot.start ?? null)
|
||||||
|
: (suggestMovePlan(work, dayStart, dayEnd, durationSeconds, breaks)?.breakSlot
|
||||||
|
.start ?? null);
|
||||||
|
|
||||||
|
if (!defaultBreakStart) {
|
||||||
|
// Even splitting/moving can't open a slot on this day.
|
||||||
|
throw new NoFreeWindowError(date, durationSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
|
breakPlacementRequest.value = {
|
||||||
|
date,
|
||||||
|
durationSeconds,
|
||||||
|
dayStart,
|
||||||
|
dayEnd,
|
||||||
|
workEntries: work,
|
||||||
|
otherEntries: breaks,
|
||||||
|
defaultBreakStart,
|
||||||
|
replaceBreakId: replaceBreakId ?? null,
|
||||||
|
};
|
||||||
|
throw new BreakPlacementDeferred();
|
||||||
|
}
|
||||||
|
|
||||||
|
function dismissBreakPlacement(): void {
|
||||||
|
breakPlacementRequest.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commit a break at `breakStart` by executing the split or move plan. Shifts
|
||||||
|
* happen before the break is saved so its target slot is free first.
|
||||||
|
*/
|
||||||
|
async function applyBreakPlacement(breakStart: string, durationSeconds: number): Promise<void> {
|
||||||
|
const req = breakPlacementRequest.value;
|
||||||
|
if (!req) return;
|
||||||
|
|
||||||
|
// The timesheet is the current member's own, so all created/edited entries stay with them.
|
||||||
|
const memberId = getCurrentMembershipId();
|
||||||
|
if (!memberId) throw new Error('No member context');
|
||||||
|
|
||||||
|
let entriesAdjusted = true;
|
||||||
|
try {
|
||||||
|
if (placementMode(req) === 'split') {
|
||||||
|
const original = timeEntries.value.find((e) => e.id === req.workEntries[0]!.id);
|
||||||
|
const plan = planSplitEntry(req.workEntries[0]!, durationSeconds, breakStart);
|
||||||
|
if (!original || !plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||||
|
// Shrink the original to the first half, then add the second half + break.
|
||||||
|
await updateEntry({
|
||||||
|
...original,
|
||||||
|
start: plan.firstHalf.start,
|
||||||
|
end: plan.firstHalf.end,
|
||||||
|
});
|
||||||
|
await api.createTimeEntry(
|
||||||
|
{
|
||||||
|
member_id: memberId,
|
||||||
|
project_id: original.project_id,
|
||||||
|
task_id: original.task_id,
|
||||||
|
start: plan.secondHalf.start,
|
||||||
|
end: plan.secondHalf.end,
|
||||||
|
billable: original.billable,
|
||||||
|
type: 'work',
|
||||||
|
description: original.description ?? null,
|
||||||
|
tags: original.tags ?? [],
|
||||||
|
},
|
||||||
|
{ params: { organization: requireOrgId() } }
|
||||||
|
);
|
||||||
|
await saveBreakEntry(
|
||||||
|
plan.breakSlot.start,
|
||||||
|
plan.breakSlot.end,
|
||||||
|
req.replaceBreakId ?? undefined,
|
||||||
|
memberId
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const plan = planMoveInsert(
|
||||||
|
[...req.workEntries, ...req.otherEntries],
|
||||||
|
req.dayStart,
|
||||||
|
req.dayEnd,
|
||||||
|
breakStart,
|
||||||
|
durationSeconds
|
||||||
|
);
|
||||||
|
if (!plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||||
|
entriesAdjusted = plan.shifted.length > 0;
|
||||||
|
// Order the shifts so no intermediate step overlaps (matters when the org
|
||||||
|
// prevents overlapping entries): entries moving earlier are updated left-to-right,
|
||||||
|
// entries moving later right-to-left, so each one vacates before its neighbour moves.
|
||||||
|
const shifts = plan.shifted
|
||||||
|
.map((shift) => ({
|
||||||
|
shift,
|
||||||
|
original: timeEntries.value.find((e) => e.id === shift.id),
|
||||||
|
}))
|
||||||
|
.filter(
|
||||||
|
(x): x is { shift: (typeof plan.shifted)[number]; original: TimeEntry } =>
|
||||||
|
!!x.original
|
||||||
|
);
|
||||||
|
const movingEarlier = shifts
|
||||||
|
.filter((x) => x.shift.start < x.original.start)
|
||||||
|
.sort((a, b) => a.original.start.localeCompare(b.original.start));
|
||||||
|
const movingLater = shifts
|
||||||
|
.filter((x) => x.shift.start >= x.original.start)
|
||||||
|
.sort((a, b) => b.original.start.localeCompare(a.original.start));
|
||||||
|
for (const { shift, original } of [...movingEarlier, ...movingLater]) {
|
||||||
|
await updateEntry({ ...original, start: shift.start, end: shift.end });
|
||||||
|
}
|
||||||
|
await saveBreakEntry(
|
||||||
|
plan.breakSlot.start,
|
||||||
|
plan.breakSlot.end,
|
||||||
|
req.replaceBreakId ?? undefined,
|
||||||
|
memberId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
notifications.addNotification(
|
||||||
|
'success',
|
||||||
|
req.replaceBreakId ? 'Break updated' : 'Break added',
|
||||||
|
entriesAdjusted
|
||||||
|
? 'Your entries were adjusted to make room for the break.'
|
||||||
|
: 'The break was added at the selected time.'
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof NoFreeWindowError) {
|
||||||
|
notifications.addNotification(
|
||||||
|
'error',
|
||||||
|
"This day can't fit the break",
|
||||||
|
'Try a shorter break or a different time.'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
notifications.addNotification(
|
||||||
|
'error',
|
||||||
|
'Failed to add break',
|
||||||
|
'Please try again later.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
breakPlacementRequest.value = null;
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
breakPlacementRequest,
|
||||||
|
placeBreak,
|
||||||
|
dismissBreakPlacement,
|
||||||
|
applyBreakPlacement,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -41,8 +41,10 @@ export function useCopyLastWeek(
|
|||||||
projectId: string | null,
|
projectId: string | null,
|
||||||
taskId: string | null,
|
taskId: string | null,
|
||||||
billable: boolean,
|
billable: boolean,
|
||||||
tags: string[]
|
tags: string[],
|
||||||
) => string
|
type?: 'work' | 'break'
|
||||||
|
) => string,
|
||||||
|
breaksEnabled: Ref<boolean>
|
||||||
) {
|
) {
|
||||||
const dayjs = getDayJsInstance();
|
const dayjs = getDayJsInstance();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -50,6 +52,14 @@ export function useCopyLastWeek(
|
|||||||
|
|
||||||
const isCopyingLastWeek = ref(false);
|
const isCopyingLastWeek = ref(false);
|
||||||
|
|
||||||
|
// The server rejects creating break entries while breaks are disabled,
|
||||||
|
// so leave last week's breaks out of the copy in that case
|
||||||
|
function copyableEntries(response: TimeEntryResponse): TimeEntry[] {
|
||||||
|
return breaksEnabled.value
|
||||||
|
? response.data
|
||||||
|
: response.data.filter((entry) => entry.type !== 'break');
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchLastWeekEntries(): Promise<TimeEntryResponse | null> {
|
async function fetchLastWeekEntries(): Promise<TimeEntryResponse | null> {
|
||||||
const prevStart = weekStart.value.subtract(7, 'day');
|
const prevStart = weekStart.value.subtract(7, 'day');
|
||||||
const prevEnd = weekStart.value;
|
const prevEnd = weekStart.value;
|
||||||
@@ -73,16 +83,22 @@ export function useCopyLastWeek(
|
|||||||
*/
|
*/
|
||||||
function addMissingRowsFromPreviousWeek(prevEntries: TimeEntry[]): void {
|
function addMissingRowsFromPreviousWeek(prevEntries: TimeEntry[]): void {
|
||||||
const existingIdentities = new Set(
|
const existingIdentities = new Set(
|
||||||
rows.value.map((r) => makeRowKey(r.projectId, r.taskId, r.billable, r.tags))
|
rows.value.map((r) => makeRowKey(r.projectId, r.taskId, r.billable, r.tags, r.type))
|
||||||
);
|
);
|
||||||
const addedIdentities = new Set<string>();
|
const addedIdentities = new Set<string>();
|
||||||
|
|
||||||
for (const entry of prevEntries) {
|
for (const entry of prevEntries) {
|
||||||
const tags = entry.tags ?? [];
|
const tags = entry.tags ?? [];
|
||||||
const identity = makeRowKey(entry.project_id, entry.task_id, entry.billable, tags);
|
const identity = makeRowKey(
|
||||||
|
entry.project_id,
|
||||||
|
entry.task_id,
|
||||||
|
entry.billable,
|
||||||
|
tags,
|
||||||
|
entry.type
|
||||||
|
);
|
||||||
if (!existingIdentities.has(identity) && !addedIdentities.has(identity)) {
|
if (!existingIdentities.has(identity) && !addedIdentities.has(identity)) {
|
||||||
addedIdentities.add(identity);
|
addedIdentities.add(identity);
|
||||||
addSlot(entry.project_id, entry.task_id, entry.billable, tags);
|
addSlot(entry.project_id, entry.task_id, entry.billable, tags, entry.type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -92,7 +108,7 @@ export function useCopyLastWeek(
|
|||||||
try {
|
try {
|
||||||
const prev = await fetchLastWeekEntries();
|
const prev = await fetchLastWeekEntries();
|
||||||
if (!prev) return;
|
if (!prev) return;
|
||||||
addMissingRowsFromPreviousWeek(prev.data);
|
addMissingRowsFromPreviousWeek(copyableEntries(prev));
|
||||||
} finally {
|
} finally {
|
||||||
isCopyingLastWeek.value = false;
|
isCopyingLastWeek.value = false;
|
||||||
}
|
}
|
||||||
@@ -110,7 +126,8 @@ export function useCopyLastWeek(
|
|||||||
|
|
||||||
const tz = getUserTimezone();
|
const tz = getUserTimezone();
|
||||||
|
|
||||||
addMissingRowsFromPreviousWeek(prev.data);
|
const prevEntries = copyableEntries(prev);
|
||||||
|
addMissingRowsFromPreviousWeek(prevEntries);
|
||||||
|
|
||||||
const prevWeekStart = weekStart.value.subtract(7, 'day');
|
const prevWeekStart = weekStart.value.subtract(7, 'day');
|
||||||
|
|
||||||
@@ -125,7 +142,7 @@ export function useCopyLastWeek(
|
|||||||
let overlapFailures = 0;
|
let overlapFailures = 0;
|
||||||
let otherFailures = 0;
|
let otherFailures = 0;
|
||||||
|
|
||||||
for (const entry of prev.data) {
|
for (const entry of prevEntries) {
|
||||||
if (!entry.end || !entry.duration) continue;
|
if (!entry.end || !entry.duration) continue;
|
||||||
|
|
||||||
// Map previous-week date → same day-of-week in current week.
|
// Map previous-week date → same day-of-week in current week.
|
||||||
@@ -174,6 +191,7 @@ export function useCopyLastWeek(
|
|||||||
start: window.start,
|
start: window.start,
|
||||||
end: window.end,
|
end: window.end,
|
||||||
billable: entry.billable,
|
billable: entry.billable,
|
||||||
|
type: entry.type,
|
||||||
description: entry.description ?? null,
|
description: entry.description ?? null,
|
||||||
tags: entry.tags ?? [],
|
tags: entry.tags ?? [],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ function buildRow(
|
|||||||
taskId: null,
|
taskId: null,
|
||||||
billable: false,
|
billable: false,
|
||||||
tags: [],
|
tags: [],
|
||||||
|
type: 'work',
|
||||||
cells: new Map([[0, cell]]),
|
cells: new Map([[0, cell]]),
|
||||||
totalSeconds: cell.totalSeconds,
|
totalSeconds: cell.totalSeconds,
|
||||||
};
|
};
|
||||||
@@ -91,6 +92,7 @@ function buildEmptyRow(projectId: string | null, key = `${projectId}:null`): Tim
|
|||||||
taskId: null,
|
taskId: null,
|
||||||
billable: false,
|
billable: false,
|
||||||
tags: [],
|
tags: [],
|
||||||
|
type: 'work',
|
||||||
cells: new Map(),
|
cells: new Map(),
|
||||||
totalSeconds: 0,
|
totalSeconds: 0,
|
||||||
};
|
};
|
||||||
@@ -308,6 +310,144 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('break placement', () => {
|
||||||
|
it('updates an existing break in place when moving it into a valid gap', async () => {
|
||||||
|
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', {
|
||||||
|
id: 'morning',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
|
||||||
|
id: 'afternoon',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const existingBreak = entry('2026-04-10T08:00:00Z', '2026-04-10T08:30:00Z', {
|
||||||
|
id: 'break-1',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const row = buildRow(null, [existingBreak], 'break-row');
|
||||||
|
row.type = 'break';
|
||||||
|
const { cellMutations } = setup([morning, afternoon, existingBreak]);
|
||||||
|
|
||||||
|
await cellMutations.handleCellUpdate(row, 0, HOUR);
|
||||||
|
|
||||||
|
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'break-1',
|
||||||
|
start: '2026-04-10T12:00:00Z',
|
||||||
|
end: '2026-04-10T13:00:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an edited break anchored to its position instead of recentering', async () => {
|
||||||
|
// 09-10 and 11:30-12:30 leave a 90-min gap; a resized 1h break has a valid
|
||||||
|
// window of 10:00-10:30. The break already starts at 10:00, so it must stay
|
||||||
|
// there (10:00-11:00) rather than jump to the centered 10:15-11:15.
|
||||||
|
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
|
||||||
|
id: 'morning',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const afternoon = entry('2026-04-10T11:30:00Z', '2026-04-10T12:30:00Z', {
|
||||||
|
id: 'afternoon',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const existingBreak = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
|
||||||
|
id: 'break-1',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const row = buildRow(null, [existingBreak], 'break-row');
|
||||||
|
row.type = 'break';
|
||||||
|
const { cellMutations } = setup([morning, afternoon, existingBreak]);
|
||||||
|
|
||||||
|
await cellMutations.handleCellUpdate(row, 0, HOUR);
|
||||||
|
|
||||||
|
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'break-1',
|
||||||
|
start: '2026-04-10T10:00:00Z',
|
||||||
|
end: '2026-04-10T11:00:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('grows a multi-break cell by re-placing the latest break, not fragmenting', async () => {
|
||||||
|
// Two breaks share the break cell. Growing the cell total must extend the
|
||||||
|
// latest-ending break (break-b) in place — never create a third break entry.
|
||||||
|
const w1 = entry('2026-04-10T12:00:00Z', '2026-04-10T14:00:00Z', {
|
||||||
|
id: 'w1',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const w2 = entry('2026-04-10T15:00:00Z', '2026-04-10T17:00:00Z', {
|
||||||
|
id: 'w2',
|
||||||
|
type: 'work',
|
||||||
|
});
|
||||||
|
const breakA = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
|
||||||
|
id: 'break-a',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const breakB = entry('2026-04-10T14:00:00Z', '2026-04-10T14:30:00Z', {
|
||||||
|
id: 'break-b',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const row = buildRow(null, [breakA, breakB], 'break-row');
|
||||||
|
row.type = 'break';
|
||||||
|
const { cellMutations } = setup([w1, w2, breakA, breakB]);
|
||||||
|
|
||||||
|
// Cell total 60m → 90m (the extra 30m lands on break-b, taking it to 60m,
|
||||||
|
// which fills the 14:00-15:00 gap).
|
||||||
|
await cellMutations.handleCellUpdate(row, 0, 90 * 60);
|
||||||
|
|
||||||
|
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'break-b',
|
||||||
|
start: '2026-04-10T14:00:00Z',
|
||||||
|
end: '2026-04-10T15:00:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shrinks a multi-break cell by trimming the tail break, not fragmenting', async () => {
|
||||||
|
const breakA = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
|
||||||
|
id: 'break-a',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const breakB = entry('2026-04-10T14:00:00Z', '2026-04-10T14:30:00Z', {
|
||||||
|
id: 'break-b',
|
||||||
|
project_id: null,
|
||||||
|
type: 'break',
|
||||||
|
});
|
||||||
|
const row = buildRow(null, [breakA, breakB], 'break-row');
|
||||||
|
row.type = 'break';
|
||||||
|
const { cellMutations } = setup([breakA, breakB]);
|
||||||
|
|
||||||
|
// Cell total 60m → 40m: trim 20m off the latest break (break-b → 14:00-14:10).
|
||||||
|
await cellMutations.handleCellUpdate(row, 0, 40 * 60);
|
||||||
|
|
||||||
|
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
|
||||||
|
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'break-b',
|
||||||
|
end: '2026-04-10T14:10:00Z',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||||
|
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// ── Extend cell (Phase 2) ──────────────────────────────────────
|
// ── Extend cell (Phase 2) ──────────────────────────────────────
|
||||||
|
|
||||||
describe('extendCell', () => {
|
describe('extendCell', () => {
|
||||||
@@ -426,6 +566,7 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
|
|||||||
taskId: null,
|
taskId: null,
|
||||||
billable: false,
|
billable: false,
|
||||||
tags: [],
|
tags: [],
|
||||||
|
type: 'work',
|
||||||
cells: new Map([[0, cell]]),
|
cells: new Map([[0, cell]]),
|
||||||
totalSeconds: HOUR,
|
totalSeconds: HOUR,
|
||||||
};
|
};
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user