Compare commits

..

1 Commits

Author SHA1 Message Date
Gregor Vostrak
1fbf7b87bb add vouch system requirement for PRs > 50 line changes 2026-07-25 03:50:22 +02:00
192 changed files with 1110 additions and 9920 deletions

12
.github/VOUCHED.td vendored
View File

@@ -14,14 +14,10 @@
# Seeded 2026-07-25 from the authors of every merged pull request. # Seeded 2026-07-25 from the authors of every merged pull request.
agross agross
akolenda
bufferhead-code
candideu candideu
kasparrosin KasparRosin
korridor korridor
nikbucher tasks table sorting Onatcer
onatcer ShrootBuck
shrootbuck smileBeda
smilebeda
thespyder
utlark utlark

View File

@@ -21,7 +21,6 @@ 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
{ {

View File

@@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Enums;
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
enum TimeEntryType: string
{
use LaravelEnumHelper;
case Work = 'work';
case Break = 'break';
}

View File

@@ -6,10 +6,7 @@ namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Throwable; use Throwable;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@@ -33,29 +30,6 @@ class Handler extends ExceptionHandler
$this->reportable(function (Throwable $e): void { $this->reportable(function (Throwable $e): void {
// //
}); });
// A request on an untrusted host (see App\Http\Middleware\TrustHosts)
// otherwise renders as a bare "Bad request." 400. Show a message that
// says how to fix it instead. The framework has already converted the
// SuspiciousOperationException into a BadRequestHttpException by the time
// renderables run, so we match that and inspect the original.
$this->renderable(function (BadRequestHttpException $e, Request $request): ?Response {
$previous = $e->getPrevious();
if (! $previous instanceof SuspiciousOperationException
|| ! str_starts_with($previous->getMessage(), 'Untrusted Host')) {
return null; // any other bad request keeps the default response
}
$message = 'This hostname is not configured for this instance. '
.'Set APP_URL, or add the host to TRUSTED_HOSTS.';
if ($request->expectsJson()) {
return response()->json(['message' => $message], 400);
}
return response()->view('errors.untrusted-host', ['message' => $message], 400);
});
} }
public function render($request, Throwable $e): Response|RedirectResponse public function render($request, Throwable $e): Response|RedirectResponse

View File

@@ -28,9 +28,7 @@ class ExportController extends Controller
$filepath = $exportService->export($organization); $filepath = $exportService->export($organization);
$downloadUrl = Storage::disk(config('filesystems.private')) $downloadUrl = Storage::disk(config('filesystems.private'))
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [ ->temporaryUrl($filepath, Carbon::now()->addMinutes(10));
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"',
]);
return new JsonResponse([ return new JsonResponse([
'success' => true, 'success' => true,

View File

@@ -78,9 +78,6 @@ 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;

View File

@@ -57,7 +57,6 @@ 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);

View File

@@ -112,7 +112,6 @@ 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();

View File

@@ -6,7 +6,6 @@ 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;
@@ -210,7 +209,6 @@ 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();
} }
@@ -336,9 +334,7 @@ class TimeEntryController extends Controller
return response()->json([ return response()->json([
'download_url' => Storage::disk(config('filesystems.private')) 'download_url' => Storage::disk(config('filesystems.private'))
->temporaryUrl($path, now()->addMinutes(5), [ ->temporaryUrl($path, now()->addMinutes(5)),
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
]),
]); ]);
} }
@@ -537,7 +533,7 @@ class TimeEntryController extends Controller
->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename); ->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename);
} else { } else {
Excel::store( Excel::store(
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate, $localizationService), new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate),
$path, $path,
config('filesystems.private'), config('filesystems.private'),
$format->getExportPackageType(), $format->getExportPackageType(),
@@ -549,9 +545,7 @@ class TimeEntryController extends Controller
return response()->json([ return response()->json([
'download_url' => Storage::disk(config('filesystems.private')) 'download_url' => Storage::disk(config('filesystems.private'))
->temporaryUrl($path, now()->addMinutes(5), [ ->temporaryUrl($path, now()->addMinutes(5)),
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
]),
]); ]);
} }
@@ -574,7 +568,6 @@ 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();
} }
@@ -766,19 +759,6 @@ 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;

View File

@@ -15,7 +15,6 @@ use App\Http\Middleware\PreventRequestsDuringMaintenance;
use App\Http\Middleware\RedirectIfAuthenticated; use App\Http\Middleware\RedirectIfAuthenticated;
use App\Http\Middleware\ShareInertiaData; use App\Http\Middleware\ShareInertiaData;
use App\Http\Middleware\TrimStrings; use App\Http\Middleware\TrimStrings;
use App\Http\Middleware\TrustHosts;
use App\Http\Middleware\TrustProxies; use App\Http\Middleware\TrustProxies;
use App\Http\Middleware\ValidateSignature; use App\Http\Middleware\ValidateSignature;
use App\Http\Middleware\VerifyCsrfToken; use App\Http\Middleware\VerifyCsrfToken;
@@ -48,7 +47,6 @@ class Kernel extends HttpKernel
*/ */
protected $middleware = [ protected $middleware = [
ForceHttps::class, ForceHttps::class,
TrustHosts::class,
TrustProxies::class, TrustProxies::class,
HandleCors::class, HandleCors::class,
PreventRequestsDuringMaintenance::class, PreventRequestsDuringMaintenance::class,

View File

@@ -1,56 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as BaseTrustHosts;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Rejects requests whose Host is not trusted, preventing Host-header poisoning of
* generated URLs (password reset, SSO callback, invitations). Trusted = the
* APP_URL host and its subdomains, plus TRUSTED_HOSTS (for multi-host access such
* as a Tailscale name). Health-check endpoints are exempt (probed by IP).
*/
class TrustHosts extends BaseTrustHosts
{
/**
* @return array<int, string|null>
*/
public function hosts(): array
{
/** @var array<int, string> $configured */
$configured = config('app.trusted_hosts', []);
$extra = array_map(function (string $host): string {
$host = trim($host);
// "*.example.com" matches any subdomain, not the apex.
if (str_starts_with($host, '*.')) {
return '^.+\.'.preg_quote(substr($host, 2), '#').'$';
}
return '^'.preg_quote($host, '#').'$';
}, $configured);
return array_merge([$this->allSubdomainsOfApplicationUrl()], $extra);
}
/**
* @param \Closure(Request): Response $next
*/
public function handle(Request $request, $next)
{
// Exempt health checks (probed by IP). Also reset the trusted hosts,
// since Octane leaks the static state across requests.
if ($request->is('health-check/*')) {
Request::setTrustedHosts([]);
return $next($request);
}
return parent::handle($request, $next);
}
}

View File

@@ -51,9 +51,6 @@ 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),
], ],
@@ -128,9 +125,4 @@ 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;
}
} }

View File

@@ -8,7 +8,6 @@ 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;
@@ -178,12 +177,6 @@ class ReportStoreRequest extends BaseFormRequest
'numeric', 'numeric',
'integer', 'integer',
], ],
// Filter by time entry type
'properties.time_entry_type' => [
'nullable',
'string',
Rule::enum(TimeEntryType::class),
],
]; ];
} }
@@ -247,15 +240,6 @@ 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'));

View File

@@ -9,7 +9,6 @@ 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;
@@ -184,11 +183,6 @@ 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',

View File

@@ -7,7 +7,6 @@ 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;
@@ -170,11 +169,6 @@ 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',

View File

@@ -7,7 +7,6 @@ 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;
@@ -156,11 +155,6 @@ 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',

View File

@@ -6,7 +6,6 @@ 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;
@@ -149,11 +148,6 @@ 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',

View File

@@ -4,7 +4,6 @@ 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;
@@ -15,7 +14,6 @@ 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;
/** /**
@@ -26,7 +24,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|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule>> * @return array<string, array<string|ValidationRule>>
*/ */
public function rules(): array public function rules(): array
{ {
@@ -44,7 +42,6 @@ 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');
@@ -63,7 +60,6 @@ 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');
@@ -89,16 +85,6 @@ 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' => [
@@ -110,7 +96,6 @@ 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 {

View File

@@ -4,7 +4,6 @@ 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;
@@ -15,7 +14,6 @@ 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;
/** /**
@@ -26,7 +24,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|\Illuminate\Contracts\Validation\Rule>> * @return array<string, array<string|ValidationRule>>
*/ */
public function rules(): array public function rules(): array
{ {
@@ -56,7 +54,6 @@ 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');
@@ -75,7 +72,6 @@ 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');
@@ -88,13 +84,7 @@ 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' => [
@@ -106,7 +96,6 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
'changes.tags' => [ 'changes.tags' => [
'nullable', 'nullable',
'array', 'array',
'prohibited_if:changes.type,break',
], ],
'changes.tags.*' => [ 'changes.tags.*' => [
'string', 'string',

View File

@@ -4,21 +4,16 @@ 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;
/** /**
@@ -29,19 +24,10 @@ 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|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule|ProhibitedIf|ConditionalRules>> * @return array<string, array<string|ValidationRule>>
*/ */
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' => [
@@ -56,7 +42,6 @@ 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');
@@ -75,7 +60,6 @@ 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');
@@ -98,22 +82,7 @@ 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' => [
@@ -125,7 +94,6 @@ class TimeEntryUpdateRequest extends BaseFormRequest
'tags' => [ 'tags' => [
'nullable', 'nullable',
'array', 'array',
Rule::prohibitedIf($isBreak),
], ],
'tags.*' => [ 'tags.*' => [
'string', 'string',

View File

@@ -57,8 +57,6 @@ 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 */

View File

@@ -50,8 +50,6 @@ 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 */

View File

@@ -47,8 +47,6 @@ 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,
]; ];
} }
} }

View File

@@ -34,7 +34,6 @@ 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
@@ -71,7 +70,6 @@ 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,

View File

@@ -4,7 +4,6 @@ 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;
@@ -29,7 +28,6 @@ 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
@@ -73,20 +71,12 @@ 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',
@@ -94,7 +84,6 @@ 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',
@@ -128,21 +117,6 @@ 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);
@@ -199,16 +173,6 @@ 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>
*/ */

View File

@@ -20,7 +20,6 @@ use App\Service\BillingContract;
use App\Service\IpLookup\IpLookupServiceContract; use App\Service\IpLookup\IpLookupServiceContract;
use App\Service\IpLookup\NoIpLookupService; use App\Service\IpLookup\NoIpLookupService;
use App\Service\PermissionStore; use App\Service\PermissionStore;
use DateTimeInterface;
use Dedoc\Scramble\Scramble; use Dedoc\Scramble\Scramble;
use Dedoc\Scramble\Support\Generator\OpenApi; use Dedoc\Scramble\Support\Generator\OpenApi;
use Dedoc\Scramble\Support\Generator\SecurityScheme; use Dedoc\Scramble\Support\Generator\SecurityScheme;
@@ -30,13 +29,8 @@ use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\StreamedResponse;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
@@ -104,27 +98,6 @@ class AppServiceProvider extends ServiceProvider
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class); $this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
$this->app->bind(BillingContract::class); $this->app->bind(BillingContract::class);
// Storage
// The local driver ignores the ResponseContentDisposition option of temporaryUrl,
// so mirror it through the signed query parameters of the storage route.
$privateDisk = config('filesystems.private');
if (config('filesystems.disks.'.$privateDisk.'.driver') === 'local') {
$disk = Storage::disk($privateDisk);
$disk->serveUsing(function (Request $request, string $path, array $headers) use ($disk): StreamedResponse {
return $disk->response($path, null, $headers, $request->query('disposition', 'inline'));
});
$disk->buildTemporaryUrlsUsing(function (string $path, DateTimeInterface $expiration, array $options) use ($privateDisk): string {
$parameters = array_filter([
'path' => $path,
'disposition' => isset($options['ResponseContentDisposition'])
? Str::before($options['ResponseContentDisposition'], ';')
: null,
]);
return url(URL::temporarySignedRoute('storage.'.$privateDisk, $expiration, $parameters, absolute: false));
});
}
// Routing // Routing
Route::model('member', Member::class); Route::model('member', Member::class);
Route::model('invitation', OrganizationInvitation::class); Route::model('invitation', OrganizationInvitation::class);

View File

@@ -33,8 +33,8 @@ class RouteServiceProvider extends ServiceProvider
} }
return $request->user() return $request->user()
? Limit::perMinute(config('app.api_rate_limit_authenticated_per_minute'))->by($request->user()->id) ? Limit::perMinute(200)->by($request->user()->id)
: Limit::perMinute(config('app.api_rate_limit_guest_per_minute'))->by($request->ip()); : Limit::perMinute(60)->by($request->ip());
}); });
$this->routes(function (): void { $this->routes(function (): void {

View File

@@ -4,7 +4,6 @@ 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;
@@ -155,7 +154,6 @@ 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');
@@ -197,7 +195,6 @@ 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');
@@ -225,8 +222,7 @@ 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 */
@@ -294,7 +290,6 @@ 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);
@@ -438,8 +433,7 @@ 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 and time_entries.organization_id = :organization_id
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
', [ ', [
@@ -448,7 +442,6 @@ 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 = [];

View File

@@ -8,7 +8,6 @@ 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;
@@ -69,8 +68,6 @@ 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.
* *
@@ -132,12 +129,6 @@ 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, reports persisted before that are missing the value and default to "work"
if (property_exists($data, 'timeEntryType')) {
$dto->timeEntryType = $data->timeEntryType !== null ? TimeEntryType::from($data->timeEntryType) : null;
} else {
$dto->timeEntryType = TimeEntryType::Work;
}
return $dto; return $dto;
} }
@@ -166,7 +157,6 @@ 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);

View File

@@ -107,7 +107,6 @@ class ExportService
'end', 'end',
'billable_rate', 'billable_rate',
'billable', 'billable',
'type',
'member_id', 'member_id',
'user_id', 'user_id',
'organization_id', 'organization_id',
@@ -132,7 +131,6 @@ 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,

View File

@@ -5,7 +5,6 @@ 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;
@@ -72,12 +71,8 @@ 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 (! $isBreak && ($record['Client'] ?? '') !== '') { if (($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,
@@ -86,7 +81,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
$projectId = null; $projectId = null;
$project = null; $project = null;
$projectMember = null; $projectMember = null;
if (! $isBreak && $record['Project'] !== '') { if ($record['Project'] !== '') {
$projectId = $this->projectImportHelper->getKey([ $projectId = $this->projectImportHelper->getKey([
'name' => $record['Project'], 'name' => $record['Project'],
'client_id' => $clientId, 'client_id' => $clientId,
@@ -102,7 +97,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
]); ]);
} }
$taskId = null; $taskId = null;
if (! $isBreak && $taskKey !== null && $record[$taskKey] !== '') { if ($taskKey !== null && $record[$taskKey] !== '') {
$taskId = $this->taskImportHelper->getKey([ $taskId = $this->taskImportHelper->getKey([
'name' => $record[$taskKey], 'name' => $record[$taskKey],
'project_id' => $projectId, 'project_id' => $projectId,
@@ -128,12 +123,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
} }
$timeEntry->billable = $record['Billable'] === 'Yes'; $timeEntry->billable = $record['Billable'] === 'Yes';
} }
if ($isBreak) { $timeEntry->tags = $this->getTags($record['Tags']);
// 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

View File

@@ -5,7 +5,6 @@ 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;
@@ -256,14 +255,6 @@ 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;

View File

@@ -23,10 +23,6 @@ class InvitationService
*/ */
public function inviteUser(Organization $organization, string $email, Role $role, User $inviter): OrganizationInvitation public function inviteUser(Organization $organization, string $email, Role $role, User $inviter): OrganizationInvitation
{ {
// Normalize the email so it matches how user emails are stored (see UserService::createUser),
// otherwise a mixed-case invite silently fails to link on registration.
$email = strtolower($email);
if (app(MemberService::class)->isEmailAlreadyMember($organization, $email)) { if (app(MemberService::class)->isEmailAlreadyMember($organization, $email)) {
throw new UserIsAlreadyMemberOfOrganizationApiException; throw new UserIsAlreadyMemberOfOrganizationApiException;
} }
@@ -59,7 +55,7 @@ class InvitationService
$organizations = new Collection; $organizations = new Collection;
$invitations = OrganizationInvitation::query() $invitations = OrganizationInvitation::query()
->whereRaw('lower(email) = ?', [strtolower($user->email)]) ->where('email', $user->email)
->whereNotNull('accepted_at') ->whereNotNull('accepted_at')
->get(); ->get();

View File

@@ -8,14 +8,12 @@ use App\Enums\CurrencyFormat;
use App\Enums\DateFormat; use App\Enums\DateFormat;
use App\Enums\IntervalFormat; use App\Enums\IntervalFormat;
use App\Enums\NumberFormat; use App\Enums\NumberFormat;
use App\Enums\TimeEntryAggregationType;
use App\Enums\TimeFormat; use App\Enums\TimeFormat;
use App\Models\Organization; use App\Models\Organization;
use Brick\Math\BigDecimal; use Brick\Math\BigDecimal;
use Brick\Money\Money; use Brick\Money\Money;
use Carbon\CarbonInterface; use Carbon\CarbonInterface;
use Carbon\CarbonInterval; use Carbon\CarbonInterval;
use Illuminate\Support\Carbon;
class LocalizationService class LocalizationService
{ {
@@ -154,38 +152,6 @@ class LocalizationService
return $date->format($this->dateFormat->toCarbonFormat()); return $date->format($this->dateFormat->toCarbonFormat());
} }
/**
* Time group types have no server-side descriptor; their keys are ISO dates and are
* formatted here instead. A Week key is the first day of that week, so it renders as the
* range it covers. A Year key is already a bare year, so it is returned unchanged - it must
* not be parsed, Carbon reads a four digit string as a time of day.
*/
public function formatTimeGroupKey(?string $key, TimeEntryAggregationType $groupType): ?string
{
if ($key === null) {
return null;
}
if ($groupType === TimeEntryAggregationType::Day) {
return $this->formatDate(Carbon::parse($key));
}
if ($groupType === TimeEntryAggregationType::Week) {
$weekStart = Carbon::parse($key);
return $this->formatDate($weekStart).' - '.$this->formatDate($weekStart->copy()->addDays(6));
}
if ($groupType === TimeEntryAggregationType::Month) {
// Note: the leading "!" resets all fields the format does not name. Without it the
// day of the month is taken from today, and a day that the parsed month does not
// have overflows the date into the next month.
return Carbon::createFromFormat('!Y-m', $key)->format('F Y');
}
return $key;
}
public function setDateFormat(DateFormat $dateFormat): void public function setDateFormat(DateFormat $dateFormat): void
{ {
$this->dateFormat = $dateFormat; $this->dateFormat = $dateFormat;

View File

@@ -4,7 +4,6 @@ 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;
@@ -26,7 +25,6 @@ class TimeEntriesDetailedCsvExport extends CsvExport
'Duration', 'Duration',
'Duration (decimal)', 'Duration (decimal)',
'Billable', 'Billable',
'Break',
'Tags', 'Tags',
]; ];
@@ -60,7 +58,6 @@ 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(', '),
]; ];
} }

View File

@@ -5,7 +5,6 @@ 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;
@@ -107,7 +106,6 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
'Duration', 'Duration',
'Duration (decimal)', 'Duration (decimal)',
'Billable', 'Billable',
'Break',
'Tags', 'Tags',
]; ];
} }
@@ -132,7 +130,6 @@ 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) {
@@ -147,7 +144,6 @@ 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 {

View File

@@ -6,7 +6,6 @@ namespace App\Service\ReportExport;
use App\Enums\ExportFormat; use App\Enums\ExportFormat;
use App\Enums\TimeEntryAggregationType; use App\Enums\TimeEntryAggregationType;
use App\Service\LocalizationService;
use Illuminate\View\View; use Illuminate\View\View;
use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromView; use Maatwebsite\Excel\Concerns\FromView;
@@ -49,8 +48,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
private bool $showBillableRate; private bool $showBillableRate;
private LocalizationService $localization;
/** /**
* @param array{ * @param array{
* grouped_type: string|null, * grouped_type: string|null,
@@ -71,7 +68,7 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
* cost: int|null * cost: int|null
* } $data * } $data
*/ */
public function __construct(array $data, ExportFormat $exportFormat, string $currency, TimeEntryAggregationType $group, TimeEntryAggregationType $subGroup, bool $showBillableRate, LocalizationService $localization) public function __construct(array $data, ExportFormat $exportFormat, string $currency, TimeEntryAggregationType $group, TimeEntryAggregationType $subGroup, bool $showBillableRate)
{ {
$this->data = $data; $this->data = $data;
$this->exportFormat = $exportFormat; $this->exportFormat = $exportFormat;
@@ -79,7 +76,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
$this->group = $group; $this->group = $group;
$this->subGroup = $subGroup; $this->subGroup = $subGroup;
$this->showBillableRate = $showBillableRate; $this->showBillableRate = $showBillableRate;
$this->localization = $localization;
} }
public function view(): View public function view(): View
@@ -91,7 +87,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
'subGroup' => $this->subGroup, 'subGroup' => $this->subGroup,
'exportFormat' => $this->exportFormat, 'exportFormat' => $this->exportFormat,
'showBillableRate' => $this->showBillableRate, 'showBillableRate' => $this->showBillableRate,
'localization' => $this->localization,
]); ]);
} }

View File

@@ -353,13 +353,6 @@ 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)
@@ -511,8 +504,6 @@ 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) {

View File

@@ -5,7 +5,6 @@ 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;
@@ -145,32 +144,6 @@ 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
*/ */

View File

@@ -75,27 +75,6 @@ return [
'url' => env('APP_URL', 'http://localhost'), 'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Trusted Hosts
|--------------------------------------------------------------------------
|
| Additional hostnames (besides the APP_URL host and its subdomains) that
| the application is allowed to respond on. This is needed for multi-host
| setups, e.g. reaching the instance over both a public domain and a
| Tailscale name. A request arriving on any host that is neither APP_URL
| (nor a subdomain of it) nor listed here is rejected, which prevents
| Host-header poisoning of password reset and other out-of-band links.
|
| See App\Http\Middleware\TrustHosts.
|
*/
'trusted_hosts' => array_values(array_filter(array_map(
'trim',
explode(',', (string) env('TRUSTED_HOSTS', ''))
))),
'asset_url' => env('ASSET_URL'), 'asset_url' => env('ASSET_URL'),
'force_https' => (bool) env('APP_FORCE_HTTPS', false), 'force_https' => (bool) env('APP_FORCE_HTTPS', false),
@@ -158,21 +137,6 @@ return [
'pagination_per_page_default' => (int) env('PAGINATION_PER_PAGE_DEFAULT', 15), 'pagination_per_page_default' => (int) env('PAGINATION_PER_PAGE_DEFAULT', 15),
/*
|--------------------------------------------------------------------------
| API Rate Limiting
|--------------------------------------------------------------------------
|
| The number of API requests allowed per minute, counted per user for
| authenticated requests and per IP address for guest requests. These
| limits are only enforced when the application runs in production.
|
*/
'api_rate_limit_authenticated_per_minute' => (int) (env('API_RATE_LIMIT_AUTH_PER_MINUTE') ?: 200),
'api_rate_limit_guest_per_minute' => (int) (env('API_RATE_LIMIT_GUEST_PER_MINUTE') ?: 60),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Encryption Key | Encryption Key

View File

@@ -33,7 +33,6 @@ 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()),
@@ -56,13 +55,6 @@ 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) => [

View File

@@ -4,7 +4,6 @@ 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;
@@ -34,7 +33,6 @@ 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(),
@@ -46,18 +44,6 @@ 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 {

View File

@@ -1,24 +0,0 @@
<?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');
});
}
};

View File

@@ -1,24 +0,0 @@
<?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');
});
}
};

View File

@@ -1,230 +0,0 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function Laravel\Prompts\info as consoleInfo;
return new class extends Migration
{
/**
* PostgreSQL cannot build or drop an index concurrently inside a transaction.
* Keeping this migration non-transactional prevents long write locks in production.
*
* @var bool
*/
public $withinTransaction = false;
/**
* Run the migrations.
*/
public function up(): void
{
// Tenant-scoped client pagination ordered by newest first; also covers the organization FK.
$this->runIndexOperation('create', 'clients_organization_created_id_index', 'CREATE INDEX CONCURRENTLY clients_organization_created_id_index ON clients (organization_id, created_at DESC, id)');
// Tenant-scoped project pagination ordered by newest first; also covers the organization FK.
$this->runIndexOperation('create', 'projects_organization_created_id_index', 'CREATE INDEX CONCURRENTLY projects_organization_created_id_index ON projects (organization_id, created_at DESC, id)');
// Speeds client relationship loads and the FK check when a client is deleted or its ID changes.
$this->runIndexOperation('create', 'projects_client_id_index', 'CREATE INDEX CONCURRENTLY projects_client_id_index ON projects (client_id)');
// Tenant-scoped task pagination ordered by newest first; also covers the organization FK.
$this->runIndexOperation('create', 'tasks_organization_created_id_index', 'CREATE INDEX CONCURRENTLY tasks_organization_created_id_index ON tasks (organization_id, created_at DESC, id)');
// Speeds project task lists and the FK check when a project is deleted or its ID changes.
$this->runIndexOperation('create', 'tasks_project_id_index', 'CREATE INDEX CONCURRENTLY tasks_project_id_index ON tasks (project_id)');
// Tenant-scoped tag pagination ordered by newest first; also covers the organization FK.
$this->runIndexOperation('create', 'tags_organization_created_id_index', 'CREATE INDEX CONCURRENTLY tags_organization_created_id_index ON tags (organization_id, created_at DESC, id)');
// Tenant-scoped report pagination ordered by newest first; also covers the organization FK.
$this->runIndexOperation('create', 'reports_organization_created_id_index', 'CREATE INDEX CONCURRENTLY reports_organization_created_id_index ON reports (organization_id, created_at DESC, id)');
// Tenant-scoped member pagination; the existing (organization_id, user_id) unique index remains for membership lookup.
$this->runIndexOperation('create', 'members_organization_created_id_index', 'CREATE INDEX CONCURRENTLY members_organization_created_id_index ON members (organization_id, created_at DESC, id)');
// Supports reverse user-to-membership lookups and the FK check when a user is deleted or its ID changes.
$this->runIndexOperation('create', 'members_user_id_index', 'CREATE INDEX CONCURRENTLY members_user_id_index ON members (user_id)');
// The existing (project_id, user_id) unique index covers project_id, but member_id and legacy user_id need reverse indexes.
$this->runIndexOperation('create', 'project_members_member_id_index', 'CREATE INDEX CONCURRENTLY project_members_member_id_index ON project_members (member_id)');
$this->runIndexOperation('create', 'project_members_user_id_index', 'CREATE INDEX CONCURRENTLY project_members_user_id_index ON project_members (user_id)');
// Supports organization deletion/current-team cleanup and the FK check on users.current_team_id.
$this->runIndexOperation('create', 'users_current_team_id_index', 'CREATE INDEX CONCURRENTLY users_current_team_id_index ON users (current_team_id)');
// Filament loads the newest audits first; this avoids scanning and sorting the large append-only audit table.
$this->runIndexOperation('create', 'audits_created_at_index', 'CREATE INDEX CONCURRENTLY audits_created_at_index ON audits (created_at DESC)');
// Main tenant time-entry range/pagination path, including its start DESC, id ordering; also covers the organization FK.
$this->runIndexOperation('create', 'time_entries_organization_start_id_index', 'CREATE INDEX CONCURRENTLY time_entries_organization_start_id_index ON time_entries (organization_id, start DESC, id)');
// Filament lists time entries globally by creation time, so the tenant-prefixed index cannot provide this ordering.
$this->runIndexOperation('create', 'time_entries_created_at_index', 'CREATE INDEX CONCURRENTLY time_entries_created_at_index ON time_entries (created_at DESC)');
// Dashboard history is consistently filtered by user and organization, then bounded by start; user first also covers its FK.
$this->runIndexOperation('create', 'time_entries_user_organization_start_index', 'CREATE INDEX CONCURRENTLY time_entries_user_organization_start_index ON time_entries (user_id, organization_id, start)');
// Member timelines, overlap checks, and billable-rate updates start with member_id; also covers its FK.
$this->runIndexOperation('create', 'time_entries_member_start_index', 'CREATE INDEX CONCURRENTLY time_entries_member_start_index ON time_entries (member_id, start)');
// These relationship/filter indexes also prevent full scans for FK checks when parent rows change or are deleted.
$this->runIndexOperation('create', 'time_entries_project_id_index', 'CREATE INDEX CONCURRENTLY time_entries_project_id_index ON time_entries (project_id)');
$this->runIndexOperation('create', 'time_entries_task_id_index', 'CREATE INDEX CONCURRENTLY time_entries_task_id_index ON time_entries (task_id)');
$this->runIndexOperation('create', 'time_entries_client_id_index', 'CREATE INDEX CONCURRENTLY time_entries_client_id_index ON time_entries (client_id)');
// Active-timer checks touch only open entries, so a partial index stays small while serving the hot member_id lookup.
$this->runIndexOperation('create', 'time_entries_active_member_index', 'CREATE INDEX CONCURRENTLY time_entries_active_member_index ON time_entries (member_id) WHERE "end" IS NULL');
// whereJsonContains(tags, tag_id) compiles to JSONB containment, which is supported by a GIN index.
$this->runIndexOperation('create', 'time_entries_tags_gin_index', 'CREATE INDEX CONCURRENTLY time_entries_tags_gin_index ON time_entries USING GIN (tags)');
// Passport already indexes user_id; these indexes cover the other FK used during OAuth client deletion/update.
$this->runIndexOperation('create', 'oauth_access_tokens_client_id_index', 'CREATE INDEX CONCURRENTLY oauth_access_tokens_client_id_index ON oauth_access_tokens (client_id)');
$this->runIndexOperation('create', 'oauth_auth_codes_client_id_index', 'CREATE INDEX CONCURRENTLY oauth_auth_codes_client_id_index ON oauth_auth_codes (client_id)');
// owner_id is already the leading column of oauth_clients_owner_id_owner_type_index.
$this->runIndexOperation('drop', 'oauth_clients_user_id_index', 'DROP INDEX CONCURRENTLY oauth_clients_user_id_index');
// Public report lookup starts with the unique share_secret index; no query filters only by this boolean.
$this->runIndexOperation('drop', 'reports_is_public_index', 'DROP INDEX CONCURRENTLY reports_is_public_index');
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$indexes = [
'clients_organization_created_id_index',
'projects_organization_created_id_index',
'projects_client_id_index',
'tasks_organization_created_id_index',
'tasks_project_id_index',
'tags_organization_created_id_index',
'reports_organization_created_id_index',
'members_organization_created_id_index',
'members_user_id_index',
'project_members_member_id_index',
'project_members_user_id_index',
'users_current_team_id_index',
'audits_created_at_index',
'time_entries_organization_start_id_index',
'time_entries_created_at_index',
'time_entries_user_organization_start_index',
'time_entries_member_start_index',
'time_entries_project_id_index',
'time_entries_task_id_index',
'time_entries_client_id_index',
'time_entries_active_member_index',
'time_entries_tags_gin_index',
'oauth_access_tokens_client_id_index',
'oauth_auth_codes_client_id_index',
];
$concurrently = DB::transactionLevel() === 0 ? ' CONCURRENTLY' : '';
foreach ($indexes as $index) {
$this->runIndexOperation('drop', $index, 'DROP INDEX'.$concurrently.' IF EXISTS '.$index);
}
$this->runIndexOperation('create', 'oauth_clients_user_id_index', 'CREATE INDEX'.$concurrently.' oauth_clients_user_id_index ON oauth_clients (owner_id)');
$this->runIndexOperation('create', 'reports_is_public_index', 'CREATE INDEX'.$concurrently.' reports_is_public_index ON reports (is_public)');
}
private function runIndexOperation(string $operation, string $index, string $statement): void
{
$indexState = $this->indexState($index);
if ($operation === 'create' && $indexState === ['valid' => true, 'ready' => true]) {
$this->writeProgress(sprintf('Skipping index [%s] because it already exists and is valid', $index));
return;
}
if ($operation === 'drop' && $indexState === null) {
$this->writeProgress(sprintf('Skipping index [%s] because it does not exist', $index));
return;
}
if ($operation === 'create' && $indexState !== null) {
$this->writeProgress(sprintf(
'Index [%s] exists but is incomplete (valid=%s, ready=%s); dropping it before rebuilding',
$index,
$indexState['valid'] ? 'true' : 'false',
$indexState['ready'] ? 'true' : 'false',
));
$this->executeIndexStatement(
'drop incomplete',
$index,
(DB::transactionLevel() === 0 ? 'DROP INDEX CONCURRENTLY ' : 'DROP INDEX ').$this->quoteIdentifier($index),
);
}
$this->executeIndexStatement($operation, $index, $statement);
}
private function executeIndexStatement(string $operation, string $index, string $statement): void
{
$startedAt = microtime(true);
$this->writeProgress(sprintf('Starting to %s index [%s]', $operation, $index));
try {
DB::statement($statement);
} catch (Throwable $exception) {
$this->writeProgress(sprintf(
'Failed to %s index [%s] after %.2f seconds: %s',
$operation,
$index,
microtime(true) - $startedAt,
$exception->getMessage(),
));
throw $exception;
}
$this->writeProgress(sprintf(
'Finished %s index [%s] in %.2f seconds',
$operation === 'create' ? 'creating' : 'dropping',
$index,
microtime(true) - $startedAt,
));
}
/**
* @return array{valid: bool, ready: bool}|null
*/
private function indexState(string $index): ?array
{
$state = DB::selectOne(
<<<'SQL'
SELECT pg_index.indisvalid::int AS valid, pg_index.indisready::int AS ready
FROM pg_index
JOIN pg_class ON pg_class.oid = pg_index.indexrelid
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE pg_namespace.nspname = current_schema()
AND pg_class.relname = ?
SQL,
[$index],
);
if ($state === null) {
return null;
}
return [
'valid' => (bool) $state->valid,
'ready' => (bool) $state->ready,
];
}
private function quoteIdentifier(string $identifier): string
{
return DB::connection()->getQueryGrammar()->wrap($identifier);
}
private function writeProgress(string $message): void
{
if (app()->runningUnitTests()) {
return;
}
$message = sprintf('[%s] %s', date(DATE_ATOM), $message);
Log::info($message);
consoleInfo($message);
}
};

View File

@@ -1,278 +0,0 @@
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();
});

View File

@@ -2874,54 +2874,3 @@ 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);
});

View File

@@ -8,7 +8,7 @@ import {
createProjectViaApi, createProjectViaApi,
createPublicProjectViaApi, createPublicProjectViaApi,
} from './utils/api'; } from './utils/api';
import { clearTableState, getTableRowNames } from './utils/table'; import { getTableRowNames } from './utils/table';
async function goToClientsOverview(page: Page) { async function goToClientsOverview(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/clients'); await page.goto(PLAYWRIGHT_BASE_URL + '/clients');
@@ -210,12 +210,18 @@ test('test that client context menu delete deletes the client', async ({ page, c
// Sorting Tests // Sorting Tests
// ============================================= // =============================================
async function clearClientTableState(page: Page) {
await page.evaluate(() => {
localStorage.removeItem('client-table-state');
});
}
test('test that sorting clients by name and status works', async ({ page, ctx }) => { test('test that sorting clients by name and status works', async ({ page, ctx }) => {
await createClientViaApi(ctx, { name: 'AAA SortClient' }); await createClientViaApi(ctx, { name: 'AAA SortClient' });
await createClientViaApi(ctx, { name: 'ZZZ SortClient' }); await createClientViaApi(ctx, { name: 'ZZZ SortClient' });
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('client_table'); const table = page.getByTestId('client_table');
@@ -247,7 +253,7 @@ test('test that sorting clients by project count works', async ({ page, ctx }) =
await createProjectViaApi(ctx, { name: 'Proj2', client_id: clientWithMany.id }); await createProjectViaApi(ctx, { name: 'Proj2', client_id: clientWithMany.id });
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('client_table'); const table = page.getByTestId('client_table');
@@ -268,7 +274,7 @@ test('test that sorting clients by project count works', async ({ page, ctx }) =
test('test that client sort state persists after page reload', async ({ page }) => { test('test that client sort state persists after page reload', async ({ page }) => {
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('client_table'); const table = page.getByTestId('client_table');
@@ -391,7 +397,7 @@ test.describe('Clients Pagination', () => {
); );
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
// Default sort is name asc; first 15 clients (00–14) on page 1. // Default sort is name asc; first 15 clients (00–14) on page 1.
@@ -444,7 +450,7 @@ test.describe('Clients Pagination', () => {
); );
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
await expect(page.getByTestId('client_table')).toBeVisible(); await expect(page.getByTestId('client_table')).toBeVisible();
@@ -464,7 +470,7 @@ test.describe('Clients Pagination', () => {
); );
await goToClientsOverview(page); await goToClientsOverview(page);
await clearTableState(page, 'client-table-state'); await clearClientTableState(page);
await page.reload(); await page.reload();
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 }); await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });

View File

@@ -11,7 +11,7 @@ import {
updateMemberBillableRateViaApi, updateMemberBillableRateViaApi,
updateOrganizationSettingViaApi, updateOrganizationSettingViaApi,
} from './utils/api'; } from './utils/api';
import { clearTableState, getTableRowNames } from './utils/table'; import { getTableRowNames } from './utils/table';
// Tests that invite + accept members need more time // Tests that invite + accept members need more time
test.describe.configure({ timeout: 45000 }); test.describe.configure({ timeout: 45000 });
@@ -779,18 +779,20 @@ test('test that accepted invitation disappears from invitations tab', async ({ p
// Sorting Tests // Sorting Tests
// ============================================= // =============================================
// Helper to clear localStorage before tests that check sorting
async function clearMemberTableState(page: Page) {
await page.evaluate(() => {
localStorage.removeItem('member-table-state');
});
}
test('test that sorting members by name, role, and status works', async ({ page, ctx }) => { test('test that sorting members by name, role, and status works', async ({ page, ctx }) => {
// Create two placeholder members with names that sort predictably around "John Doe". // Create two placeholder members with names that sort predictably around "John Doe"
// Seeded alphabetically a second apart: created_at only has second precision and
// same-second rows fall back to a random UUID order. The spacing is what makes the
// API order (created_at desc: ZZZ, AAA, John) deterministic, so the tie-break
// assertions below are testing the tie-break rather than a coin flip.
await createPlaceholderMemberViaImportApi(ctx, 'AAA SortFirst'); await createPlaceholderMemberViaImportApi(ctx, 'AAA SortFirst');
await page.waitForTimeout(1100);
await createPlaceholderMemberViaImportApi(ctx, 'ZZZ SortLast'); await createPlaceholderMemberViaImportApi(ctx, 'ZZZ SortLast');
await goToMembersPage(page); await goToMembersPage(page);
await clearTableState(page, 'member-table-state'); await clearMemberTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('member_table'); const table = page.getByTestId('member_table');
@@ -812,24 +814,20 @@ test('test that sorting members by name, role, and status works', async ({ page,
const ownerIdx = names.indexOf('John Doe'); const ownerIdx = names.indexOf('John Doe');
const placeholderIdx = names.indexOf('AAA SortFirst'); const placeholderIdx = names.indexOf('AAA SortFirst');
expect(ownerIdx).toBeLessThan(placeholderIdx); expect(ownerIdx).toBeLessThan(placeholderIdx);
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
await roleHeader.click(); // desc: Placeholder first await roleHeader.click(); // desc: Placeholder first
names = await getTableRowNames(table); names = await getTableRowNames(table);
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe')); expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
// -- Status sorting -- // -- Status sorting --
const statusHeader = table.getByText('Status').first(); const statusHeader = table.getByText('Status').first();
await statusHeader.click(); // asc: Active(0) < Inactive(1) await statusHeader.click(); // asc: Active(0) < Inactive(1)
names = await getTableRowNames(table); names = await getTableRowNames(table);
expect(names.indexOf('John Doe')).toBeLessThan(names.indexOf('AAA SortFirst')); expect(names.indexOf('John Doe')).toBeLessThan(names.indexOf('AAA SortFirst'));
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
await statusHeader.click(); // desc: Inactive first await statusHeader.click(); // desc: Inactive first
names = await getTableRowNames(table); names = await getTableRowNames(table);
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe')); expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
// -- Email: just verify sort indicator appears -- // -- Email: just verify sort indicator appears --
const emailHeader = table.getByText('Email').first(); const emailHeader = table.getByText('Email').first();
@@ -839,7 +837,7 @@ test('test that sorting members by name, role, and status works', async ({ page,
test('test that member sort state persists after page reload', async ({ page }) => { test('test that member sort state persists after page reload', async ({ page }) => {
await goToMembersPage(page); await goToMembersPage(page);
await clearTableState(page, 'member-table-state'); await clearMemberTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('member_table'); const table = page.getByTestId('member_table');
@@ -877,7 +875,7 @@ test('test that sorting members by billable rate works', async ({ page, ctx }) =
await updateMemberBillableRateViaApi(ctx, lowRateMember!.id, 5000); await updateMemberBillableRateViaApi(ctx, lowRateMember!.id, 5000);
await goToMembersPage(page); await goToMembersPage(page);
await clearTableState(page, 'member-table-state'); await clearMemberTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('member_table'); const table = page.getByTestId('member_table');

View File

@@ -4,7 +4,7 @@ import { PLAYWRIGHT_BASE_URL, TEST_USER_PASSWORD } from '../playwright/config';
async function goToOrganizationSettings(page) { async function goToOrganizationSettings(page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard'); await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
await page.locator('[data-testid="organization_switcher"]:visible').click(); await page.locator('[data-testid="organization_switcher"]:visible').click();
await page.getByRole('menuitem', { name: 'Organization Settings' }).click(); await page.getByText('Organization Settings').click();
} }
async function createTimeEntry(page, duration: string) { async function createTimeEntry(page, duration: string) {

View File

@@ -13,12 +13,18 @@ import {
archiveProjectViaApi, archiveProjectViaApi,
updateOrganizationSettingViaApi, updateOrganizationSettingViaApi,
} from './utils/api'; } from './utils/api';
import { clearTableState, getSeededRowOrder } from './utils/table';
async function goToProjectsOverview(page: Page) { async function goToProjectsOverview(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/projects'); await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
} }
// Helper to clear localStorage before tests that check persistence
async function clearProjectTableState(page: Page) {
await page.evaluate(() => {
localStorage.removeItem('project-table-state');
});
}
// Create new project via modal // Create new project via modal
test('test that creating and deleting a new project via the modal works', async ({ page }) => { test('test that creating and deleting a new project via the modal works', async ({ page }) => {
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000); const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
@@ -78,7 +84,7 @@ test('test that archiving and unarchiving projects works', async ({ page, ctx })
await createProjectViaApi(ctx, { name: newProjectName }); await createProjectViaApi(ctx, { name: newProjectName });
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 }); await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
@@ -474,7 +480,7 @@ test('test that sorting projects by all columns works', async ({ page, ctx }) =>
}); });
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
await expect(page.getByTestId('project_table')).toBeVisible(); await expect(page.getByTestId('project_table')).toBeVisible();
await expect(page.getByText('AAA Project')).toBeVisible(); await expect(page.getByText('AAA Project')).toBeVisible();
@@ -603,7 +609,7 @@ test('test that filtering projects by status works', async ({ page, ctx }) => {
await createProjectViaApi(ctx, { name: newProjectName }); await createProjectViaApi(ctx, { name: newProjectName });
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 }); await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
@@ -634,7 +640,7 @@ test('test that filtering projects by status works', async ({ page, ctx }) => {
test('test that filter state persists after page reload', async ({ page }) => { test('test that filter state persists after page reload', async ({ page }) => {
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
// Apply Active status filter // Apply Active status filter
@@ -650,96 +656,9 @@ test('test that filter state persists after page reload', async ({ page }) => {
await expect(page.getByTestId('status-filter-badge')).toBeVisible(); await expect(page.getByTestId('status-filter-badge')).toBeVisible();
}); });
test('test that projects without a client or estimate are ordered by name at the bottom', async ({
page,
ctx,
}) => {
// Seeded a second apart: created_at only has second precision and same-second rows
// fall back to a random UUID order. The spacing makes the API order of the clientless
// rows (created_at desc: ZZZ, AAA) deterministic and different from the alphabetical
// order the name tie-break should produce.
await createProjectViaApi(ctx, { name: 'AAA Tiebreak Project' });
await page.waitForTimeout(1100);
await createProjectViaApi(ctx, { name: 'ZZZ Tiebreak Project' });
const clientAardvark = await createClientViaApi(ctx, { name: 'Aardvark Co' });
const clientZulu = await createClientViaApi(ctx, { name: 'Zulu Co' });
const projectM = await createProjectViaApi(ctx, {
name: 'MMM Tiebreak Project',
client_id: clientAardvark.id,
estimated_time: 36000, // 10h, 1h tracked below = 10%
});
await createTimeEntryViaApi(ctx, { duration: '1h', projectId: projectM.id });
const projectN = await createProjectViaApi(ctx, {
name: 'NNN Tiebreak Project',
client_id: clientZulu.id,
estimated_time: 14400, // 4h, 2h tracked below = 50%
});
await createTimeEntryViaApi(ctx, { duration: '2h', projectId: projectN.id });
await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state');
await page.reload();
const table = page.getByTestId('project_table');
await expect(table).toBeVisible();
const seeded = [
'AAA Tiebreak Project',
'MMM Tiebreak Project',
'NNN Tiebreak Project',
'ZZZ Tiebreak Project',
];
const getOrder = () => getSeededRowOrder(table, seeded);
// -- Client: empty rows last in both directions, alphabetical among themselves --
const clientHeader = table.locator('.select-none', { hasText: 'Client' }).first();
await clientHeader.click();
await expect
.poll(getOrder)
.toEqual([
'MMM Tiebreak Project',
'NNN Tiebreak Project',
'AAA Tiebreak Project',
'ZZZ Tiebreak Project',
]);
await clientHeader.click();
await expect
.poll(getOrder)
.toEqual([
'NNN Tiebreak Project',
'MMM Tiebreak Project',
'AAA Tiebreak Project',
'ZZZ Tiebreak Project',
]);
// -- Progress: same, and the first click sorts highest first --
const progressHeader = table.locator('.select-none', { hasText: 'Progress' }).first();
await progressHeader.click();
await expect
.poll(getOrder)
.toEqual([
'NNN Tiebreak Project',
'MMM Tiebreak Project',
'AAA Tiebreak Project',
'ZZZ Tiebreak Project',
]);
await progressHeader.click();
await expect
.poll(getOrder)
.toEqual([
'MMM Tiebreak Project',
'NNN Tiebreak Project',
'AAA Tiebreak Project',
'ZZZ Tiebreak Project',
]);
});
test('test that sort state persists after page reload', async ({ page }) => { test('test that sort state persists after page reload', async ({ page }) => {
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
// Click on Name header twice to sort descending // Click on Name header twice to sort descending
@@ -1195,7 +1114,7 @@ test.describe('Projects Pagination', () => {
); );
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
// Default sort is name asc; first 15 projects (00–14) should be on page 1. // Default sort is name asc; first 15 projects (00–14) should be on page 1.
@@ -1249,7 +1168,7 @@ test.describe('Projects Pagination', () => {
); );
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
await expect(page.getByTestId('project_table')).toBeVisible(); await expect(page.getByTestId('project_table')).toBeVisible();
@@ -1266,7 +1185,7 @@ test.describe('Projects Pagination', () => {
); );
await goToProjectsOverview(page); await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state'); await clearProjectTableState(page);
await page.reload(); await page.reload();
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 }); await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });
@@ -1288,36 +1207,3 @@ test.describe('Projects Pagination', () => {
await expect(page.getByText(prefix + '00')).not.toBeVisible(); await expect(page.getByText(prefix + '00')).not.toBeVisible();
}); });
}); });
test('test that searching projects by name works', async ({ page, ctx }) => {
const suffix = Math.floor(1 + Math.random() * 10000);
const matchingProjectName = 'Searchable Project ' + suffix;
const otherProjectName = 'Unrelated Work ' + suffix;
await createProjectViaApi(ctx, { name: matchingProjectName });
await createProjectViaApi(ctx, { name: otherProjectName });
await goToProjectsOverview(page);
await clearTableState(page, 'project-table-state');
await page.reload();
await expect(page.getByText(matchingProjectName)).toBeVisible({ timeout: 10000 });
await expect(page.getByText(otherProjectName)).toBeVisible();
const searchInput = page.getByRole('searchbox', { name: 'Search projects' });
// Searching is case insensitive and matches part of the name
await searchInput.fill('SEARCHABLE');
await expect(page.getByText(matchingProjectName)).toBeVisible();
await expect(page.getByText(otherProjectName)).not.toBeVisible();
// A term that matches nothing empties the table
await searchInput.fill('no project has this name');
await expect(page.getByText(matchingProjectName)).not.toBeVisible();
await expect(page.getByText(otherProjectName)).not.toBeVisible();
await expect(page.getByText('No matching projects')).toBeVisible();
await expect(page.getByRole('button', { name: 'Create your First Project' })).not.toBeVisible();
// Clearing the search restores both projects
await searchInput.fill('');
await expect(page.getByText(matchingProjectName)).toBeVisible();
await expect(page.getByText(otherProjectName)).toBeVisible();
});

View File

@@ -10,7 +10,6 @@ import {
createTimeEntryWithTagViaApi, createTimeEntryWithTagViaApi,
createTimeEntryWithBillableStatusViaApi, createTimeEntryWithBillableStatusViaApi,
createBareTimeEntryViaApi, createBareTimeEntryViaApi,
createTimeEntryOnDateViaApi,
createPublicProjectViaApi, createPublicProjectViaApi,
updateOrganizationSettingViaApi, updateOrganizationSettingViaApi,
} from './utils/api'; } from './utils/api';
@@ -842,127 +841,6 @@ test('test that setting group by to current sub group triggers sub group fallbac
await expect(groupBySelects.filter({ hasText: 'Members' }).first()).toBeVisible(); await expect(groupBySelects.filter({ hasText: 'Members' }).first()).toBeVisible();
}); });
test('test that group by date groups the report by day and formats the date labels with organization settings', async ({
page,
ctx,
}) => {
await updateOrganizationSettingViaApi(ctx, { date_format: 'point-separated-d-m-yyyy' });
await createTimeEntryViaApi(ctx, {
description: 'Entry for group by date',
duration: '1h',
});
// Go to reporting page
await goToReporting(page);
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
// Find the "Group by" selects within the reporting table
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
// Default state: group=Project
await groupBySelects.filter({ hasText: 'Project' }).first().click();
const [aggregateResponse] = await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') &&
response.url().includes('group=day') &&
response.status() === 200
),
page.getByRole('option', { name: 'Date', exact: true }).click(),
]);
// Verify the API request contains the correct group parameter
const requestUrl = new URL(aggregateResponse.url());
expect(requestUrl.searchParams.get('group')).toBe('day');
// The row label is rendered in the organization date format (D.M.YYYY)
await expect(
page.getByTestId('reporting_view').getByText(/^\d{1,2}\.\d{1,2}\.\d{4}$/)
).toBeVisible();
await expect(page.getByTestId('reporting_view').getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(
0
);
});
test('test that group by week requests week grouping and does not leak the raw group key', async ({
page,
ctx,
}) => {
await createTimeEntryViaApi(ctx, {
description: 'Entry for group by week',
duration: '1h',
});
await goToReporting(page);
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
await groupBySelects.filter({ hasText: 'Project' }).first().click();
const [aggregateResponse] = await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') &&
response.url().includes('group=week') &&
response.status() === 200
),
page.getByRole('option', { name: 'Week', exact: true }).click(),
]);
const requestUrl = new URL(aggregateResponse.url());
expect(requestUrl.searchParams.get('group')).toBe('week');
// The raw group key is the first day of the week and must not leak through.
await expect(page.getByTestId('reporting_view').getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(
0
);
});
test('test that group by week labels a week spanning new year with a range crossing the year', async ({
page,
ctx,
}) => {
await updateOrganizationSettingViaApi(ctx, { date_format: 'slash-separated-dd-mm-yyyy' });
for (const day of ['2025-12-22', '2025-12-29', '2026-01-05']) {
await createTimeEntryOnDateViaApi(ctx, {
date: new Date(`${day}T09:00:00Z`),
duration: '1h',
description: `Entry for ${day}`,
});
}
// The reporting page keeps its range in session storage, so seed a range spanning new year
// rather than driving the date picker.
await page.addInitScript(() => {
window.sessionStorage.setItem('reporting-start-date', '2025-12-15');
window.sessionStorage.setItem('reporting-end-date', '2026-01-15');
});
await goToReporting(page);
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
await groupBySelects.filter({ hasText: 'Project' }).first().click();
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') &&
response.url().includes('group=week') &&
response.status() === 200
),
page.getByRole('option', { name: 'Week', exact: true }).click(),
]);
const reportingView = page.getByTestId('reporting_view');
await expect(reportingView.getByText('22/12/2025 - 28/12/2025', { exact: true })).toBeVisible();
await expect(reportingView.getByText('29/12/2025 - 04/01/2026', { exact: true })).toBeVisible();
await expect(reportingView.getByText('05/01/2026 - 11/01/2026', { exact: true })).toBeVisible();
await expect(reportingView.getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(0);
});
// ────────────────────────────────────────────────── // ──────────────────────────────────────────────────
// Export Tests // Export Tests
// ────────────────────────────────────────────────── // ──────────────────────────────────────────────────
@@ -1141,24 +1019,3 @@ 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(),
]);
});

View File

@@ -16,7 +16,6 @@ import {
createTimeEntryWithBillableStatusViaApi, createTimeEntryWithBillableStatusViaApi,
createTagViaApi, createTagViaApi,
createReportViaApi, createReportViaApi,
updateOrganizationSettingViaApi,
} from './utils/api'; } from './utils/api';
import { import {
goToReporting, goToReporting,
@@ -69,42 +68,6 @@ test('test that saving a report creates a shared report and its shareable link s
await expect(page.getByText('Total')).toBeVisible(); await expect(page.getByText('Total')).toBeVisible();
}); });
test('test that a shared report grouped by date shows date labels formatted by the organization setting', async ({
page,
ctx,
}) => {
const reportName = 'DateGroupReport ' + Math.floor(Math.random() * 10000);
await updateOrganizationSettingViaApi(ctx, { date_format: 'point-separated-d-m-yyyy' });
await createTimeEntryViaApi(ctx, {
description: 'Entry for date grouping',
duration: '1h',
});
await goToReporting(page);
// Switch the grouping to "Date"
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
await groupBySelects.filter({ hasText: 'Project' }).first().click();
await Promise.all([
page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') &&
response.url().includes('group=day') &&
response.status() === 200
),
page.getByRole('option', { name: 'Date', exact: true }).click(),
]);
const { shareableLink } = await saveAsSharedReport(page, reportName);
// Verify row labels are formatted correctly
await page.goto(shareableLink);
await expect(page.getByText('Total')).toBeVisible();
await expect(page.getByText(/^\d{1,2}\.\d{1,2}\.\d{4}$/)).toBeVisible();
await expect(page.getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(0);
});
test('test that shared report with invalid secret shows no data', async ({ page }) => { test('test that shared report with invalid secret shows no data', async ({ page }) => {
await page.goto(PLAYWRIGHT_BASE_URL + '/shared-report#invalid-secret-value'); await page.goto(PLAYWRIGHT_BASE_URL + '/shared-report#invalid-secret-value');
await expect(page.getByText('No time entries found').first()).toBeVisible(); await expect(page.getByText('No time entries found').first()).toBeVisible();

View File

@@ -3,7 +3,7 @@ import type { Page } from '@playwright/test';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config'; import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { test } from '../playwright/fixtures'; import { test } from '../playwright/fixtures';
import { createTagViaApi } from './utils/api'; import { createTagViaApi } from './utils/api';
import { clearTableState, getTableRowNames } from './utils/table'; import { getTableRowNames } from './utils/table';
async function goToTagsOverview(page: Page) { async function goToTagsOverview(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/tags'); await page.goto(PLAYWRIGHT_BASE_URL + '/tags');
@@ -147,12 +147,18 @@ test('test that tag context menu delete deletes the tag', async ({ page, ctx })
// Sorting Tests // Sorting Tests
// ============================================= // =============================================
async function clearTagTableState(page: Page) {
await page.evaluate(() => {
localStorage.removeItem('tag-table-state');
});
}
test('test that sorting tags by name works', async ({ page, ctx }) => { test('test that sorting tags by name works', async ({ page, ctx }) => {
await createTagViaApi(ctx, { name: 'AAA SortTag' }); await createTagViaApi(ctx, { name: 'AAA SortTag' });
await createTagViaApi(ctx, { name: 'ZZZ SortTag' }); await createTagViaApi(ctx, { name: 'ZZZ SortTag' });
await goToTagsOverview(page); await goToTagsOverview(page);
await clearTableState(page, 'tag-table-state'); await clearTagTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('tag_table'); const table = page.getByTestId('tag_table');
@@ -170,7 +176,7 @@ test('test that sorting tags by name works', async ({ page, ctx }) => {
test('test that tag sort state persists after page reload', async ({ page }) => { test('test that tag sort state persists after page reload', async ({ page }) => {
await goToTagsOverview(page); await goToTagsOverview(page);
await clearTableState(page, 'tag-table-state'); await clearTagTableState(page);
await page.reload(); await page.reload();
const table = page.getByTestId('tag_table'); const table = page.getByTestId('tag_table');

View File

@@ -7,56 +7,13 @@ import {
createPublicProjectViaApi, createPublicProjectViaApi,
createTaskViaApi, createTaskViaApi,
createClientViaApi, createClientViaApi,
createTimeEntryViaApi,
updateOrganizationSettingViaApi, updateOrganizationSettingViaApi,
type TestContext,
} from './utils/api'; } from './utils/api';
import { clearTableState, getTableRowNames } from './utils/table';
async function goToProjectsOverview(page: Page) { async function goToProjectsOverview(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/projects'); await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
} }
async function createSortableTasks(ctx: TestContext) {
const project = await createProjectViaApi(ctx, { name: 'Task Sorting Project' });
const taskA = await createTaskViaApi(ctx, {
name: 'AAA Sorting Task',
project_id: project.id,
estimated_time: 36000,
});
const taskB = await createTaskViaApi(ctx, {
name: 'BBB Sorting Task',
project_id: project.id,
estimated_time: 14400,
});
const taskC = await createTaskViaApi(ctx, {
name: 'CCC Sorting Task',
project_id: project.id,
});
expect(taskA.estimated_time).toBe(36000);
expect(taskB.estimated_time).toBe(14400);
expect(taskC.estimated_time).toBeNull();
await createTimeEntryViaApi(ctx, {
duration: '1h',
projectId: project.id,
taskId: taskA.id,
});
await createTimeEntryViaApi(ctx, {
duration: '2h',
projectId: project.id,
taskId: taskB.id,
});
await createTimeEntryViaApi(ctx, {
duration: '3h',
projectId: project.id,
taskId: taskC.id,
});
return { project, taskA, taskB, taskC };
}
test('test that creating and deleting a new task in a new project works', async ({ page }) => { test('test that creating and deleting a new task in a new project works', async ({ page }) => {
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000); const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
await goToProjectsOverview(page); await goToProjectsOverview(page);
@@ -344,59 +301,6 @@ test('test that creating a new project from the task create modal project dropdo
await expect(page.getByTestId('task_table')).toContainText(newTaskName); await expect(page.getByTestId('task_table')).toContainText(newTaskName);
}); });
// =============================================
// Sorting Tests
// =============================================
test('test that sorting tasks by name, total time and progress works', async ({ page, ctx }) => {
const { project, taskA, taskB, taskC } = await createSortableTasks(ctx);
await goToProjectsOverview(page);
await clearTableState(page, 'task-table-state');
await page.goto(PLAYWRIGHT_BASE_URL + '/projects/' + project.id);
const table = page.getByTestId('task_table');
await expect(table).toBeVisible();
// This project contains only the seeded tasks, so assert the complete order.
const expectOrder = async (expected: string[]) => {
await expect.poll(() => getTableRowNames(table)).toEqual(expected);
};
const clickHeader = async (headerText: string) => {
await table.getByText(headerText).first().click();
};
await expectOrder([taskA.name, taskB.name, taskC.name]);
await clickHeader('Task Name');
await expectOrder([taskC.name, taskB.name, taskA.name]);
await clickHeader('Task Name');
await expectOrder([taskA.name, taskB.name, taskC.name]);
await clickHeader('Total Time');
await expectOrder([taskC.name, taskB.name, taskA.name]);
await clickHeader('Total Time');
await expectOrder([taskA.name, taskB.name, taskC.name]);
await clickHeader('Progress');
await expectOrder([taskB.name, taskA.name, taskC.name]);
await clickHeader('Progress');
await expectOrder([taskA.name, taskB.name, taskC.name]);
});
test('test that task sort state persists after page reload', async ({ page, ctx }) => {
const { project, taskA, taskB, taskC } = await createSortableTasks(ctx);
await goToProjectsOverview(page);
await clearTableState(page, 'task-table-state');
await page.goto(PLAYWRIGHT_BASE_URL + '/projects/' + project.id);
const table = page.getByTestId('task_table');
await expect(table).toBeVisible();
await table.getByText('Progress').first().click();
await expect.poll(() => getTableRowNames(table)).toEqual([taskB.name, taskA.name, taskC.name]);
await page.reload();
// Verify the persisted row order, not just the sort indicator.
await expect.poll(() => getTableRowNames(table)).toEqual([taskB.name, taskA.name, taskC.name]);
});
// ============================================= // =============================================
// Employee Permission Tests // Employee Permission Tests
// ============================================= // =============================================

View File

@@ -50,7 +50,7 @@ async function goToTimeOverview(page: Page) {
async function goToOrganizationSettings(page: Page) { async function goToOrganizationSettings(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard'); await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
await page.locator('[data-testid="organization_switcher"]:visible').click(); await page.locator('[data-testid="organization_switcher"]:visible').click();
await page.getByRole('menuitem', { name: 'Organization Settings' }).click(); await page.getByText('Organization Settings').click();
} }
async function createEmptyTimeEntry(page: Page) { async function createEmptyTimeEntry(page: Page) {
@@ -2303,21 +2303,3 @@ 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 worked time first, then the break portion
await expect(page.getByTestId('day_break_duration').first()).toBeVisible();
await expect(page.getByTestId('day_break_duration').first().locator('..')).toContainText(
'2h 00min work · 0h 30min break'
);
});

View File

@@ -2,15 +2,7 @@ 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 { import { createProjectViaApi, createTaskViaApi, createTimeEntryOnDateViaApi } from './utils/api';
createProjectViaApi,
createTaskViaApi,
createTimeEntryOnDateViaApi,
createTimeEntryWithTimestampsViaApi,
getTimeEntriesViaApi,
updateOrganizationSettingViaApi,
type TestContext,
} from './utils/api';
// ────────────────────────────────────────────────── // ──────────────────────────────────────────────────
// Helpers // Helpers
@@ -66,34 +58,6 @@ function addRowButton(page: Page) {
return page.getByRole('button', { name: /Add row/i }).first(); return page.getByRole('button', { name: /Add row/i }).first();
} }
async function fillBreakCell(page: Page, hours: string, dayIndex = 0) {
const input = page
.locator('[data-testid="timesheet_row"]')
.filter({ has: page.getByText('Break', { exact: true }) })
.locator('[data-testid="timesheet_cell"]')
.nth(dayIndex)
.locator('input');
await input.click();
await input.fill(hours);
return input;
}
function waitForBreakCreated(page: Page) {
return page.waitForResponse(
async (resp) =>
resp.url().includes('/time-entries') &&
resp.request().method() === 'POST' &&
resp.status() === 201 &&
(await resp.json()).data.type === 'break'
);
}
async function getDayEntriesViaApi(ctx: TestContext, day: string) {
return (await getTimeEntriesViaApi(ctx))
.filter((e) => e.start.startsWith(day))
.sort((a, b) => a.start.localeCompare(b.start));
}
async function chooseRowIdentity(page: Page, optionName: string) { async function chooseRowIdentity(page: Page, optionName: string) {
await addRowButton(page).click(); await addRowButton(page).click();
@@ -675,252 +639,3 @@ 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 breakCell = await fillBreakCell(page, '0.5');
await breakCell.press('Enter');
// The placement modal opens with the split preview, naming the entry that
// will be split so the user can recognize it.
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
await expect(page.getByTestId('break_placement_summary')).toContainText(
'No Project · Split me'
);
await Promise.all([
waitForBreakCreated(page),
page.getByRole('button', { name: 'Add break' }).click(),
]);
// The break is inserted without reducing the eight hours of work.
const dayEntries = await getDayEntriesViaApi(ctx, day);
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
['work', `${day}T09:00:00Z`, `${day}T13:00:00Z`],
['break', `${day}T13:00:00Z`, `${day}T13:30:00Z`],
['work', `${day}T13:30:00Z`, `${day}T17:30:00Z`],
]);
});
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 breakCell = await fillBreakCell(page, '0.5');
await Promise.all([waitForBreakCreated(page), breakCell.press('Enter')]);
await expect(page.getByTestId('break_placement_summary')).not.toBeVisible();
const dayEntries = await getDayEntriesViaApi(ctx, day);
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 breakCell = await fillBreakCell(page, '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([
waitForBreakCreated(page),
page.getByRole('button', { name: 'Add break' }).click(),
]);
const dayEntries = await getDayEntriesViaApi(ctx, day);
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
const hint = page.getByRole('button', {
name: 'does not align with your work entries',
});
await expect(hint).toBeVisible();
// The resulting warning 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 breakCell = await fillBreakCell(page, '0.75');
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 breaks = (await getDayEntriesViaApi(ctx, day)).filter((e) => 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`);
});
test('test that editing an adjacent break vacates its old slot before extending work', async ({
page,
ctx,
}) => {
// The existing break must move before work can extend through its old slot.
await updateOrganizationSettingViaApi(ctx, {
breaks_enabled: true,
prevent_overlapping_time_entries: true,
});
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
await createTimeEntryWithTimestampsViaApi(ctx, {
start: `${day}T09:00:00Z`,
end: `${day}T17:00:00Z`,
description: 'Work before break',
});
const breakEntry = await createTimeEntryWithTimestampsViaApi(ctx, {
start: `${day}T17:00:00Z`,
end: `${day}T17:30:00Z`,
type: 'break',
});
await goToTimesheet(page);
await expect(page.getByTestId('timesheet_view')).toBeVisible();
const breakCell = await fillBreakCell(page, '1');
await breakCell.press('Enter');
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
await Promise.all([
page.waitForResponse(
(resp) =>
resp.url().includes(`/time-entries/${breakEntry.id}`) &&
resp.request().method() === 'PUT' &&
resp.status() === 200
),
page.waitForResponse(
async (resp) =>
resp.url().includes('/time-entries') &&
resp.request().method() === 'POST' &&
resp.status() === 201 &&
(await resp.json()).data.type === 'work'
),
page.getByRole('button', { name: 'Add break' }).click(),
]);
const entries = await getDayEntriesViaApi(ctx, day);
expect(entries.map((entry) => [entry.id, entry.type, entry.start, entry.end])).toEqual([
[expect.any(String), 'work', `${day}T09:00:00Z`, `${day}T13:00:00Z`],
[breakEntry.id, 'break', `${day}T13:00:00Z`, `${day}T14:00:00Z`],
[expect.any(String), 'work', `${day}T14:00:00Z`, `${day}T18:00:00Z`],
]);
});

View File

@@ -13,7 +13,6 @@ import {
createProjectViaApi, createProjectViaApi,
createTaskViaApi, createTaskViaApi,
createClientViaApi, createClientViaApi,
createTimeEntryViaApi,
archiveProjectViaApi, archiveProjectViaApi,
markTaskDoneViaApi, markTaskDoneViaApi,
updateOrganizationCurrencyViaWeb, updateOrganizationCurrencyViaWeb,
@@ -376,66 +375,6 @@ 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,
@@ -742,39 +681,3 @@ 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();
});

View File

@@ -357,7 +357,7 @@ export async function createProjectWithClientViaApi(
export async function createTaskViaApi( export async function createTaskViaApi(
ctx: TestContext, ctx: TestContext,
data: { name: string; project_id: string; estimated_time?: number } data: { name: string; project_id: string }
) { ) {
const response = await ctx.request.post( const response = await ctx.request.post(
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/tasks`, `${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/tasks`,
@@ -365,20 +365,12 @@ export async function createTaskViaApi(
data: { data: {
name: data.name, name: data.name,
project_id: data.project_id, project_id: data.project_id,
...(data.estimated_time !== undefined
? { estimated_time: data.estimated_time }
: {}),
}, },
} }
); );
expect(response.status()).toBe(201); expect(response.status()).toBe(201);
const body = await response.json(); const body = await response.json();
return body.data as { return body.data as { id: string; name: string; project_id: string };
id: string;
name: string;
project_id: string;
estimated_time: number | null;
};
} }
export async function markTaskDoneViaApi(ctx: TestContext, task: { id: string; name: string }) { export async function markTaskDoneViaApi(ctx: TestContext, task: { id: string; name: string }) {
@@ -414,7 +406,6 @@ 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);
@@ -430,7 +421,6 @@ 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',
}, },
} }
); );
@@ -764,7 +754,6 @@ 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();
@@ -790,7 +779,6 @@ 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(
@@ -805,19 +793,12 @@ 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 { return body.data as { id: string; start: string; end: string; description: string };
id: string;
start: string;
end: string;
description: string;
type: 'work' | 'break';
};
} }
// ────────────────────────────────────────────────── // ──────────────────────────────────────────────────
@@ -922,71 +903,3 @@ 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;
}>;
}

View File

@@ -20,17 +20,7 @@ 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 (
@@ -44,7 +34,6 @@ 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)
); );
}); });
@@ -59,18 +48,7 @@ export async function assertThatTimerIsStopped(page: Page) {
).toHaveClass(/bg-accent-300\/70/); ).toHaveClass(/bg-accent-300\/70/);
} }
export async function stoppedTimeEntryResponse( export async function stoppedTimeEntryResponse(page: Page, { description = '', tags = [] } = {}) {
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 &&
@@ -84,7 +62,6 @@ export async function stoppedTimeEntryResponse(
(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)
); );
}); });

View File

@@ -1,4 +1,4 @@
import type { Locator, Page } from '@playwright/test'; import type { Locator } from '@playwright/test';
/** /**
* Extract the first cell's text content from each row in a table. * Extract the first cell's text content from each row in a table.
@@ -14,22 +14,3 @@ export async function getTableRowNames(table: Locator): Promise<string[]> {
} }
return names; return names;
} }
/**
* The visual order of the given seeded names within the table, ignoring any other rows.
*/
export async function getSeededRowOrder(table: Locator, seeded: string[]): Promise<string[]> {
const rowNames = await getTableRowNames(table);
return rowNames
.map((rowName) => seeded.find((name) => rowName.includes(name)))
.filter((name): name is string => Boolean(name));
}
/**
* Drop a table's persisted sort/filter state so a test starts from the defaults.
*/
export async function clearTableState(page: Page, key: string) {
await page.evaluate((storageKey) => {
localStorage.removeItem(storageKey);
}, key);
}

View File

@@ -1,14 +1,14 @@
{ {
"Billing": { "Billing": {
"repository": "solidtime-io/extension-billing", "repository": "solidtime-io/extension-billing",
"ref": "v0.0.6" "ref": "v0.0.3"
}, },
"Services": { "Services": {
"repository": "solidtime-io/extension-services", "repository": "solidtime-io/extension-services",
"ref": "v0.0.2" "ref": "v0.0.1"
}, },
"Invoicing": { "Invoicing": {
"repository": "solidtime-io/extension-invoicing", "repository": "solidtime-io/extension-invoicing",
"ref": "v0.0.3" "ref": "v0.0.1"
} }
} }

4
package-lock.json generated
View File

@@ -8396,7 +8396,7 @@
}, },
"resources/js/packages/api": { "resources/js/packages/api": {
"name": "@solidtime/api", "name": "@solidtime/api",
"version": "0.0.7", "version": "0.0.6",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"devDependencies": { "devDependencies": {
"vite-plugin-dts": "^4.5.4" "vite-plugin-dts": "^4.5.4"
@@ -8411,7 +8411,7 @@
}, },
"resources/js/packages/ui": { "resources/js/packages/ui": {
"name": "@solidtime/ui", "name": "@solidtime/ui",
"version": "0.0.22", "version": "0.0.21",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"devDependencies": { "devDependencies": {
"@types/chroma-js": "^3.1.2", "@types/chroma-js": "^3.1.2",

View File

@@ -11,13 +11,14 @@ import Pagination from '@/Components/Common/Pagination.vue';
import { canCreateClients } from '@/utils/permissions'; import { canCreateClients } from '@/utils/permissions';
import { useProjectsQuery } from '@/utils/useProjectsQuery'; import { useProjectsQuery } from '@/utils/useProjectsQuery';
import { import {
useSortableTable, useVueTable,
type SortableColumnDef, getCoreRowModel,
type SortDirection, getSortedRowModel,
} from '@/utils/useSortableTable'; type SortingState,
} from '@tanstack/vue-table';
export type SortColumn = 'name' | 'projects_count' | 'status'; export type SortColumn = 'name' | 'projects_count' | 'status';
export type { SortDirection } from '@/utils/useSortableTable'; export type SortDirection = 'asc' | 'desc';
const props = defineProps<{ const props = defineProps<{
clients: Client[]; clients: Client[];
@@ -43,7 +44,17 @@ const projectCountMap = computed(() => {
return map; return map;
}); });
const columns = computed<SortableColumnDef<Client, SortColumn>[]>(() => [ // Name is always the secondary sort so rows with equal values render
// alphabetically instead of in API (created_at) order.
const sorting = computed<SortingState>(() => [
{
id: props.sortColumn,
desc: props.sortDirection === 'desc',
},
...(props.sortColumn !== 'name' ? [{ id: 'name', desc: false }] : []),
]);
const columns = computed(() => [
{ {
id: 'name', id: 'name',
accessorFn: (row: Client) => row.name.toLowerCase(), accessorFn: (row: Client) => row.name.toLowerCase(),
@@ -59,22 +70,41 @@ const columns = computed<SortableColumnDef<Client, SortColumn>[]>(() => [
}, },
]); ]);
const { const descFirstColumns = new Set<SortColumn>(
sortedRows: sortedClients, columns.value
descFirstColumns, .filter((c) => 'sortDescFirst' in c && c.sortDescFirst)
nextDirection, .map((c) => c.id as SortColumn)
} = useSortableTable({ );
data: () => props.clients,
columns: () => columns.value,
sortColumn: () => props.sortColumn,
sortDirection: () => props.sortDirection,
tieBreakColumn: 'name',
});
function handleSort(column: SortColumn) { function handleSort(column: SortColumn) {
emit('sort', column, nextDirection(column)); if (props.sortColumn === column) {
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
} else {
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
}
} }
const table = useVueTable({
get data() {
return props.clients;
},
get columns() {
return columns.value;
},
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
state: {
get sorting() {
return sorting.value;
},
},
manualSorting: false,
});
const sortedClients = computed(() => {
return table.getRowModel().rows.map((row) => row.original);
});
// Client-side pagination: the full list is in memory, only one page is mounted at a time. // Client-side pagination: the full list is in memory, only one page is mounted at a time.
const PAGE_SIZE = 15; const PAGE_SIZE = 15;
const currentPage = ref(1); const currentPage = ref(1);

View File

@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import TableHeading from '@/Components/Common/TableHeading.vue'; import TableHeading from '@/Components/Common/TableHeading.vue';
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue'; import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
import type { SortColumn, SortDirection } from '@/Components/Common/Client/ClientTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Client/ClientTable.vue';
const props = defineProps<{ const props = defineProps<{
@@ -9,29 +9,57 @@ const props = defineProps<{
descFirstColumns: ReadonlySet<SortColumn>; descFirstColumns: ReadonlySet<SortColumn>;
}>(); }>();
defineEmits<{ const emit = defineEmits<{
sort: [column: SortColumn]; sort: [column: SortColumn];
}>(); }>();
function handleSort(column: SortColumn) {
emit('sort', column);
}
function isSorted(column: SortColumn): boolean {
return props.sortColumn === column;
}
function isChevronDown(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return props.descFirstColumns.has(column)
? props.sortDirection === 'desc'
: props.sortDirection === 'asc';
}
function isChevronUp(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return !isChevronDown(column);
}
</script> </script>
<template> <template>
<TableHeading> <TableHeading>
<SortableTableHeaderCell <div
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12" class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
column="name" @click="handleSort('name')">
v-bind="props"
@sort="$emit('sort', $event)">
Name Name
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
<SortableTableHeaderCell <ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
column="projects_count" <span v-else class="w-4 h-4"></span>
v-bind="props" </div>
@sort="$emit('sort', $event)"> <div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('projects_count')">
Projects Projects
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('projects_count')" class="w-4 h-4" />
<SortableTableHeaderCell column="status" v-bind="props" @sort="$emit('sort', $event)"> <ChevronUpIcon v-else-if="isChevronUp('projects_count')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('status')">
Status Status
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
<ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12"> <div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
<span class="sr-only">Edit</span> <span class="sr-only">Edit</span>
</div> </div>

View File

@@ -3,14 +3,16 @@ import MemberTableHeading from '@/Components/Common/Member/MemberTableHeading.vu
import MemberTableRow from '@/Components/Common/Member/MemberTableRow.vue'; import MemberTableRow from '@/Components/Common/Member/MemberTableRow.vue';
import { useMembersQuery } from '@/utils/useMembersQuery'; import { useMembersQuery } from '@/utils/useMembersQuery';
import type { Member } from '@/packages/api/src'; import type { Member } from '@/packages/api/src';
import { computed } from 'vue';
import { import {
useSortableTable, useVueTable,
type SortableColumnDef, getCoreRowModel,
type SortDirection, getSortedRowModel,
} from '@/utils/useSortableTable'; type SortingState,
} from '@tanstack/vue-table';
export type SortColumn = 'name' | 'email' | 'role' | 'billable_rate' | 'status'; export type SortColumn = 'name' | 'email' | 'role' | 'billable_rate' | 'status';
export type { SortDirection } from '@/utils/useSortableTable'; export type SortDirection = 'asc' | 'desc';
const props = defineProps<{ const props = defineProps<{
sortColumn: SortColumn; sortColumn: SortColumn;
@@ -31,7 +33,14 @@ const roleOrder: Record<string, number> = {
placeholder: 4, placeholder: 4,
}; };
const columns: SortableColumnDef<Member, SortColumn>[] = [ const sorting = computed<SortingState>(() => [
{
id: props.sortColumn,
desc: props.sortDirection === 'desc',
},
]);
const columns = [
{ {
id: 'name', id: 'name',
accessorFn: (row: Member) => row.name.toLowerCase(), accessorFn: (row: Member) => row.name.toLowerCase(),
@@ -47,6 +56,7 @@ const columns: SortableColumnDef<Member, SortColumn>[] = [
{ {
id: 'billable_rate', id: 'billable_rate',
sortDescFirst: true, sortDescFirst: true,
sortUndefined: 'last' as const,
accessorFn: (row: Member) => { accessorFn: (row: Member) => {
if (row.billable_rate === null) return undefined; if (row.billable_rate === null) return undefined;
return row.billable_rate; return row.billable_rate;
@@ -58,21 +68,36 @@ const columns: SortableColumnDef<Member, SortColumn>[] = [
}, },
]; ];
const { const descFirstColumns = new Set<SortColumn>(
sortedRows: sortedMembers, columns.filter((c) => c.sortDescFirst).map((c) => c.id as SortColumn)
descFirstColumns, );
nextDirection,
} = useSortableTable({
data: () => members.value,
columns: () => columns,
sortColumn: () => props.sortColumn,
sortDirection: () => props.sortDirection,
tieBreakColumn: 'name',
});
function handleSort(column: SortColumn) { function handleSort(column: SortColumn) {
emit('sort', column, nextDirection(column)); if (props.sortColumn === column) {
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
} else {
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
}
} }
const table = useVueTable({
get data() {
return members.value;
},
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
state: {
get sorting() {
return sorting.value;
},
},
manualSorting: false,
});
const sortedMembers = computed(() => {
return table.getRowModel().rows.map((row) => row.original);
});
</script> </script>
<template> <template>

View File

@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import TableHeading from '@/Components/Common/TableHeading.vue'; import TableHeading from '@/Components/Common/TableHeading.vue';
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue'; import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
import type { SortColumn, SortDirection } from '@/Components/Common/Member/MemberTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Member/MemberTable.vue';
const props = defineProps<{ const props = defineProps<{
@@ -9,35 +9,73 @@ const props = defineProps<{
descFirstColumns: ReadonlySet<SortColumn>; descFirstColumns: ReadonlySet<SortColumn>;
}>(); }>();
defineEmits<{ const emit = defineEmits<{
sort: [column: SortColumn]; sort: [column: SortColumn];
}>(); }>();
function handleSort(column: SortColumn) {
emit('sort', column);
}
function isSorted(column: SortColumn): boolean {
return props.sortColumn === column;
}
function isChevronDown(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return props.descFirstColumns.has(column)
? props.sortDirection === 'desc'
: props.sortDirection === 'asc';
}
function isChevronUp(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return !isChevronDown(column);
}
</script> </script>
<template> <template>
<TableHeading> <TableHeading>
<SortableTableHeaderCell <div
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12" class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
column="name" @click="handleSort('name')">
v-bind="props"
@sort="$emit('sort', $event)">
Name Name
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
<SortableTableHeaderCell column="email" v-bind="props" @sort="$emit('sort', $event)"> <ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('email')">
Email Email
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('email')" class="w-4 h-4" />
<SortableTableHeaderCell column="role" v-bind="props" @sort="$emit('sort', $event)"> <ChevronUpIcon v-else-if="isChevronUp('email')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('role')">
Role Role
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('role')" class="w-4 h-4" />
<SortableTableHeaderCell <ChevronUpIcon v-else-if="isChevronUp('role')" class="w-4 h-4" />
column="billable_rate" <span v-else class="w-4 h-4"></span>
v-bind="props" </div>
@sort="$emit('sort', $event)"> <div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('billable_rate')">
Billable Rate Billable Rate
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('billable_rate')" class="w-4 h-4" />
<SortableTableHeaderCell column="status" v-bind="props" @sort="$emit('sort', $event)"> <ChevronUpIcon v-else-if="isChevronUp('billable_rate')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('status')">
Status Status
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
<ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12 bg-row-heading-background"> <div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12 bg-row-heading-background">
<span class="sr-only">Edit</span> <span class="sr-only">Edit</span>
</div> </div>

View File

@@ -7,7 +7,6 @@ import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue
import ProjectTableHeading from '@/Components/Common/Project/ProjectTableHeading.vue'; import ProjectTableHeading from '@/Components/Common/Project/ProjectTableHeading.vue';
import ProjectTableRow from '@/Components/Common/Project/ProjectTableRow.vue'; import ProjectTableRow from '@/Components/Common/Project/ProjectTableRow.vue';
import Pagination from '@/Components/Common/Pagination.vue'; import Pagination from '@/Components/Common/Pagination.vue';
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
export type SortColumn = export type SortColumn =
| 'name' | 'name'
@@ -17,7 +16,7 @@ export type SortColumn =
| 'billable_rate' | 'billable_rate'
| 'status' | 'status'
| 'visibility'; | 'visibility';
export type { SortDirection } from '@/utils/useSortableTable'; export type SortDirection = 'asc' | 'desc';
import { canCreateProjects } from '@/utils/permissions'; import { canCreateProjects } from '@/utils/permissions';
import type { CreateProjectBody, Project, Client, CreateClientBody } from '@/packages/api/src'; import type { CreateProjectBody, Project, Client, CreateClientBody } from '@/packages/api/src';
import { useProjectsStore } from '@/utils/useProjects'; import { useProjectsStore } from '@/utils/useProjects';
@@ -28,24 +27,20 @@ import { isAllowedToPerformPremiumAction } from '@/utils/billing';
import { useOrganizationQuery } from '@/utils/useOrganizationQuery'; import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
import { getCurrentOrganizationId } from '@/utils/useUser'; import { getCurrentOrganizationId } from '@/utils/useUser';
import { import {
useSortableTable, useVueTable,
type SortableColumnDef, getCoreRowModel,
type SortDirection, getSortedRowModel,
} from '@/utils/useSortableTable'; type SortingState,
} from '@tanstack/vue-table';
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!); const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const props = withDefaults( const props = defineProps<{
defineProps<{ projects: Project[];
projects: Project[]; showBillableRate: boolean;
showBillableRate: boolean; sortColumn: SortColumn;
sortColumn: SortColumn; sortDirection: SortDirection;
sortDirection: SortDirection; }>();
isFiltered?: boolean;
isLoading?: boolean;
}>(),
{ isFiltered: false, isLoading: false }
);
const emit = defineEmits<{ const emit = defineEmits<{
sort: [column: SortColumn, direction: SortDirection]; sort: [column: SortColumn, direction: SortDirection];
@@ -62,16 +57,28 @@ const clientNameMap = computed(() => {
return map; return map;
}); });
// Convert sort props to TanStack Table format.
// Name is always the secondary sort so rows with equal values render
// alphabetically instead of in API (created_at) order.
const sorting = computed<SortingState>(() => [
{
id: props.sortColumn,
desc: props.sortDirection === 'desc',
},
...(props.sortColumn !== 'name' ? [{ id: 'name', desc: false }] : []),
]);
// Define column accessors for sorting. // Define column accessors for sorting.
// Numeric columns use sortDescFirst so that the first click (chevron down) sorts highest-first, // Numeric columns use sortDescFirst so that the first click (chevron down) sorts highest-first,
// while text columns default to ascending (A-Z) on first click (chevron down). // while text columns default to ascending (A-Z) on first click (chevron down).
const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [ const columns = computed(() => [
{ {
id: 'name', id: 'name',
accessorFn: (row: Project) => row.name.toLowerCase(), accessorFn: (row: Project) => row.name.toLowerCase(),
}, },
{ {
id: 'client_name', id: 'client_name',
sortUndefined: 'last' as const,
accessorFn: (row: Project) => { accessorFn: (row: Project) => {
if (!row.client_id) return undefined; if (!row.client_id) return undefined;
return (clientNameMap.value.get(row.client_id) ?? '').toLowerCase(); return (clientNameMap.value.get(row.client_id) ?? '').toLowerCase();
@@ -80,11 +87,12 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
{ {
id: 'spent_time', id: 'spent_time',
sortDescFirst: true, sortDescFirst: true,
accessorFn: (row: Project) => row.spent_time, accessorFn: (row: Project) => row.spent_time ?? 0,
}, },
{ {
id: 'progress', id: 'progress',
sortDescFirst: true, sortDescFirst: true,
sortUndefined: 'last' as const,
accessorFn: (row: Project) => { accessorFn: (row: Project) => {
if (!row.estimated_time) return undefined; if (!row.estimated_time) return undefined;
return (row.spent_time / row.estimated_time) * 100; return (row.spent_time / row.estimated_time) * 100;
@@ -93,7 +101,7 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
{ {
id: 'billable_rate', id: 'billable_rate',
sortDescFirst: true, sortDescFirst: true,
accessorFn: (row: Project) => row.billable_rate, accessorFn: (row: Project) => row.billable_rate ?? 0,
}, },
{ {
id: 'status', id: 'status',
@@ -105,22 +113,40 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
}, },
]); ]);
const { // Columns with sortDescFirst get desc as default direction on first click.
sortedRows: sortedProjects, const descFirstColumns = new Set<SortColumn>(
descFirstColumns, columns.value.filter((c) => c.sortDescFirst).map((c) => c.id as SortColumn)
nextDirection, );
} = useSortableTable({
data: () => props.projects,
columns: () => columns.value,
sortColumn: () => props.sortColumn,
sortDirection: () => props.sortDirection,
tieBreakColumn: 'name',
});
function handleSort(column: SortColumn) { function handleSort(column: SortColumn) {
emit('sort', column, nextDirection(column)); if (props.sortColumn === column) {
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
} else {
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
}
} }
const table = useVueTable({
get data() {
return props.projects;
},
get columns() {
return columns.value;
},
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
state: {
get sorting() {
return sorting.value;
},
},
manualSorting: false,
});
const sortedProjects = computed(() => {
return table.getRowModel().rows.map((row) => row.original);
});
// Client-side pagination: the full list is in memory, only one page is mounted at a time. // Client-side pagination: the full list is in memory, only one page is mounted at a time.
const PAGE_SIZE = 15; const PAGE_SIZE = 15;
const currentPage = ref(1); const currentPage = ref(1);
@@ -134,28 +160,6 @@ const paginatedProjects = computed(() => {
return sortedProjects.value.slice(start, start + PAGE_SIZE); return sortedProjects.value.slice(start, start + PAGE_SIZE);
}); });
const emptyState = computed(() => {
if (props.isFiltered) {
return {
title: 'No matching projects',
description: 'Try a different search term or adjust your filters.',
showCreateButton: false,
};
}
if (!canCreateProjects()) {
return {
title: 'You are not a member of any projects',
description: 'Ask your manager to add you to a project as a team member.',
showCreateButton: false,
};
}
return {
title: 'No projects found',
description: 'Create your first project now!',
showCreateButton: true,
};
});
const showCreateProjectModal = ref(false); const showCreateProjectModal = ref(false);
async function createProject(project: CreateProjectBody): Promise<Project | undefined> { async function createProject(project: CreateProjectBody): Promise<Project | undefined> {
@@ -189,21 +193,24 @@ const gridTemplate = computed(() => {
:sort-direction="props.sortDirection" :sort-direction="props.sortDirection"
:desc-first-columns="descFirstColumns" :desc-first-columns="descFirstColumns"
@sort="handleSort"></ProjectTableHeading> @sort="handleSort"></ProjectTableHeading>
<div <div v-if="sortedProjects.length === 0" class="col-span-full py-24 text-center">
v-if="props.isLoading"
class="col-span-full flex justify-center items-center py-24">
<LoadingSpinner></LoadingSpinner>
</div>
<div
v-else-if="sortedProjects.length === 0"
class="col-span-full py-24 text-center">
<FolderPlusIcon class="w-8 text-icon-default inline pb-2"></FolderPlusIcon> <FolderPlusIcon class="w-8 text-icon-default inline pb-2"></FolderPlusIcon>
<h3 class="text-text-primary font-semibold">{{ emptyState.title }}</h3> <h3 class="text-text-primary font-semibold">
{{
canCreateProjects()
? 'No projects found'
: 'You are not a member of any projects'
}}
</h3>
<p class="pb-5 max-w-md mx-auto text-sm pt-1"> <p class="pb-5 max-w-md mx-auto text-sm pt-1">
{{ emptyState.description }} {{
canCreateProjects()
? 'Create your first project now!'
: 'Ask your manager to add you to a project as a team member.'
}}
</p> </p>
<SecondaryButton <SecondaryButton
v-if="emptyState.showCreateButton" v-if="canCreateProjects()"
:icon="PlusIcon" :icon="PlusIcon"
@click="showCreateProjectModal = true" @click="showCreateProjectModal = true"
>Create your First Project >Create your First Project

View File

@@ -1,7 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue';
import TableHeading from '@/Components/Common/TableHeading.vue'; import TableHeading from '@/Components/Common/TableHeading.vue';
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue'; import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue';
const props = defineProps<{ const props = defineProps<{
@@ -15,51 +14,90 @@ const emit = defineEmits<{
sort: [column: SortColumn]; sort: [column: SortColumn];
}>(); }>();
// Bound once per cell instead of repeating the three sort props on every column.
const sortState = computed(() => ({
sortColumn: props.sortColumn,
sortDirection: props.sortDirection,
descFirstColumns: props.descFirstColumns,
}));
function handleSort(column: SortColumn) { function handleSort(column: SortColumn) {
emit('sort', column); emit('sort', column);
} }
function isSorted(column: SortColumn): boolean {
return props.sortColumn === column;
}
function isChevronDown(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return props.descFirstColumns.has(column)
? props.sortDirection === 'desc'
: props.sortDirection === 'asc';
}
function isChevronUp(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return !isChevronDown(column);
}
</script> </script>
<template> <template>
<TableHeading> <TableHeading>
<SortableTableHeaderCell <div
class="pr-3 pl-2 sm:pl-4 lg:pl-6" class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
column="name" @click="handleSort('name')">
v-bind="sortState"
@sort="handleSort">
Name Name
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
<SortableTableHeaderCell column="client_name" v-bind="sortState" @sort="handleSort"> <ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('client_name')">
Client Client
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('client_name')" class="w-4 h-4" />
<SortableTableHeaderCell column="spent_time" v-bind="sortState" @sort="handleSort"> <ChevronUpIcon v-else-if="isChevronUp('client_name')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('spent_time')">
Total Time Total Time
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('spent_time')" class="w-4 h-4" />
<SortableTableHeaderCell column="progress" v-bind="sortState" @sort="handleSort"> <ChevronUpIcon v-else-if="isChevronUp('spent_time')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('progress')">
Progress Progress
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('progress')" class="w-4 h-4" />
<SortableTableHeaderCell <ChevronUpIcon v-else-if="isChevronUp('progress')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
v-if="showBillableRate" v-if="showBillableRate"
column="billable_rate" class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
v-bind="sortState" @click="handleSort('billable_rate')">
@sort="handleSort">
Billable Rate Billable Rate
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('billable_rate')" class="w-4 h-4" />
<SortableTableHeaderCell column="status" v-bind="sortState" @sort="handleSort"> <ChevronUpIcon v-else-if="isChevronUp('billable_rate')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('status')">
Status Status
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
<SortableTableHeaderCell column="visibility" v-bind="sortState" @sort="handleSort"> <ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
@click="handleSort('visibility')">
Visibility Visibility
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('visibility')" class="w-4 h-4" />
<div class="relative py-1.5 pl-3 pr-2 sm:pr-4 lg:pr-6"> <ChevronUpIcon v-else-if="isChevronUp('visibility')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
<span class="sr-only">Edit</span> <span class="sr-only">Edit</span>
</div> </div>
</TableHeading> </TableHeading>
</template> </template>
<style scoped></style>

View File

@@ -88,13 +88,13 @@ const showEditProjectModal = ref(false);
<ContextMenuTrigger as-child> <ContextMenuTrigger as-child>
<TableRow :href="route('projects.show', { project: project.id })"> <TableRow :href="route('projects.show', { project: project.id })">
<div <div
class="whitespace-nowrap min-w-0 flex items-center space-x-5 py-4 pr-3 text-sm font-medium text-text-primary pl-2 sm:pl-4 lg:pl-6"> class="whitespace-nowrap min-w-0 flex items-center space-x-5 3xl:pl-12 py-4 pr-3 text-sm font-medium text-text-primary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12">
<div <div
:style="{ :style="{
backgroundColor: project.color, backgroundColor: project.color,
boxShadow: `var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) ${project.color}30`, boxShadow: `var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) ${project.color}30`,
}" }"
class="w-3 h-3 ml-1 rounded-full"></div> class="w-3 h-3 rounded-full"></div>
<span class="overflow-ellipsis overflow-hidden"> <span class="overflow-ellipsis overflow-hidden">
{{ project.name }} {{ project.name }}
</span> </span>
@@ -155,7 +155,7 @@ const showEditProjectModal = ref(false);
</template> </template>
</div> </div>
<div <div
class="relative whitespace-nowrap flex items-center pl-3 text-right text-sm font-medium pr-2 sm:pr-4 lg:pr-6"> class="relative whitespace-nowrap flex items-center pl-3 text-right text-sm font-medium pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
<ProjectMoreOptionsDropdown <ProjectMoreOptionsDropdown
:project="project" :project="project"
@edit="showEditProjectModal = true" @edit="showEditProjectModal = true"

View File

@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { computed, ref } from 'vue';
import { UserGroupIcon, CheckCircleIcon, GlobeAltIcon } from '@heroicons/vue/16/solid'; import { UserGroupIcon, CheckCircleIcon, GlobeAltIcon } from '@heroicons/vue/16/solid';
import ListFilterIcon from '@/packages/ui/src/Icons/ListFilterIcon.vue'; import ListFilterIcon from '@/packages/ui/src/Icons/ListFilterIcon.vue';
import { import {
@@ -81,18 +81,23 @@ function toggleNoClient() {
clientIds, clientIds,
}); });
} }
const hasActiveFilters = computed(() => {
return (
props.filters.status !== 'all' ||
props.filters.visibility !== 'all' ||
props.filters.clientIds.length > 0
);
});
</script> </script>
<template> <template>
<DropdownMenu v-model:open="open"> <DropdownMenu v-model:open="open">
<DropdownMenuTrigger as-child> <DropdownMenuTrigger as-child>
<!-- -ml-1.5 cancels the icon's inset inside the button so it sits flush with the toolbar's left padding --> <Button variant="ghost" size="xs" aria-label="Filter projects">
<Button <ListFilterIcon
variant="ghost" :class="[hasActiveFilters ? '' : '-ml-0.5', 'h-4 w-4 text-icon-default']" />
size="icon" <span v-if="!hasActiveFilters" class="text-nowrap">Filter</span>
class="-ml-1.5 h-7 w-7 flex-shrink-0"
aria-label="Filter projects">
<ListFilterIcon class="h-4 w-4 text-icon-default" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="start" class="w-56"> <DropdownMenuContent align="start" class="w-56">

View File

@@ -9,7 +9,7 @@ const showExportModal = defineModel('show', { default: false });
function downloadCurrentExport() { function downloadCurrentExport() {
if (props.exportUrl) { if (props.exportUrl) {
window.open(props.exportUrl, '_self'); window.open(props.exportUrl, '_blank')?.focus();
} }
} }
</script> </script>

View File

@@ -1,8 +1,7 @@
<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, Coffee } from '@lucide/vue'; import { Check } 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';
@@ -28,7 +27,6 @@ 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 });
@@ -39,8 +37,6 @@ 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 }[] = [
@@ -166,38 +162,6 @@ 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"

View File

@@ -71,7 +71,6 @@ 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);
@@ -127,7 +126,6 @@ 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,
@@ -162,7 +160,7 @@ const aggregatedTableTimeEntries = computed<AggregatedTimeEntries | undefined>((
}); });
const reportProperties = computed(() => { const reportProperties = computed(() => {
const { billable: billableFilter, type: typeFilter, ...rest } = filterParams.value; const { billable: billableFilter, ...rest } = filterParams.value;
let billableValue: boolean | null = null; let billableValue: boolean | null = null;
if (billableFilter === 'true') { if (billableFilter === 'true') {
@@ -174,7 +172,6 @@ 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),
@@ -240,8 +237,7 @@ const groupedPieChartData = computed(() => {
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => { aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
const name = getNameForReportingRowEntry( const name = getNameForReportingRowEntry(
entry.key, entry.key,
aggregatedTableTimeEntries.value?.grouped_type ?? null, aggregatedTableTimeEntries.value?.grouped_type ?? null
organization?.value?.date_format
); );
let color = getRandomColorWithSeed(entry.key ?? 'none'); let color = getRandomColorWithSeed(entry.key ?? 'none');
if ( if (
@@ -256,7 +252,11 @@ const groupedPieChartData = computed(() => {
} }
return { return {
value: entry.seconds, value: entry.seconds,
name: name ?? '', name:
getNameForReportingRowEntry(
entry.key,
aggregatedTableTimeEntries.value?.grouped_type ?? null
) ?? '',
color: color, color: color,
}; };
}) ?? [] }) ?? []
@@ -266,25 +266,18 @@ const groupedPieChartData = computed(() => {
const tableData = computed(() => { const tableData = computed(() => {
return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => { return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
return { return {
key: entry.key,
seconds: entry.seconds, seconds: entry.seconds,
cost: entry.cost, cost: entry.cost,
description: getNameForReportingRowEntry( description: getNameForReportingRowEntry(
entry.key, entry.key,
aggregatedTableTimeEntries.value?.grouped_type ?? null, aggregatedTableTimeEntries.value?.grouped_type ?? null
organization?.value?.date_format
), ),
grouped_data: grouped_data:
entry.grouped_data?.map((el) => { entry.grouped_data?.map((el) => {
return { return {
key: el.key,
seconds: el.seconds, seconds: el.seconds,
cost: el.cost, cost: el.cost,
description: getNameForReportingRowEntry( description: getNameForReportingRowEntry(el.key, entry.grouped_type),
el.key,
entry.grouped_type,
organization?.value?.date_format
),
}; };
}) ?? [], }) ?? [],
}; };
@@ -378,7 +371,6 @@ 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"
@@ -425,8 +417,9 @@ const tableData = computed(() => {
"> ">
<ReportingRow <ReportingRow
v-for="entry in tableData" v-for="entry in tableData"
:key="entry.key ?? 'none'" :key="entry.description ?? 'none'"
:currency="getOrganizationCurrencyString()" :currency="getOrganizationCurrencyString()"
:type="aggregatedTableTimeEntries.grouped_type"
:show-cost="showBillableRate" :show-cost="showBillableRate"
:entry="entry"></ReportingRow> :entry="entry"></ReportingRow>
<div class="contents [&>*]:transition text-text-tertiary [&>*]:h-[50px]"> <div class="contents [&>*]:transition text-text-tertiary [&>*]:h-[50px]">

View File

@@ -11,7 +11,6 @@ type AggregatedGroupedData = GroupedData & {
}; };
type GroupedData = { type GroupedData = {
key: string | null;
seconds: number; seconds: number;
cost: number | null; cost: number | null;
description: string | null | undefined; description: string | null | undefined;
@@ -73,7 +72,7 @@ const organization = inject<ComputedRef<Organization>>('organization');
:style="`grid-template-columns: 1fr 150px ${showCost ? '150px' : ''}`"> :style="`grid-template-columns: 1fr 150px ${showCost ? '150px' : ''}`">
<ReportingRow <ReportingRow
v-for="subEntry in entry.grouped_data" v-for="subEntry in entry.grouped_data"
:key="subEntry.key ?? 'none'" :key="subEntry.description ?? 'none'"
:currency="props.currency" :currency="props.currency"
:show-cost="showCost" :show-cost="showCost"
indent indent

View File

@@ -1,54 +0,0 @@
<script setup lang="ts" generic="TColumn extends string">
import { computed, useAttrs } from 'vue';
import type { ClassValue } from 'clsx';
import { cn } from '@/lib/utils';
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
import type { SortDirection } from '@/utils/useSortableTable';
defineOptions({ inheritAttrs: false });
const props = defineProps<{
column: TColumn;
sortColumn: TColumn;
sortDirection: SortDirection;
descFirstColumns: ReadonlySet<TColumn>;
}>();
const emit = defineEmits<{
sort: [column: TColumn];
}>();
const attrs = useAttrs();
const isSorted = computed(() => props.sortColumn === props.column);
const isChevronDown = computed(() => {
if (!isSorted.value) return false;
return props.descFirstColumns.has(props.column)
? props.sortDirection === 'desc'
: props.sortDirection === 'asc';
});
const cellClass = computed(() =>
cn(
'px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1',
attrs.class as ClassValue
)
);
</script>
<template>
<button type="button" :class="cellClass" @click="emit('sort', column)">
<slot></slot>
<span class="sr-only">
{{
isSorted
? `sorted ${sortDirection === 'asc' ? 'ascending' : 'descending'}`
: 'not sorted'
}}
</span>
<ChevronDownIcon v-if="isChevronDown" aria-hidden="true" class="w-4 h-4" />
<ChevronUpIcon v-else-if="isSorted" aria-hidden="true" class="w-4 h-4" />
<span v-else aria-hidden="true" class="w-4 h-4"></span>
</button>
</template>

View File

@@ -2,7 +2,7 @@
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue'; import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import { FolderPlusIcon } from '@heroicons/vue/24/solid'; import { FolderPlusIcon } from '@heroicons/vue/24/solid';
import { PlusIcon } from '@heroicons/vue/16/solid'; import { PlusIcon } from '@heroicons/vue/16/solid';
import { ref } from 'vue'; import { computed, ref } from 'vue';
import { useTagsQuery } from '@/utils/useTagsQuery'; import { useTagsQuery } from '@/utils/useTagsQuery';
import TagTableRow from '@/Components/Common/Tag/TagTableRow.vue'; import TagTableRow from '@/Components/Common/Tag/TagTableRow.vue';
import TagCreateModal from '@/packages/ui/src/Tag/TagCreateModal.vue'; import TagCreateModal from '@/packages/ui/src/Tag/TagCreateModal.vue';
@@ -10,13 +10,14 @@ import TagTableHeading from '@/Components/Common/Tag/TagTableHeading.vue';
import { canCreateTags } from '@/utils/permissions'; import { canCreateTags } from '@/utils/permissions';
import type { Tag } from '@/packages/api/src'; import type { Tag } from '@/packages/api/src';
import { import {
useSortableTable, useVueTable,
type SortableColumnDef, getCoreRowModel,
type SortDirection, getSortedRowModel,
} from '@/utils/useSortableTable'; type SortingState,
} from '@tanstack/vue-table';
export type SortColumn = 'name'; export type SortColumn = 'name';
export type { SortDirection } from '@/utils/useSortableTable'; export type SortDirection = 'asc' | 'desc';
const props = defineProps<{ const props = defineProps<{
createTag: (name: string) => Promise<Tag | undefined>; createTag: (name: string) => Promise<Tag | undefined>;
@@ -31,27 +32,50 @@ const emit = defineEmits<{
const { tags } = useTagsQuery(); const { tags } = useTagsQuery();
const showCreateTagModal = ref(false); const showCreateTagModal = ref(false);
const columns: SortableColumnDef<Tag, SortColumn>[] = [ const sorting = computed<SortingState>(() => [
{
id: props.sortColumn,
desc: props.sortDirection === 'desc',
},
]);
const columns = [
{ {
id: 'name', id: 'name',
accessorFn: (row: Tag) => row.name.toLowerCase(), accessorFn: (row: Tag) => row.name.toLowerCase(),
}, },
]; ];
const { const descFirstColumns = new Set<SortColumn>(
sortedRows: sortedTags, columns.filter((c) => 'sortDescFirst' in c && c.sortDescFirst).map((c) => c.id as SortColumn)
descFirstColumns, );
nextDirection,
} = useSortableTable({
data: () => tags.value,
columns: () => columns,
sortColumn: () => props.sortColumn,
sortDirection: () => props.sortDirection,
});
function handleSort(column: SortColumn) { function handleSort(column: SortColumn) {
emit('sort', column, nextDirection(column)); if (props.sortColumn === column) {
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
} else {
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
}
} }
const table = useVueTable({
get data() {
return tags.value;
},
columns,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
state: {
get sorting() {
return sorting.value;
},
},
manualSorting: false,
});
const sortedTags = computed(() => {
return table.getRowModel().rows.map((row) => row.original);
});
</script> </script>
<template> <template>

View File

@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import TableHeading from '@/Components/Common/TableHeading.vue'; import TableHeading from '@/Components/Common/TableHeading.vue';
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue'; import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
import type { SortColumn, SortDirection } from '@/Components/Common/Tag/TagTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Tag/TagTable.vue';
const props = defineProps<{ const props = defineProps<{
@@ -9,20 +9,41 @@ const props = defineProps<{
descFirstColumns: ReadonlySet<SortColumn>; descFirstColumns: ReadonlySet<SortColumn>;
}>(); }>();
defineEmits<{ const emit = defineEmits<{
sort: [column: SortColumn]; sort: [column: SortColumn];
}>(); }>();
function handleSort(column: SortColumn) {
emit('sort', column);
}
function isSorted(column: SortColumn): boolean {
return props.sortColumn === column;
}
function isChevronDown(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return props.descFirstColumns.has(column)
? props.sortDirection === 'desc'
: props.sortDirection === 'asc';
}
function isChevronUp(column: SortColumn): boolean {
if (!isSorted(column)) return false;
return !isChevronDown(column);
}
</script> </script>
<template> <template>
<TableHeading> <TableHeading>
<SortableTableHeaderCell <div
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12" class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
column="name" @click="handleSort('name')">
v-bind="props"
@sort="$emit('sort', $event)">
Name Name
</SortableTableHeaderCell> <ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
<ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
<span v-else class="w-4 h-4"></span>
</div>
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12"> <div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
<span class="sr-only">Edit</span> <span class="sr-only">Edit</span>
</div> </div>

View File

@@ -8,62 +8,12 @@ import TaskTableHeading from '@/Components/Common/Task/TaskTableHeading.vue';
import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue'; import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue';
import { canCreateTasks } from '@/utils/permissions'; import { canCreateTasks } from '@/utils/permissions';
import type { Task } from '@/packages/api/src'; import type { Task } from '@/packages/api/src';
import {
useSortableTable,
type SortableColumnDef,
type SortDirection,
} from '@/utils/useSortableTable';
export type SortColumn = 'name' | 'spent_time' | 'progress';
export type { SortDirection } from '@/utils/useSortableTable';
const props = defineProps<{ const props = defineProps<{
projectId: string; projectId: string;
tasks: Task[]; tasks: Task[];
sortColumn: SortColumn;
sortDirection: SortDirection;
}>(); }>();
const emit = defineEmits<{
sort: [column: SortColumn, direction: SortDirection];
}>();
const columns: SortableColumnDef<Task, SortColumn>[] = [
{
id: 'name',
accessorFn: (row: Task) => row.name.toLowerCase(),
},
{
id: 'spent_time',
sortDescFirst: true,
accessorFn: (row: Task) => row.spent_time,
},
{
id: 'progress',
sortDescFirst: true,
accessorFn: (row: Task) => {
if (!row.estimated_time) return undefined;
return (row.spent_time / row.estimated_time) * 100;
},
},
];
const {
sortedRows: sortedTasks,
descFirstColumns,
nextDirection,
} = useSortableTable({
data: () => props.tasks,
columns: () => columns,
sortColumn: () => props.sortColumn,
sortDirection: () => props.sortDirection,
tieBreakColumn: 'name',
});
function handleSort(column: SortColumn) {
emit('sort', column, nextDirection(column));
}
const createTask = ref(false); const createTask = ref(false);
</script> </script>
@@ -80,12 +30,8 @@ const createTask = ref(false);
1fr minmax(80px, auto) minmax(120px, auto) minmax(50px, auto) 1fr minmax(80px, auto) minmax(120px, auto) minmax(50px, auto)
80px; 80px;
"> ">
<TaskTableHeading <TaskTableHeading></TaskTableHeading>
:sort-column="sortColumn" <div v-if="tasks.length === 0" class="col-span-5 py-24 text-center">
:sort-direction="sortDirection"
:desc-first-columns="descFirstColumns"
@sort="handleSort"></TaskTableHeading>
<div v-if="sortedTasks.length === 0" class="col-span-5 py-24 text-center">
<PlusCircleIcon class="w-8 text-icon-default inline pb-2"></PlusCircleIcon> <PlusCircleIcon class="w-8 text-icon-default inline pb-2"></PlusCircleIcon>
<h3 class="text-text-primary font-semibold">No tasks found</h3> <h3 class="text-text-primary font-semibold">No tasks found</h3>
<p v-if="canCreateTasks()" class="pb-5">Create your first task now!</p> <p v-if="canCreateTasks()" class="pb-5">Create your first task now!</p>
@@ -96,7 +42,7 @@ const createTask = ref(false);
>Create your First Task >Create your First Task
</SecondaryButton> </SecondaryButton>
</div> </div>
<template v-for="task in sortedTasks" :key="task.id"> <template v-for="task in tasks" :key="task.id">
<TaskTableRow :task="task"></TaskTableRow> <TaskTableRow :task="task"></TaskTableRow>
</template> </template>
</div> </div>

View File

@@ -1,37 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import TableHeading from '@/Components/Common/TableHeading.vue'; import TableHeading from '@/Components/Common/TableHeading.vue';
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
import type { SortColumn, SortDirection } from '@/Components/Common/Task/TaskTable.vue';
const props = defineProps<{
sortColumn: SortColumn;
sortDirection: SortDirection;
descFirstColumns: ReadonlySet<SortColumn>;
}>();
defineEmits<{
sort: [column: SortColumn];
}>();
</script> </script>
<template> <template>
<TableHeading> <TableHeading>
<SortableTableHeaderCell <div class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12">
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12"
column="name"
v-bind="props"
@sort="$emit('sort', $event)">
Task Name Task Name
</SortableTableHeaderCell> </div>
<SortableTableHeaderCell column="spent_time" v-bind="props" @sort="$emit('sort', $event)"> <div class="px-3 py-1.5 text-left text-text-tertiary">Total Time</div>
Total Time <div class="px-3 py-1.5 text-left text-text-tertiary">Progress</div>
</SortableTableHeaderCell>
<SortableTableHeaderCell column="progress" v-bind="props" @sort="$emit('sort', $event)">
Progress
</SortableTableHeaderCell>
<div class="px-3 py-1.5 text-left text-text-tertiary">Status</div> <div class="px-3 py-1.5 text-left text-text-tertiary">Status</div>
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12"> <div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
<span class="sr-only">Edit</span> <span class="sr-only">Edit</span>
</div> </div>
</TableHeading> </TableHeading>
</template> </template>
<style scoped></style>

View File

@@ -28,7 +28,6 @@ const {
}, },
queries: { queries: {
member_id: getCurrentMembershipId(), member_id: getCurrentMembershipId(),
type: 'work',
}, },
}); });
}, },

View File

@@ -62,8 +62,6 @@ 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',
}; };
}); });
@@ -95,24 +93,20 @@ const tableData = computed(() => {
return ( return (
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => { aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
return { return {
key: entry.key,
seconds: entry.seconds, seconds: entry.seconds,
cost: entry.cost, cost: entry.cost,
description: getNameForReportingRowEntry( description: getNameForReportingRowEntry(
entry.key, entry.key,
aggregatedTableTimeEntries.value?.grouped_type ?? null, aggregatedTableTimeEntries.value?.grouped_type ?? null
organization?.value?.date_format
), ),
grouped_data: grouped_data:
entry.grouped_data?.map((el) => { entry.grouped_data?.map((el) => {
return { return {
key: el.key,
seconds: el.seconds, seconds: el.seconds,
cost: el.cost, cost: el.cost,
description: getNameForReportingRowEntry( description: getNameForReportingRowEntry(
el.key, el.key,
entry.grouped_type ?? null, entry.grouped_type ?? null
organization?.value?.date_format
), ),
}; };
}) ?? [], }) ?? [],
@@ -168,7 +162,7 @@ const showBillableRate = computed(() => {
"> ">
<ReportingRow <ReportingRow
v-for="entry in tableData" v-for="entry in tableData"
:key="entry.key ?? 'none'" :key="entry.description ?? 'none'"
:currency="getOrganizationCurrencyString()" :currency="getOrganizationCurrencyString()"
:show-cost="showBillableRate" :show-cost="showBillableRate"
:entry="entry"></ReportingRow> :entry="entry"></ReportingRow>

View File

@@ -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 { getDayJsInstance } from '@/packages/ui/src/utils/time'; import dayjs from 'dayjs';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled'; import utc from 'dayjs/plugin/utc';
import duration from 'dayjs/plugin/duration';
import { getLastWorkTimeEntry, useCurrentTimeEntryStore } from '@/utils/useCurrentTimeEntry'; import { 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,7 +20,6 @@ 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,
@@ -45,15 +44,15 @@ const page = usePage<{
user: User; user: User;
}; };
}>(); }>();
const dayjs = getDayJsInstance(); dayjs.extend(duration);
dayjs.extend(utc);
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!); const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const breaksEnabled = useBreaksEnabled(organization);
const currentTimeEntryStore = useCurrentTimeEntryStore(); const currentTimeEntryStore = useCurrentTimeEntryStore();
const { currentTimeEntry, isActive, isOnBreak, now } = storeToRefs(currentTimeEntryStore); const { currentTimeEntry, isActive, now } = storeToRefs(currentTimeEntryStore);
const { startLiveTimer, stopLiveTimer, setActiveState, startBreak, resumeWorkAfterBreak } = const { startLiveTimer, stopLiveTimer, setActiveState } = currentTimeEntryStore;
currentTimeEntryStore;
const { projects } = useProjectsQuery(); const { projects } = useProjectsQuery();
const { tasks } = useTasksQuery(); const { tasks } = useTasksQuery();
@@ -68,8 +67,6 @@ 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) {
@@ -126,14 +123,6 @@ 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 });
@@ -153,16 +142,6 @@ 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>
@@ -207,29 +186,17 @@ 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>

View File

@@ -1,249 +0,0 @@
<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,
type Interval,
} 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>;
entryLabel: (id: string) => string;
}>();
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, {
dayStart: props.request.dayStart,
dayEnd: props.request.dayEnd,
otherEntries: props.request.otherEntries,
});
});
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 around it. The work moves to make room and keeps its full length."
: "There's no free gap that fits this break, so the surrounding entries will be shifted to make room.";
});
interface PlanLine {
times: string;
label: string;
}
const changeSummary = computed<PlanLine[]>(() => {
const req = props.request;
if (!req) return [];
const range = (interval: Interval) => `${fmt(interval.start)}–${fmt(interval.end)}`;
const moved = (from: Interval, to: Interval) => `${range(from)} → ${range(to)}`;
if (mode.value === 'split') {
const plan = splitPlan.value;
if (!plan) return [];
const workLabel = props.entryLabel(req.workEntries[0]!.id);
return [
{ times: range(plan.firstHalf), label: workLabel },
{ times: range(plan.breakSlot), label: 'Break' },
{ times: range(plan.secondHalf), label: workLabel },
...plan.shifted.map((shift) => ({
times: moved(req.otherEntries.find((e) => e.id === shift.id)!, shift),
label: props.entryLabel(shift.id),
})),
];
}
const plan = movePlan.value;
if (!plan) return [];
if (plan.shifted.length === 0) return [{ times: 'No entries need to move.', label: '' }];
return plan.shifted.map((shift) => {
const original =
req.workEntries.find((e) => e.id === shift.id) ??
req.otherEntries.find((e) => e.id === shift.id)!;
return { times: moved(original, shift), label: props.entryLabel(shift.id) };
});
});
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="flex items-baseline gap-2">
<span class="tabular-nums whitespace-nowrap">{{ line.times }}</span>
<span v-if="line.label" class="text-text-tertiary truncate">
{{ line.label }}
</span>
</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 has to sit inside the work, leaving at least a minute of work on each side, and the work around it has to stay inside the day."
: "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>

View File

@@ -93,26 +93,4 @@ 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();
});
}); });

View File

@@ -18,7 +18,6 @@ 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;
}>(); }>();
@@ -31,16 +30,6 @@ 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';
@@ -62,7 +51,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="isReadonly" :delay-duration="100"> <TooltipProvider v-if="hasRunningEntry" :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">
@@ -79,7 +68,7 @@ const inputClass = computed(() => {
disabled:opacity-50 disabled:cursor-not-allowed" /> disabled:opacity-50 disabled:cursor-not-allowed" />
</span> </span>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent>{{ readonlyTooltip }}</TooltipContent> <TooltipContent> Stop the running time entry to edit the timesheet </TooltipContent>
</Tooltip> </Tooltip>
</TooltipProvider> </TooltipProvider>
<template v-else> <template v-else>

View File

@@ -2,9 +2,6 @@
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';
@@ -29,8 +26,6 @@ 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[];
@@ -44,7 +39,6 @@ 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<{
@@ -80,34 +74,9 @@ 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 <div class="text-xs font-medium text-text-secondary">
class="flex items-center justify-center gap-1 text-xs font-medium text-text-secondary"> {{ dayjs(day).format('ddd D') }}
<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
@@ -116,7 +85,7 @@ const emit = defineEmits<{
</div> </div>
<div class="bg-background dark:bg-secondary"></div> <div class="bg-background dark:bg-secondary"></div>
<!-- Data rows (break row is pinned last) --> <!-- Data rows -->
<TimesheetRow <TimesheetRow
v-for="row in rows" v-for="row in rows"
:key="row.key" :key="row.key"
@@ -171,9 +140,9 @@ const emit = defineEmits<{
</TimeTrackerProjectTaskDropdown> </TimeTrackerProjectTaskDropdown>
</div> </div>
<!-- Totals row: worked time, with break time annotated below (calendar-style) --> <!-- Totals row -->
<div <div
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"> 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">
Total Total
</div> </div>
<div <div
@@ -181,32 +150,18 @@ const emit = defineEmits<{
:key="dayIndex" :key="dayIndex"
data-testid="timesheet_day_total" data-testid="timesheet_day_total"
:class="[ :class="[
'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', 'flex items-center justify-center border-t border-default-background-separator bg-background dark:bg-secondary px-2 py-1 text-xs font-medium',
weekDays[dayIndex] === todayDate weekDays[dayIndex] === todayDate
? 'text-text-primary' ? 'text-text-primary'
: 'text-text-secondary', : 'text-text-secondary',
]"> ]">
<span <span class="w-[80px] text-center">
>{{ formatDuration(total) {{ total > 0 ? formatDuration(total) : '-' }}
}}<template v-if="total > 0 && (breakDayTotals[dayIndex] ?? 0) > 0"> </span>
work</template
></span
>
<span
v-if="(breakDayTotals[dayIndex] ?? 0) > 0"
class="font-normal text-text-tertiary"
>{{ formatDuration(breakDayTotals[dayIndex] ?? 0) }} break</span
>
</div> </div>
<div <div
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"> 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">
<span {{ weekTotalFormatted }}
>{{ weekTotalFormatted
}}<template v-if="breakGrandTotal > 0"> work</template></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>

View File

@@ -1,8 +1,6 @@
<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';
@@ -24,7 +22,6 @@ 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;
@@ -65,11 +62,6 @@ 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;
@@ -82,13 +74,7 @@ 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 <div class="flex-1 min-w-0">
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"
@@ -108,13 +94,11 @@ 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
@@ -131,7 +115,6 @@ 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)" />
@@ -143,11 +126,10 @@ function hasRunningEntry(dayIndex: number): boolean {
{{ rowTotalFormatted }} {{ rowTotalFormatted }}
</div> </div>
<!-- Remove action (the break row is permanent while breaks are enabled) --> <!-- Remove action -->
<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"

View File

@@ -2,17 +2,10 @@
import { BellAlertIcon, XMarkIcon } from '@heroicons/vue/20/solid'; import { BellAlertIcon, XMarkIcon } from '@heroicons/vue/20/solid';
import { SecondaryButton } from '@/packages/ui/src'; import { SecondaryButton } from '@/packages/ui/src';
import { useStorage } from '@vueuse/core'; import { useStorage } from '@vueuse/core';
import { router } from '@inertiajs/vue3'; const showReleaseInfo = useStorage('showReleaseInfo-desktop', true);
import { getCurrentOrganizationId } from '@/utils/useUser';
import { canUpdateOrganization } from '@/utils/permissions';
const showReleaseInfo = useStorage('showReleaseInfo-breaks', true);
function openOrganizationSettings() { function openDesktopGithubRepo() {
router.visit(route('organizations.show', getCurrentOrganizationId())); window.open('https://github.com/solidtime-io/solidtime-desktop', '_blank')?.focus();
}
function openBreaksDocs() {
window.open('https://docs.solidtime.io/user-guide/breaks', '_blank')?.focus();
} }
</script> </script>
@@ -23,7 +16,7 @@ function openBreaksDocs() {
<div <div
class="text-xs pb-1.5 font-semibold text-text-tertiary flex items-center space-x-1"> class="text-xs pb-1.5 font-semibold text-text-tertiary flex items-center space-x-1">
<BellAlertIcon class="w-3.5"></BellAlertIcon> <BellAlertIcon class="w-3.5"></BellAlertIcon>
<span> New Feature </span> <span> New Update </span>
</div> </div>
<button> <button>
<XMarkIcon <XMarkIcon
@@ -33,22 +26,14 @@ function openBreaksDocs() {
</div> </div>
<p class="text-xs"> <p class="text-xs">
<span class="font-semibold">Breaks</span> are here! Enable them in the organization <span class="font-semibold">Solidtime Desktop Beta</span> is here! Test our brand
settings to track break time in the time tracker and timesheet. new clients for Windows, macOS and Linux now.
</p> </p>
<SecondaryButton <SecondaryButton
v-if="canUpdateOrganization()"
size="small" size="small"
class="w-full text-center justify-center mt-1.5" class="w-full text-center justify-center mt-1.5"
@click="openOrganizationSettings" @click="openDesktopGithubRepo"
>Enable now</SecondaryButton >Download now</SecondaryButton
>
<SecondaryButton
v-else
size="small"
class="w-full text-center justify-center mt-1.5"
@click="openBreaksDocs"
>Learn more</SecondaryButton
> >
</div> </div>
</div> </div>

View File

@@ -31,9 +31,6 @@ 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.
@@ -131,7 +128,6 @@ 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"

View File

@@ -11,8 +11,8 @@ import ClientCreateModal from '@/Components/Common/Client/ClientCreateModal.vue'
import PageTitle from '@/Components/Common/PageTitle.vue'; import PageTitle from '@/Components/Common/PageTitle.vue';
import { canCreateClients } from '@/utils/permissions'; import { canCreateClients } from '@/utils/permissions';
import { TabBar, TabBarItem } from '@/packages/ui/src'; import { TabBar, TabBarItem } from '@/packages/ui/src';
import { useTableSortState } from '@/utils/useTableSortState'; import { useStorage } from '@vueuse/core';
import type { SortColumn } from '@/Components/Common/Client/ClientTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Client/ClientTable.vue';
const { clients } = useClientsQuery(); const { clients } = useClientsQuery();
@@ -20,10 +20,25 @@ const activeTab = ref<'active' | 'archived'>('active');
const createClient = ref(false); const createClient = ref(false);
const { tableState, handleSort } = useTableSortState<SortColumn>('client-table-state', { interface ClientTableState {
sortColumn: 'name', sortColumn: SortColumn;
sortDirection: 'asc', sortDirection: SortDirection;
}); }
const tableState = useStorage<ClientTableState>(
'client-table-state',
{
sortColumn: 'name',
sortDirection: 'asc',
},
undefined,
{ mergeDefaults: true }
);
function handleSort(column: SortColumn, direction: SortDirection) {
tableState.value.sortColumn = column;
tableState.value.sortDirection = direction;
}
const shownClients = computed(() => { const shownClients = computed(() => {
return clients.value.filter((client) => { return clients.value.filter((client) => {

View File

@@ -12,8 +12,8 @@ import type { Role } from '@/types/jetstream';
import PageTitle from '@/Components/Common/PageTitle.vue'; import PageTitle from '@/Components/Common/PageTitle.vue';
import InvitationTable from '@/Components/Common/Invitation/InvitationTable.vue'; import InvitationTable from '@/Components/Common/Invitation/InvitationTable.vue';
import { canCreateInvitations } from '@/utils/permissions'; import { canCreateInvitations } from '@/utils/permissions';
import { useTableSortState } from '@/utils/useTableSortState'; import { useStorage } from '@vueuse/core';
import type { SortColumn } from '@/Components/Common/Member/MemberTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Member/MemberTable.vue';
const inviteMember = ref(false); const inviteMember = ref(false);
@@ -23,10 +23,25 @@ defineProps<{
const activeTab = ref<'all' | 'invitations'>('all'); const activeTab = ref<'all' | 'invitations'>('all');
const { tableState, handleSort } = useTableSortState<SortColumn>('member-table-state', { interface MemberTableState {
sortColumn: 'name', sortColumn: SortColumn;
sortDirection: 'asc', sortDirection: SortDirection;
}); }
const tableState = useStorage<MemberTableState>(
'member-table-state',
{
sortColumn: 'name',
sortDirection: 'asc',
},
undefined,
{ mergeDefaults: true }
);
function handleSort(column: SortColumn, direction: SortDirection) {
tableState.value.sortColumn = column;
tableState.value.sortDirection = direction;
}
</script> </script>
<template> <template>

View File

@@ -15,7 +15,6 @@ import {
import { Link } from '@inertiajs/vue3'; import { Link } from '@inertiajs/vue3';
import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue'; import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue';
import TaskTable from '@/Components/Common/Task/TaskTable.vue'; import TaskTable from '@/Components/Common/Task/TaskTable.vue';
import type { SortColumn } from '@/Components/Common/Task/TaskTable.vue';
import CardTitle from '@/packages/ui/src/CardTitle.vue'; import CardTitle from '@/packages/ui/src/CardTitle.vue';
import Card from '@/Components/Common/Card.vue'; import Card from '@/Components/Common/Card.vue';
import ProjectMemberTable from '@/Components/Common/ProjectMember/ProjectMemberTable.vue'; import ProjectMemberTable from '@/Components/Common/ProjectMember/ProjectMemberTable.vue';
@@ -30,7 +29,6 @@ import { formatCents } from '../packages/ui/src/utils/money';
import { getOrganizationCurrencyString } from '../utils/money'; import { getOrganizationCurrencyString } from '../utils/money';
import { useOrganizationQuery } from '@/utils/useOrganizationQuery'; import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
import { getCurrentOrganizationId } from '@/utils/useUser'; import { getCurrentOrganizationId } from '@/utils/useUser';
import { useTableSortState } from '@/utils/useTableSortState';
const { projects } = useProjectsQuery(); const { projects } = useProjectsQuery();
@@ -67,11 +65,6 @@ const activeTab = ref<'active' | 'done'>('active');
const { tasks } = useTasksQuery(); const { tasks } = useTasksQuery();
const { tableState, handleSort } = useTableSortState<SortColumn>('task-table-state', {
sortColumn: 'name',
sortDirection: 'asc',
});
const shownTasks = computed(() => { const shownTasks = computed(() => {
return tasks.value.filter((task) => { return tasks.value.filter((task) => {
if (activeTab.value === 'active') { if (activeTab.value === 'active') {
@@ -166,12 +159,7 @@ const shownTasks = computed(() => {
</template> </template>
</CardTitle> </CardTitle>
<Card> <Card>
<TaskTable <TaskTable :tasks="shownTasks" :project-id="projectId"></TaskTable>
:tasks="shownTasks"
:project-id="projectId"
:sort-column="tableState.sortColumn"
:sort-direction="tableState.sortDirection"
@sort="handleSort"></TaskTable>
</Card> </Card>
</div> </div>
<div v-if="canViewProjectMembers()"> <div v-if="canViewProjectMembers()">

View File

@@ -1,12 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import AppLayout from '@/Layouts/AppLayout.vue';
import MainContainer from '@/packages/ui/src/MainContainer.vue'; import MainContainer from '@/packages/ui/src/MainContainer.vue';
import AppLayout from '@/Layouts/AppLayout.vue';
import { FolderIcon, PlusIcon } from '@heroicons/vue/20/solid'; import { FolderIcon, PlusIcon } from '@heroicons/vue/20/solid';
import { Search } from '@lucide/vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue'; import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import ProjectTable from '@/Components/Common/Project/ProjectTable.vue'; import ProjectTable from '@/Components/Common/Project/ProjectTable.vue';
import TextInput from '@/packages/ui/src/Input/TextInput.vue'; import { computed } from 'vue';
import { computed, ref } from 'vue';
import { useProjectsQuery } from '@/utils/useProjectsQuery'; import { useProjectsQuery } from '@/utils/useProjectsQuery';
import { useProjectsStore } from '@/utils/useProjects'; import { useProjectsStore } from '@/utils/useProjects';
import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue'; import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue';
@@ -20,7 +18,6 @@ import { getCurrentOrganizationId, getCurrentRole } from '@/utils/useUser';
import { useOrganizationQuery } from '@/utils/useOrganizationQuery'; import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
import { isAllowedToPerformPremiumAction } from '@/utils/billing'; import { isAllowedToPerformPremiumAction } from '@/utils/billing';
import { useStorage } from '@vueuse/core'; import { useStorage } from '@vueuse/core';
import { useTableSortState } from '@/utils/useTableSortState';
import ProjectsFilterDropdown from '@/Components/Common/Project/ProjectsFilterDropdown.vue'; import ProjectsFilterDropdown from '@/Components/Common/Project/ProjectsFilterDropdown.vue';
import ProjectStatusFilterBadge from '@/Components/Common/Project/ProjectStatusFilterBadge.vue'; import ProjectStatusFilterBadge from '@/Components/Common/Project/ProjectStatusFilterBadge.vue';
import ProjectVisibilityFilterBadge from '@/Components/Common/Project/ProjectVisibilityFilterBadge.vue'; import ProjectVisibilityFilterBadge from '@/Components/Common/Project/ProjectVisibilityFilterBadge.vue';
@@ -29,7 +26,7 @@ import { NO_CLIENT_ID } from '@/Components/Common/Project/constants';
import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue';
// Fetch data using TanStack Query // Fetch data using TanStack Query
const { projects, isLoading: projectsLoading } = useProjectsQuery(); const { projects } = useProjectsQuery();
const { clients } = useClientsQuery(); const { clients } = useClientsQuery();
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!); const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
@@ -44,7 +41,7 @@ interface ProjectTableState {
}; };
} }
const { tableState, handleSort } = useTableSortState<SortColumn, ProjectTableState>( const tableState = useStorage<ProjectTableState>(
'project-table-state', 'project-table-state',
{ {
sortColumn: 'name', sortColumn: 'name',
@@ -55,28 +52,24 @@ const { tableState, handleSort } = useTableSortState<SortColumn, ProjectTableSta
visibility: 'all', visibility: 'all',
}, },
}, },
// The filters are merged key by key so a stored value missing a newer filter still undefined,
// picks up its default instead of the whole object falling back. {
(storage, defaults) => ({ mergeDefaults: (storage, defaults) => ({
...defaults, ...defaults,
...storage, ...storage,
filters: { ...defaults.filters, ...storage.filters }, filters: { ...defaults.filters, ...storage.filters },
}) }),
}
); );
// Not persisted, so a reload never starts silently filtered function handleSort(column: SortColumn, direction: SortDirection) {
const search = ref(''); tableState.value.sortColumn = column;
tableState.value.sortDirection = direction;
}
// Filter projects based on current filters // Filter projects based on current filters
const filteredProjects = computed(() => { const filteredProjects = computed(() => {
const searchTerm = search.value.trim().toLowerCase();
return projects.value.filter((project) => { return projects.value.filter((project) => {
// Name search
if (searchTerm && !project.name.toLowerCase().includes(searchTerm)) {
return false;
}
// Status filter // Status filter
if (tableState.value.filters.status === 'active' && project.is_archived) { if (tableState.value.filters.status === 'active' && project.is_archived) {
return false; return false;
@@ -110,15 +103,6 @@ const filteredProjects = computed(() => {
}); });
}); });
const hasActiveFilters = computed(() => {
return (
search.value.trim() !== '' ||
tableState.value.filters.status !== 'all' ||
tableState.value.filters.visibility !== 'all' ||
tableState.value.filters.clientIds.length > 0
);
});
// Helper functions for active filters // Helper functions for active filters
function removeStatusFilter() { function removeStatusFilter() {
tableState.value.filters.status = 'all'; tableState.value.filters.status = 'all';
@@ -151,7 +135,8 @@ const showBillableRate = computed(() => {
<template> <template>
<AppLayout title="Projects" data-testid="projects_view"> <AppLayout title="Projects" data-testid="projects_view">
<MainContainer class="py-3 sm:pt-5 flex justify-between items-center"> <MainContainer
class="py-3 sm:pt-5 border-b border-default-background-separator flex justify-between items-center">
<div class="flex items-center space-x-3 sm:space-x-6"> <div class="flex items-center space-x-3 sm:space-x-6">
<PageTitle :icon="FolderIcon" title="Projects"></PageTitle> <PageTitle :icon="FolderIcon" title="Projects"></PageTitle>
</div> </div>
@@ -204,25 +189,11 @@ const showBillableRate = computed(() => {
:clients="clients" :clients="clients"
@remove="removeClientFilter" @remove="removeClientFilter"
@update:value="tableState.filters.clientIds = $event as string[]" /> @update:value="tableState.filters.clientIds = $event as string[]" />
<div class="relative">
<Search
class="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-icon-default" />
<TextInput
v-model="search"
size="sm"
type="search"
aria-label="Search projects"
placeholder="Search projects..."
class="w-60 border-transparent bg-transparent pl-7 shadow-none placeholder:text-text-tertiary hover:bg-black/5 focus-visible:bg-input-background dark:hover:bg-white/5 [&::-webkit-search-cancel-button]:hidden" />
</div>
</div> </div>
</MainContainer> </MainContainer>
<ProjectTable <ProjectTable
:show-billable-rate="showBillableRate" :show-billable-rate="showBillableRate"
:is-filtered="hasActiveFilters"
:is-loading="projectsLoading"
:projects="filteredProjects" :projects="filteredProjects"
:sort-column="tableState.sortColumn" :sort-column="tableState.sortColumn"
:sort-direction="tableState.sortDirection" :sort-direction="tableState.sortDirection"

View File

@@ -74,7 +74,6 @@ 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);
@@ -107,7 +106,6 @@ 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,
}; };
@@ -331,7 +329,6 @@ 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"

View File

@@ -116,43 +116,25 @@ const subGroup = computed(() => {
} }
return 'project'; return 'project';
}); });
const { emptyPlaceholder, getNameForReportingRowEntry } = useReportingStore(); const { emptyPlaceholder } = useReportingStore();
/**
* The public report endpoint has no descriptor for time group types, so their labels are
* derived from the raw group key.
*/
function resolveLabel(
description: string | null | undefined,
key: string | null | undefined,
groupedType: string
) {
if (description !== null && description !== undefined) {
return description;
}
return (
getNameForReportingRowEntry(key ?? null, groupedType, reportDateFormat.value) ??
emptyPlaceholder[groupedType] ??
''
);
}
const groupedPieChartData = computed(() => { const groupedPieChartData = computed(() => {
return ( return (
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => { aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
const groupedType = aggregatedTableTimeEntries.value?.grouped_type ?? 'project'; if (entry.description === null) {
const name = resolveLabel(entry.description, entry.key, groupedType);
if (name === emptyPlaceholder[groupedType]) {
return { return {
value: entry.seconds, value: entry.seconds,
name: name, name:
emptyPlaceholder[
aggregatedTableTimeEntries.value?.grouped_type ?? 'project'
] ?? '',
color: '#CCCCCC', color: '#CCCCCC',
}; };
} }
return { return {
value: entry.seconds, value: entry.seconds,
name: name, name: entry.description,
color: entry.color ?? getRandomColorWithSeed(name), color: entry.color ?? getRandomColorWithSeed(entry.description ?? 'none'),
}; };
}) ?? [] }) ?? []
); );
@@ -161,25 +143,21 @@ const groupedPieChartData = computed(() => {
const tableData = computed(() => { const tableData = computed(() => {
return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => { return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
return { return {
key: entry.key,
seconds: entry.seconds, seconds: entry.seconds,
cost: entry.cost, cost: entry.cost,
description: resolveLabel( description:
entry.description, entry.description ??
entry.key, emptyPlaceholder[aggregatedTableTimeEntries.value?.grouped_type ?? 'project'] ??
aggregatedTableTimeEntries.value?.grouped_type ?? 'project' '',
),
grouped_data: grouped_data:
entry.grouped_data?.map((el) => { entry.grouped_data?.map((el) => {
return { return {
key: el.key,
seconds: el.seconds, seconds: el.seconds,
cost: el.cost, cost: el.cost,
description: resolveLabel( description:
el.description, el.description ??
el.key, emptyPlaceholder[entry.grouped_type ?? 'project'] ??
entry.grouped_type ?? 'project' '',
),
}; };
}) ?? [], }) ?? [],
}; };
@@ -241,7 +219,7 @@ onMounted(async () => {
"> ">
<ReportingRow <ReportingRow
v-for="entry in tableData" v-for="entry in tableData"
:key="entry.key ?? 'none'" :key="entry.description ?? 'none'"
:currency="reportCurrency" :currency="reportCurrency"
:currency-format="reportCurrencyFormat" :currency-format="reportCurrencyFormat"
:show-cost="true" :show-cost="true"

View File

@@ -9,15 +9,30 @@ import TagCreateModal from '@/packages/ui/src/Tag/TagCreateModal.vue';
import PageTitle from '@/Components/Common/PageTitle.vue'; import PageTitle from '@/Components/Common/PageTitle.vue';
import { canCreateTags } from '@/utils/permissions'; import { canCreateTags } from '@/utils/permissions';
import { useTagsStore } from '@/utils/useTags'; import { useTagsStore } from '@/utils/useTags';
import { useTableSortState } from '@/utils/useTableSortState'; import { useStorage } from '@vueuse/core';
import type { SortColumn } from '@/Components/Common/Tag/TagTable.vue'; import type { SortColumn, SortDirection } from '@/Components/Common/Tag/TagTable.vue';
const showCreateTagModal = ref(false); const showCreateTagModal = ref(false);
const { tableState, handleSort } = useTableSortState<SortColumn>('tag-table-state', { interface TagTableState {
sortColumn: 'name', sortColumn: SortColumn;
sortDirection: 'asc', sortDirection: SortDirection;
}); }
const tableState = useStorage<TagTableState>(
'tag-table-state',
{
sortColumn: 'name',
sortDirection: 'asc',
},
undefined,
{ mergeDefaults: true }
);
function handleSort(column: SortColumn, direction: SortDirection) {
tableState.value.sortColumn = column;
tableState.value.sortDirection = direction;
}
async function createTag(tag: string) { async function createTag(tag: string) {
return await useTagsStore().createTag(tag); return await useTagsStore().createTag(tag);

View File

@@ -198,7 +198,7 @@ const showResultModal = ref(false);
for="file-upload" for="file-upload"
class="relative cursor-pointer rounded-md font-semibold text-text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 focus-within:ring-offset-gray-900 hover:text-indigo-500"> class="relative cursor-pointer rounded-md font-semibold text-text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 focus-within:ring-offset-gray-900 hover:text-indigo-500">
<span v-if="files">{{ filenames }}</span> <span v-if="files">{{ filenames }}</span>
<span v-else>Upload the Export file</span> <span v-else>Upload a Toggl/Clockify Export</span>
<input <input
id="file-upload" id="file-upload"
ref="importFile" ref="importFile"

View File

@@ -17,18 +17,15 @@ 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({
@@ -42,7 +39,6 @@ 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>
@@ -73,10 +69,6 @@ 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>

View File

@@ -1,7 +1,6 @@
<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';
@@ -103,11 +102,6 @@ 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>
@@ -159,7 +153,6 @@ function goToCalendarDay(date: string) {
: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>

Some files were not shown because too many files have changed in this diff Show More