Compare commits

..

30 Commits

Author SHA1 Message Date
Gregor Vostrak
7922af92e2 move Client visibleByEmployee logic to model scope 2025-10-21 11:53:08 +02:00
Alexander Groß
d1d2aedbae Show clients that are assigned to the employee, closes #893 2025-10-17 09:52:15 +02:00
Gregor Vostrak
19a206d57c add prevent_overlapping_time_entries setting to organization
when enabled users are blocked from creating or editing new time entries that are overlapping with other time entries
2025-10-13 14:23:41 +02:00
Gregor Vostrak
c0788c270b fix typescript openapi mapping types 2025-10-07 17:42:44 +02:00
Gregor Vostrak
7765056074 add tag grouping 2025-10-07 17:15:20 +02:00
Kaspar Rosin
639f5332e4 feat: add duplicate time entry fields 2025-10-07 17:10:22 +02:00
Gregor Vostrak
4a50145329 fix calendar header timezone issue 2025-10-06 19:30:58 +02:00
Gregor Vostrak
8aabffd1e7 fix race condition in UserTimezoneMismatchModal 2025-10-06 18:33:57 +02:00
Gregor Vostrak
b373427dc7 add feedback button in sidebar 2025-10-01 13:20:23 +02:00
Gregor Vostrak
d2a4d60441 clarify UserSettingsIcon Dropdown Profile Settings Item Description 2025-10-01 13:20:23 +02:00
Gregor Vostrak
c3305b3df6 remove bottom padding for toast container
This became redundant due to the floating feedback bubble removal
2025-10-01 13:20:23 +02:00
Gregor Vostrak
7584e59d0b improve focus states and keyboard navigation for organization switcher and user settings dropdown 2025-10-01 13:20:23 +02:00
Gregor Vostrak
d2f75cca6e update organization switcher to use shadcn dropdownmenu 2025-10-01 13:20:23 +02:00
Gregor Vostrak
250379d4bd change profile dropdown to shadcn, add feedback entry 2025-10-01 13:20:23 +02:00
Gregor Vostrak
7f89fd8ea1 fix overflow issues in short calendar events 2025-09-29 12:19:27 +02:00
Gregor Vostrak
0b45f3b473 change create bucket script to work with new minio client versions 2025-09-29 12:09:15 +02:00
Gregor Vostrak
9827a74ae2 lock caddy version to 2.10 to fix docker buiilds 2025-09-08 13:49:43 +02:00
Gregor Vostrak
3425847a44 make time entry create in calendar use minimal interval instead of 1h duration 2025-09-08 13:28:36 +02:00
Gregor Vostrak
47b778fab9 make sure that 0 duration entries are shown correctly in calendar 2025-09-08 13:28:36 +02:00
Gregor Vostrak
85d69f1f16 fix scroll overflow issue in calendar with banner 2025-09-08 13:28:36 +02:00
Gregor Vostrak
fca55fe0e1 improve calendar fetching behaviour to always include prev/next period 2025-09-08 13:28:36 +02:00
Gregor Vostrak
f19abb9db6 make calendar fetch time ranges respect user timezone 2025-09-08 13:28:36 +02:00
Gregor Vostrak
e3bd50ed6b improve contrast of calendar events 2025-09-08 13:28:36 +02:00
Gregor Vostrak
c582530899 add edit time entry dropdown option to timeentryrow 2025-09-08 13:28:36 +02:00
Gregor Vostrak
fb5185a32f fix card background active color contrast in light mode 2025-09-08 13:28:36 +02:00
Gregor Vostrak
0a0854f771 fix recently tracked time entries card placeholders 2025-09-08 13:28:36 +02:00
Gregor Vostrak
4e635cde83 add support for week_start and time_format in calendar
also rename them so that they do not conflict with the datepicker calendar component
2025-09-08 13:28:36 +02:00
Gregor Vostrak
9fa9522237 add calendar view 2025-09-08 13:28:36 +02:00
Gregor Vostrak
04c44097d0 fix duplicated borders in time and detailed reporting view 2025-09-08 13:28:36 +02:00
Gregor Vostrak
3d5a0cb974 add timezone mismatch modal 2025-09-08 13:28:36 +02:00
57 changed files with 2576 additions and 1906 deletions

View File

@@ -20,6 +20,7 @@ enum TimeEntryAggregationType: string
case Client = 'client';
case Billable = 'billable';
case Description = 'description';
case Tag = 'tag';
public static function fromInterval(TimeEntryAggregationTypeInterval $timeEntryAggregationTypeInterval): TimeEntryAggregationType
{

View File

@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace App\Exceptions\Api;
class OverlappingTimeEntryApiException extends ApiException
{
public const string KEY = 'overlapping_time_entry';
}

View File

@@ -38,11 +38,17 @@ class ClientController extends Controller
public function index(Organization $organization, ClientIndexRequest $request): ClientCollection
{
$this->checkPermission($organization, 'clients:view');
$canViewAllClients = $this->hasPermission($organization, 'clients:view:all');
$user = $this->user();
$clientsQuery = Client::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc');
if (! $canViewAllClients) {
$clientsQuery->visibleByEmployee($user);
}
$filterArchived = $request->getFilterArchived();
if ($filterArchived === 'true') {
$clientsQuery->whereNotNull('archived_at');

View File

@@ -61,6 +61,9 @@ class OrganizationController extends Controller
if ($request->getTimeFormat() !== null) {
$organization->time_format = $request->getTimeFormat();
}
if ($request->getPreventOverlappingTimeEntries() !== null) {
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
}
$hasBillableRate = $request->has('billable_rate');
if ($hasBillableRate) {
$oldBillableRate = $organization->billable_rate;

View File

@@ -7,6 +7,7 @@ namespace App\Http\Controllers\Api\V1;
use App\Enums\ExportFormat;
use App\Enums\Role;
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
use App\Exceptions\Api\OverlappingTimeEntryApiException;
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
use App\Exceptions\Api\TimeEntryStillRunningApiException;
@@ -45,6 +46,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\File;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
@@ -56,6 +58,43 @@ use Spatie\TemporaryDirectory\TemporaryDirectory;
class TimeEntryController extends Controller
{
private function assertNoOverlap(Organization $organization, Member $member, \Illuminate\Support\Carbon $start, ?\Illuminate\Support\Carbon $end, ?TimeEntry $exclude = null): void
{
if (! $organization->prevent_overlapping_time_entries) {
return;
}
$query = TimeEntry::query()
->where('organization_id', $organization->getKey())
->where('user_id', $member->user_id)
->when($exclude !== null, function (Builder $q) use ($exclude): void {
$q->where('id', '!=', $exclude->getKey());
})
->where(function (Builder $q) use ($start, $end): void {
$q->where(function (Builder $q2) use ($start): void {
$q2->where('end', '>', $start)
->where('start', '<', $start);
});
if ($end !== null) {
$q->orWhere(function (Builder $q4) use ($end): void {
$q4->where('start', '<', $end)
->where('end', '>', $end);
});
// Check if the new entry completely surrounds an existing entry
$q->orWhere(function (Builder $q6) use ($start, $end): void {
$q6->where('start', '>=', $start)
->where('end', '<=', $end);
});
}
});
if ($query->exists()) {
throw new OverlappingTimeEntryApiException;
}
}
protected function checkPermission(Organization $organization, string $permission, ?TimeEntry $timeEntry = null): void
{
parent::checkPermission($organization, $permission);
@@ -549,17 +588,15 @@ class TimeEntryController extends Controller
throw new TimeEntryStillRunningApiException;
}
// Overlap check for create
$start = Carbon::parse($request->input('start'));
$end = $request->input('end') !== null ? Carbon::parse($request->input('end')) : null;
$this->assertNoOverlap($organization, $member, $start, $end);
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
$client = $project?->client;
$task = $request->input('task_id') !== null ? $project->tasks()->findOrFail((string) $request->input('task_id')) : null;
if ($project !== null) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null) {
RecalculateSpentTimeForTask::dispatch($task);
}
$timeEntry = new TimeEntry;
$timeEntry->fill($request->validated());
$timeEntry->client()->associate($client);
@@ -569,6 +606,13 @@ class TimeEntryController extends Controller
$timeEntry->setComputedAttributeValue('billable_rate');
$timeEntry->save();
if ($project !== null) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null) {
RecalculateSpentTimeForTask::dispatch($task);
}
return new TimeEntryResource($timeEntry);
}
@@ -593,6 +637,13 @@ class TimeEntryController extends Controller
throw new TimeEntryCanNotBeRestartedApiException;
}
// Overlap check for update (exclude current)
/** @var Member $effectiveMember */
$effectiveMember = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : $timeEntry->member;
$effectiveStart = $request->has('start') ? Carbon::parse($request->input('start')) : $timeEntry->start;
$effectiveEnd = $request->has('end') ? ($request->input('end') !== null ? Carbon::parse($request->input('end')) : null) : $timeEntry->end;
$this->assertNoOverlap($organization, $effectiveMember, $effectiveStart, $effectiveEnd, $timeEntry);
$oldProject = $timeEntry->project;
$oldTask = $timeEntry->task;

View File

@@ -41,7 +41,8 @@ class HandleInertiaRequests extends Middleware
{
$hasBilling = Module::has('Billing') && Module::isEnabled('Billing');
$hasInvoicing = Module::has('Invoicing') && Module::isEnabled('Invoicing');
$hasServices = Module::has('Services') && Module::isEnabled('Services');
/** @var BillingContract $billing */
$billing = app(BillingContract::class);
@@ -50,6 +51,7 @@ class HandleInertiaRequests extends Middleware
return array_merge(parent::share($request), [
'has_billing_extension' => $hasBilling,
'has_invoicing_extension' => $hasInvoicing,
'has_services_extension' => $hasServices,
'billing' => $currentOrganization !== null ? [
'has_subscription' => $billing->hasSubscription($currentOrganization),
'has_trial' => $billing->hasTrial($currentOrganization),

View File

@@ -39,6 +39,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
'employees_can_see_billable_rates' => [
'boolean',
],
'prevent_overlapping_time_entries' => [
'boolean',
],
'number_format' => [
Rule::enum(NumberFormat::class),
],
@@ -98,4 +101,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
{
return $this->has('employees_can_see_billable_rates') ? $this->boolean('employees_can_see_billable_rates') : null;
}
public function getPreventOverlappingTimeEntries(): ?bool
{
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
}
}

View File

@@ -53,6 +53,8 @@ class OrganizationResource extends BaseResource
'billable_rate' => $this->showBillableRate ? $this->resource->billable_rate : null,
/** @var bool $employees_can_see_billable_rates Can members of the organization with role "employee" see the billable rates */
'employees_can_see_billable_rates' => $this->resource->employees_can_see_billable_rates,
/** @var bool $prevent_overlapping_time_entries Prevent creating overlapping time entries (only new entries) */
'prevent_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
/** @var string $currency Currency code (ISO 4217) */
'currency' => $this->resource->currency,
/** @var string $currency_symbol Currency symbol */

View File

@@ -7,6 +7,7 @@ namespace App\Models;
use App\Models\Concerns\CustomAuditable;
use App\Models\Concerns\HasUuids;
use Database\Factories\ClientFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -62,6 +63,18 @@ class Client extends Model implements AuditableContract
return $this->hasMany(Project::class, 'client_id');
}
/**
* @param Builder<Client> $builder
* @return Builder<Client>
*/
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
{
return $builder->whereHas('projects', function (Builder $builder) use ($user): Builder {
/** @var Builder<Project> $builder */
return $builder->visibleByEmployee($user);
});
}
/**
* @return Attribute<bool, never>
*/

View File

@@ -70,6 +70,7 @@ class Organization extends JetstreamTeam implements AuditableContract
'personal_team' => 'boolean',
'currency' => 'string',
'employees_can_see_billable_rates' => 'boolean',
'prevent_overlapping_time_entries' => 'boolean',
'number_format' => NumberFormat::class,
'currency_format' => CurrencyFormat::class,
'date_format' => DateFormat::class,

View File

@@ -109,6 +109,7 @@ class JetstreamServiceProvider extends ServiceProvider
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
@@ -172,6 +173,7 @@ class JetstreamServiceProvider extends ServiceProvider
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
@@ -232,6 +234,7 @@ class JetstreamServiceProvider extends ServiceProvider
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
@@ -256,12 +259,13 @@ class JetstreamServiceProvider extends ServiceProvider
'projects:view',
'tags:view',
'tasks:view',
'clients:view',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'organizations:view',
])->description('Employees have the ability to read, create, and update their own time entries and they can see the projects that they are members of.');
])->description('Employees have the ability to read, create, and update their own time entries, they can see the projects that they are members of and the clients they are assigned to.');
Jetstream::role(Role::Placeholder->value, 'Placeholder', [
])->description('Placeholders are used for importing data. They cannot log in and have no permissions.');

View File

@@ -10,6 +10,7 @@ use App\Enums\TimeEntryRoundingType;
use App\Enums\Weekday;
use App\Models\Client;
use App\Models\Project;
use App\Models\Tag;
use App\Models\Task;
use App\Models\TimeEntry;
use App\Models\User;
@@ -17,6 +18,7 @@ use Carbon\CarbonTimeZone;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class TimeEntryAggregationService
@@ -45,9 +47,21 @@ class TimeEntryAggregationService
public function getAggregatedTimeEntries(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end, bool $showBillableRate, ?TimeEntryRoundingType $roundingType, ?int $roundingMinutes): array
{
$fillGapsInTimeGroupsIsPossible = $fillGapsInTimeGroups && $start !== null && $end !== null;
/** @var Builder<TimeEntry> $baseTotalsQuery */
$baseTotalsQuery = $timeEntriesQuery->clone();
$group1Select = null;
$group2Select = null;
$groupBy = null;
// If any grouping is by tag, expand rows per tag and ensure a NULL row for entries without tags
if (($group1Type === TimeEntryAggregationType::Tag) || ($group2Type === TimeEntryAggregationType::Tag)) {
$timeEntriesQuery->crossJoin(DB::raw(
"LATERAL (\n".
" SELECT jsonb_array_elements_text(coalesce(tags, '[]'::jsonb)) AS tag\n".
" UNION ALL\n".
" SELECT ''::text AS tag WHERE coalesce(jsonb_array_length(tags), 0) = 0\n".
') AS tag(tag)'
));
}
if ($group1Type !== null) {
$group1Select = $this->getGroupByQuery($group1Type, $timezone, $startOfWeek);
$groupBy = ['group_1'];
@@ -84,6 +98,26 @@ class TimeEntryAggregationService
$group1Response = [];
$group1ResponseSum = 0;
$group1ResponseCost = 0;
// If Tag is subgroup, prepare base totals per primary group without tag expansion
$baseTotalsPerGroup1Map = [];
if ($group2Type === TimeEntryAggregationType::Tag) {
$baseTotalsPerGroup1Query = $baseTotalsQuery->clone();
$baseTotalsPerGroup1 = $baseTotalsPerGroup1Query
->selectRaw(
$group1Select.' as group_1,'.
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')))) as aggregate,'.
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')) * (coalesce(billable_rate, 0)::float/60/60))) as cost'
)
->groupBy('group_1')
->get();
foreach ($baseTotalsPerGroup1 as $row) {
/** @var object{group_1: mixed, aggregate: int|null, cost: int|null} $row */
$baseTotalsPerGroup1Map[(string) ($row->group_1 ?? '')] = [
'aggregate' => (int) ($row->aggregate ?? 0),
'cost' => (int) ($row->cost ?? 0),
];
}
}
foreach ($groupedAggregates as $group1 => $group1Aggregates) {
/** @var string|int $group1 */
$group2Response = [];
@@ -103,6 +137,14 @@ class TimeEntryAggregationService
$group2ResponseSum += (int) $aggregate->get(0)->aggregate;
$group2ResponseCost += (int) $aggregate->get(0)->cost;
}
// Override primary group totals when Tag is subgroup to avoid double counting
if ($group2Type === TimeEntryAggregationType::Tag) {
$keyForMap = (string) $group1;
if (array_key_exists($keyForMap, $baseTotalsPerGroup1Map)) {
$group2ResponseSum = $baseTotalsPerGroup1Map[$keyForMap]['aggregate'];
$group2ResponseCost = $baseTotalsPerGroup1Map[$keyForMap]['cost'];
}
}
} else {
/** @var Collection<int, object{aggregate: int, cost: int}> $group1Aggregates */
$group2ResponseSum = (int) $group1Aggregates->get(0)->aggregate;
@@ -121,6 +163,23 @@ class TimeEntryAggregationService
$group1ResponseCost += $group2ResponseCost;
}
// If Tag is selected in any grouping, compute overall totals from base (non-tag-expanded) query to avoid double counting
$hasTagGrouping = ($group1Type === TimeEntryAggregationType::Tag) || ($group2Type === TimeEntryAggregationType::Tag);
if ($hasTagGrouping) {
// Reset selects and ordering on the cloned base query
$baseTotals = $baseTotalsQuery
->selectRaw(
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')))) as aggregate,'.
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')) * (coalesce(billable_rate, 0)::float/60/60))) as cost'
)
->first();
if ($baseTotals !== null) {
/** @var object{aggregate: int|null, cost: int|null} $baseTotals */
$group1ResponseSum = (int) ($baseTotals->aggregate ?? 0);
$group1ResponseCost = (int) ($baseTotals->cost ?? 0);
}
}
if ($fillGapsInTimeGroupsIsPossible) {
$group1Response = $this->fillGapsInTimeGroups($group1Response, $group1Type, $group2Type, $timezone, $startOfWeek, $start, $end);
}
@@ -294,6 +353,17 @@ class TimeEntryAggregationService
'color' => null,
];
}
} elseif ($type === TimeEntryAggregationType::Tag) {
$tags = Tag::query()
->whereIn('id', $keys)
->select('id', 'name')
->get();
foreach ($tags as $tag) {
$descriptorMap[$tag->id] = [
'description' => $tag->name,
'color' => null,
];
}
}
return $descriptorMap;
@@ -436,6 +506,8 @@ class TimeEntryAggregationService
return 'billable';
} elseif ($group === TimeEntryAggregationType::Description) {
return 'description';
} elseif ($group === TimeEntryAggregationType::Tag) {
return 'tag';
}
}

View File

@@ -0,0 +1,30 @@
<?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
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('organizations', function (Blueprint $table): void {
$table->boolean('prevent_overlapping_time_entries')->default(false)->after('employees_can_see_billable_rates');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('organizations', function (Blueprint $table): void {
$table->dropColumn('prevent_overlapping_time_entries');
});
}
};

View File

@@ -2,7 +2,7 @@
# Source: https://helgesver.re/articles/laravel-sail-create-minio-bucket-automatically
/usr/bin/mc config host add local ${S3_ENDPOINT} ${S3_ACCESS_KEY_ID} ${S3_SECRET_ACCESS_KEY};
/usr/bin/mc alias set local ${S3_ENDPOINT} ${S3_ACCESS_KEY_ID} ${S3_SECRET_ACCESS_KEY};
/usr/bin/mc rm -r --force local/${S3_BUCKET};
/usr/bin/mc mb --ignore-existing local/${S3_BUCKET};
/usr/bin/mc anonymous set public local/${S3_BUCKET};

View File

@@ -16,7 +16,7 @@ RUN CGO_ENABLED=1 \
XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \
CGO_CFLAGS=$(php-config --includes) \
CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \
xcaddy build \
xcaddy build v2.10.0 \
--output /usr/local/bin/frankenphp \
--with github.com/dunglas/frankenphp=./ \
--with github.com/dunglas/frankenphp/caddy=./caddy/ \

View File

@@ -1,508 +0,0 @@
import { expect, Page, Browser } from '@playwright/test';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { test } from '../playwright/fixtures';
async function goToSharedReports(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting/shared');
}
async function goToReporting(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting');
}
async function createTimeEntryWithProject(page: Page, projectName: string, duration: string) {
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
await page.getByRole('button', { name: 'Create Project' }).click();
await page.getByLabel('Project Name').fill(projectName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Project' }).click();
await page.getByText(projectName).waitFor({ state: 'visible' });
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill(`Time entry for ${projectName}`);
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await Promise.all([
page.getByRole('button', { name: 'Create Time Entry' }).click(),
page.waitForResponse(
(response) => response.url().includes('/time-entries') && response.status() === 201
),
]);
}
async function createTimeEntryWithTag(page: Page, tagName: string, duration: string) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill(`Time entry with tag ${tagName}`);
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createTimeEntryWithBillableStatus(
page: Page,
isBillable: boolean,
duration: string
) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page
.getByTestId('time_entry_description')
.fill(`Time entry ${isBillable ? 'billable' : 'non-billable'}`);
await page.getByRole('button', { name: 'Non-Billable' }).click();
if (!isBillable) {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
}
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createReport(
page: Page,
reportName: string,
options: {
projectFilter?: string;
tagFilter?: string;
billableFilter?: 'billable' | 'non-billable' | 'all';
timeRange?: { start: string; end: string };
} = {}
) {
await goToReporting(page);
await page.waitForLoadState('networkidle');
// Apply filters if specified
if (options.projectFilter) {
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(options.projectFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.tagFilter) {
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText(options.tagFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.billableFilter && options.billableFilter !== 'all') {
await page.getByRole('button', { name: 'Billable' }).click();
if (options.billableFilter === 'billable') {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
}
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
// Set custom time range if specified
if (options.timeRange) {
await page.getByRole('button', { name: 'This Week' }).click();
await page.getByRole('option', { name: 'Custom Range' }).click();
await page.locator('input[name="startDate"]').fill(options.timeRange.start);
await page.locator('input[name="endDate"]').fill(options.timeRange.end);
await page.getByRole('button', { name: 'Apply' }).click();
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
await page.waitForLoadState('networkidle');
// Save the report
await page.getByRole('button', { name: 'Save Report' }).click();
await page.getByLabel('Report Name').fill(reportName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Report' }).click();
await page.waitForLoadState('networkidle');
}
async function makeReportPublic(page: Page, reportName: string): Promise<string> {
await goToSharedReports(page);
await page.waitForLoadState('networkidle');
// Find the report row and click the edit button
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
// Make the report public
await page.getByRole('switch', { name: 'Make report public' }).click();
// Wait for the API response
await page.waitForResponse(
(response) => response.url().includes('/reports/') && response.status() === 200
);
// Save the changes
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Get the public URL
const copyButton = reportRow.getByRole('button', { name: 'Copy URL' });
await copyButton.click();
// Extract the URL from clipboard or from the button's data attribute
const publicUrl = await page.evaluate(() => navigator.clipboard.readText());
return publicUrl;
}
async function createUnauthenticatedPage(browser: Browser): Promise<Page> {
const context = await browser.newContext();
const page = await context.newPage();
return page;
}
test('access public shared report without authentication', async ({ page, browser }) => {
const projectName = 'Public Access Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Public Access Report ' + Math.floor(Math.random() * 10000);
// Create test data with authenticated user
await createTimeEntryWithProject(page, projectName, '2h 30min');
// Create and make report public
await createReport(page, reportName, { projectFilter: projectName });
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify the report is accessible and displays data
await expect(unauthenticatedPage.getByText(reportName)).toBeVisible();
await expect(unauthenticatedPage.getByText(projectName)).toBeVisible();
await expect(unauthenticatedPage.getByText('2h 30min')).toBeVisible();
// Verify no authentication elements are present
await expect(unauthenticatedPage.getByRole('button', { name: 'Login' })).not.toBeVisible();
await expect(unauthenticatedPage.getByRole('button', { name: 'Register' })).not.toBeVisible();
await unauthenticatedPage.close();
});
test('access public shared report with project filter shows filtered data', async ({
page,
browser,
}) => {
const projectName = 'Filtered Project ' + Math.floor(Math.random() * 10000);
const otherProjectName = 'Other Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Filtered Report ' + Math.floor(Math.random() * 10000);
// Create test data for two projects
await createTimeEntryWithProject(page, projectName, '1h 30min');
await createTimeEntryWithProject(page, otherProjectName, '45min');
// Create and make report public with project filter
await createReport(page, reportName, { projectFilter: projectName });
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify only filtered project data is shown
await expect(unauthenticatedPage.getByText(projectName)).toBeVisible();
await expect(unauthenticatedPage.getByText(otherProjectName)).not.toBeVisible();
await expect(unauthenticatedPage.getByText('1h 30min')).toBeVisible();
await expect(unauthenticatedPage.getByText('45min')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('access public shared report with tag filter shows filtered data', async ({
page,
browser,
}) => {
const tagName = 'PublicTag' + Math.floor(Math.random() * 10000);
const otherTagName = 'PrivateTag' + Math.floor(Math.random() * 10000);
const reportName = 'Tag Filtered Report ' + Math.floor(Math.random() * 10000);
// Create test data for two tags
await createTimeEntryWithTag(page, tagName, '2h');
await createTimeEntryWithTag(page, otherTagName, '1h');
// Create and make report public with tag filter
await createReport(page, reportName, { tagFilter: tagName });
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify only filtered tag data is shown
await expect(unauthenticatedPage.getByText(tagName)).toBeVisible();
await expect(unauthenticatedPage.getByText(otherTagName)).not.toBeVisible();
await expect(unauthenticatedPage.getByText('2h 00min')).toBeVisible();
await expect(unauthenticatedPage.getByText('1h 00min')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('access public shared report with billable filter shows filtered data', async ({
page,
browser,
}) => {
const reportName = 'Billable Filtered Report ' + Math.floor(Math.random() * 10000);
// Create test data for billable and non-billable entries
await createTimeEntryWithBillableStatus(page, true, '3h');
await createTimeEntryWithBillableStatus(page, false, '1h 30min');
// Create and make report public with billable filter
await createReport(page, reportName, { billableFilter: 'billable' });
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify only billable data is shown
await expect(unauthenticatedPage.getByText('3h 00min')).toBeVisible();
await expect(unauthenticatedPage.getByText('1h 30min')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('access public shared report with custom time range shows filtered data', async ({
page,
browser,
}) => {
const projectName = 'TimeRange Project ' + Math.floor(Math.random() * 10000);
const reportName = 'TimeRange Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '2h 15min');
// Create and make report public with custom time range
const startDate = new Date();
startDate.setDate(startDate.getDate() - 7);
const endDate = new Date();
await createReport(page, reportName, {
projectFilter: projectName,
timeRange: {
start: startDate.toISOString().split('T')[0],
end: endDate.toISOString().split('T')[0],
},
});
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify the data is shown within the time range
await expect(unauthenticatedPage.getByText(projectName)).toBeVisible();
await expect(unauthenticatedPage.getByText('2h 15min')).toBeVisible();
await unauthenticatedPage.close();
});
test('access public shared report with multiple filters shows correctly filtered data', async ({
page,
browser,
}) => {
const projectName = 'MultiFilter Project ' + Math.floor(Math.random() * 10000);
const tagName = 'MultiTag' + Math.floor(Math.random() * 10000);
const reportName = 'MultiFilter Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create a time entry with project, tag, and billable status
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill('Multi-filter entry');
// Set project
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
// Set tag
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
// Set as billable
await page.getByRole('button', { name: 'Non-Billable' }).click();
await page.getByRole('option', { name: 'Billable', exact: true }).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill('2h 30min');
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
// Create and make report public with multiple filters
await createReport(page, reportName, {
projectFilter: projectName,
tagFilter: tagName,
billableFilter: 'billable',
});
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify the filtered data is shown
await expect(unauthenticatedPage.getByText(projectName)).toBeVisible();
await expect(unauthenticatedPage.getByText(tagName)).toBeVisible();
await expect(unauthenticatedPage.getByText('2h 30min')).toBeVisible();
await unauthenticatedPage.close();
});
test('cannot access private shared report without authentication', async ({ page, browser }) => {
const projectName = 'Private Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Private Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create report but don't make it public
await createReport(page, reportName, { projectFilter: projectName });
// Try to access the shared reports page without authentication
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(PLAYWRIGHT_BASE_URL + '/reporting/shared');
// Should redirect to login or show unauthorized
await expect(unauthenticatedPage.getByRole('button', { name: 'Login' })).toBeVisible();
await unauthenticatedPage.close();
});
test('cannot access public shared report with invalid share secret', async ({ page, browser }) => {
const projectName = 'Invalid Secret Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Invalid Secret Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create and make report public
await createReport(page, reportName, { projectFilter: projectName });
await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Try to access with invalid share secret
const invalidUrl = PLAYWRIGHT_BASE_URL + '/shared-report#invalid-secret-123';
await unauthenticatedPage.goto(invalidUrl);
// Should show error or not found
await expect(unauthenticatedPage.getByText('Report not found')).toBeVisible();
await unauthenticatedPage.close();
});
test('public shared report displays charts and visualizations', async ({ page, browser }) => {
const projectName = 'Chart Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Chart Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '4h');
// Create and make report public
await createReport(page, reportName, { projectFilter: projectName });
const publicUrl = await makeReportPublic(page, reportName);
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify charts are displayed
await expect(unauthenticatedPage.locator('canvas')).toBeVisible();
// Verify summary statistics
await expect(unauthenticatedPage.getByText('Total Time')).toBeVisible();
await expect(unauthenticatedPage.getByText('4h 00min')).toBeVisible();
await unauthenticatedPage.close();
});
test('public shared report shows correct report metadata', async ({ page, browser }) => {
const projectName = 'Metadata Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Metadata Report ' + Math.floor(Math.random() * 10000);
const description = 'This is a public report showing project data';
// Create test data
await createTimeEntryWithProject(page, projectName, '1h 45min');
// Create report
await createReport(page, reportName, { projectFilter: projectName });
// Add description and make public
await goToSharedReports(page);
await page.waitForLoadState('networkidle');
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
await page.getByLabel('Description').fill(description);
await page.getByRole('switch', { name: 'Make report public' }).click();
await page.waitForResponse(
(response) => response.url().includes('/reports/') && response.status() === 200
);
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Get public URL
const copyButton = reportRow.getByRole('button', { name: 'Copy URL' });
await copyButton.click();
const publicUrl = await page.evaluate(() => navigator.clipboard.readText());
// Create unauthenticated page
const unauthenticatedPage = await createUnauthenticatedPage(browser);
// Access the public report URL
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify report metadata
await expect(unauthenticatedPage.getByText(reportName)).toBeVisible();
await expect(unauthenticatedPage.getByText(description)).toBeVisible();
await unauthenticatedPage.close();
});

View File

@@ -1,542 +0,0 @@
import { expect, Page, Browser } from '@playwright/test';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { test } from '../playwright/fixtures';
async function goToSharedReports(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting/shared');
}
async function goToReporting(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting');
}
async function createTimeEntryWithProject(
page: Page,
projectName: string,
duration: string,
description: string = ''
) {
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
await page.getByRole('button', { name: 'Create Project' }).click();
await page.getByLabel('Project Name').fill(projectName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Project' }).click();
await page.getByText(projectName).waitFor({ state: 'visible' });
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page
.getByTestId('time_entry_description')
.fill(description || `Time entry for ${projectName}`);
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await Promise.all([
page.getByRole('button', { name: 'Create Time Entry' }).click(),
page.waitForResponse(
(response) => response.url().includes('/time-entries') && response.status() === 201
),
]);
}
async function createTimeEntryWithTag(
page: Page,
tagName: string,
duration: string,
description: string = ''
) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page
.getByTestId('time_entry_description')
.fill(description || `Time entry with tag ${tagName}`);
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createTimeEntryWithBillableStatus(
page: Page,
isBillable: boolean,
duration: string,
description: string = ''
) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page
.getByTestId('time_entry_description')
.fill(description || `Time entry ${isBillable ? 'billable' : 'non-billable'}`);
await page.getByRole('button', { name: 'Non-Billable' }).click();
if (!isBillable) {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
}
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createReport(
page: Page,
reportName: string,
options: {
projectFilter?: string;
tagFilter?: string;
billableFilter?: 'billable' | 'non-billable' | 'all';
timeRange?: { start: string; end: string };
} = {}
) {
await goToReporting(page);
await page.waitForLoadState('networkidle');
// Apply filters if specified
if (options.projectFilter) {
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(options.projectFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.tagFilter) {
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText(options.tagFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.billableFilter && options.billableFilter !== 'all') {
await page.getByRole('button', { name: 'Billable' }).click();
if (options.billableFilter === 'billable') {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
}
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
// Set custom time range if specified
if (options.timeRange) {
await page.getByRole('button', { name: 'This Week' }).click();
await page.getByRole('option', { name: 'Custom Range' }).click();
await page.locator('input[name="startDate"]').fill(options.timeRange.start);
await page.locator('input[name="endDate"]').fill(options.timeRange.end);
await page.getByRole('button', { name: 'Apply' }).click();
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
await page.waitForLoadState('networkidle');
// Save the report
await page.getByRole('button', { name: 'Save Report' }).click();
await page.getByLabel('Report Name').fill(reportName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Report' }).click();
await page.waitForLoadState('networkidle');
}
async function makeReportPublic(page: Page, reportName: string): Promise<string> {
await goToSharedReports(page);
await page.waitForLoadState('networkidle');
// Find the report row and click the edit button
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
// Make the report public
await page.getByRole('switch', { name: 'Make report public' }).click();
// Wait for the API response
await page.waitForResponse(
(response) => response.url().includes('/reports/') && response.status() === 200
);
// Save the changes
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Get the public URL
const copyButton = reportRow.getByRole('button', { name: 'Copy URL' });
await copyButton.click();
// Extract the URL from clipboard or from the button's data attribute
const publicUrl = await page.evaluate(() => navigator.clipboard.readText());
return publicUrl;
}
async function createUnauthenticatedPage(browser: Browser): Promise<Page> {
const context = await browser.newContext();
const page = await context.newPage();
return page;
}
test('verify shared report data accuracy with project filter', async ({ page, browser }) => {
const projectName = 'Accuracy Project ' + Math.floor(Math.random() * 10000);
const otherProjectName = 'Other Accuracy Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Accuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data with specific durations
await createTimeEntryWithProject(page, projectName, '2h 30min', 'Task 1');
await createTimeEntryWithProject(page, projectName, '1h 15min', 'Task 2');
await createTimeEntryWithProject(page, otherProjectName, '3h', 'Other task');
// Create and make report public with project filter
await createReport(page, reportName, { projectFilter: projectName });
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(projectName).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Note expected total: 2h 30min + 1h 15min = 3h 45min
await expect(page.getByText('3h 45min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify total time matches
await expect(unauthenticatedPage.getByText('3h 45min')).toBeVisible();
await expect(unauthenticatedPage.getByText(projectName)).toBeVisible();
await expect(unauthenticatedPage.getByText('Task 1')).toBeVisible();
await expect(unauthenticatedPage.getByText('Task 2')).toBeVisible();
await expect(unauthenticatedPage.getByText(otherProjectName)).not.toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report data accuracy with tag filter', async ({ page, browser }) => {
const tagName = 'AccuracyTag' + Math.floor(Math.random() * 10000);
const otherTagName = 'OtherTag' + Math.floor(Math.random() * 10000);
const reportName = 'Tag Accuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data with specific durations
await createTimeEntryWithTag(page, tagName, '1h 30min', 'Tagged task 1');
await createTimeEntryWithTag(page, tagName, '2h 15min', 'Tagged task 2');
await createTimeEntryWithTag(page, otherTagName, '45min', 'Other tagged task');
// Create and make report public with tag filter
await createReport(page, reportName, { tagFilter: tagName });
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText(tagName).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Note expected total: 1h 30min + 2h 15min = 3h 45min
await expect(page.getByText('3h 45min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify total time matches
await expect(unauthenticatedPage.getByText('3h 45min')).toBeVisible();
await expect(unauthenticatedPage.getByText(tagName)).toBeVisible();
await expect(unauthenticatedPage.getByText('Tagged task 1')).toBeVisible();
await expect(unauthenticatedPage.getByText('Tagged task 2')).toBeVisible();
await expect(unauthenticatedPage.getByText(otherTagName)).not.toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report data accuracy with billable filter', async ({ page, browser }) => {
const reportName = 'Billable Accuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data with specific durations
await createTimeEntryWithBillableStatus(page, true, '2h', 'Billable task 1');
await createTimeEntryWithBillableStatus(page, true, '1h 30min', 'Billable task 2');
await createTimeEntryWithBillableStatus(page, false, '45min', 'Non-billable task');
// Create and make report public with billable filter
await createReport(page, reportName, { billableFilter: 'billable' });
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Billable' }).click();
await page.getByRole('option', { name: 'Billable', exact: true }).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Note expected total: 2h + 1h 30min = 3h 30min
await expect(page.getByText('3h 30min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify total time matches
await expect(unauthenticatedPage.getByText('3h 30min')).toBeVisible();
await expect(unauthenticatedPage.getByText('Billable task 1')).toBeVisible();
await expect(unauthenticatedPage.getByText('Billable task 2')).toBeVisible();
await expect(unauthenticatedPage.getByText('Non-billable task')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report data accuracy with non-billable filter', async ({ page, browser }) => {
const reportName = 'Non-Billable Accuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data with specific durations
await createTimeEntryWithBillableStatus(page, false, '1h 45min', 'Non-billable task 1');
await createTimeEntryWithBillableStatus(page, false, '2h 30min', 'Non-billable task 2');
await createTimeEntryWithBillableStatus(page, true, '1h', 'Billable task');
// Create and make report public with non-billable filter
await createReport(page, reportName, { billableFilter: 'non-billable' });
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Billable' }).click();
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Note expected total: 1h 45min + 2h 30min = 4h 15min
await expect(page.getByText('4h 15min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify total time matches
await expect(unauthenticatedPage.getByText('4h 15min')).toBeVisible();
await expect(unauthenticatedPage.getByText('Non-billable task 1')).toBeVisible();
await expect(unauthenticatedPage.getByText('Non-billable task 2')).toBeVisible();
await expect(unauthenticatedPage.getByText('Billable task')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report data accuracy with multiple filters', async ({ page, browser }) => {
const projectName = 'MultiAccuracy Project ' + Math.floor(Math.random() * 10000);
const tagName = 'MultiAccuracyTag' + Math.floor(Math.random() * 10000);
const reportName = 'MultiAccuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h', 'Project only');
// Create a time entry with project, tag, and billable status
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill('Multi-filter matched entry');
// Set project
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
// Set tag
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
// Set as billable
await page.getByRole('button', { name: 'Non-Billable' }).click();
await page.getByRole('option', { name: 'Billable', exact: true }).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill('2h 30min');
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
// Create another entry that won't match all filters
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill('Partial match entry');
// Set same project but different tag and non-billable
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill('DifferentTag');
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
await page.locator('[role="dialog"] input[name="Duration"]').fill('1h 15min');
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
// Create and make report public with multiple filters
await createReport(page, reportName, {
projectFilter: projectName,
tagFilter: tagName,
billableFilter: 'billable',
});
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(projectName).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText(tagName).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
await page.getByRole('button', { name: 'Billable' }).click();
await page.getByRole('option', { name: 'Billable', exact: true }).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Should only show the entry that matches all filters (2h 30min)
await expect(page.getByText('2h 30min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify only the matching entry is shown
await expect(unauthenticatedPage.getByText('2h 30min')).toBeVisible();
await expect(unauthenticatedPage.getByText('Multi-filter matched entry')).toBeVisible();
await expect(unauthenticatedPage.getByText('Project only')).not.toBeVisible();
await expect(unauthenticatedPage.getByText('Partial match entry')).not.toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report data accuracy with time range filter', async ({ page, browser }) => {
const projectName = 'TimeRange Accuracy Project ' + Math.floor(Math.random() * 10000);
const reportName = 'TimeRange Accuracy Report ' + Math.floor(Math.random() * 10000);
// Create test data within date range
await createTimeEntryWithProject(page, projectName, '1h 30min', 'Within range 1');
await createTimeEntryWithProject(page, projectName, '2h 15min', 'Within range 2');
// Create and make report public with time range
const startDate = new Date();
startDate.setDate(startDate.getDate() - 1);
const endDate = new Date();
endDate.setDate(endDate.getDate() + 1);
await createReport(page, reportName, {
projectFilter: projectName,
timeRange: {
start: startDate.toISOString().split('T')[0],
end: endDate.toISOString().split('T')[0],
},
});
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in authenticated reporting view
await goToReporting(page);
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(projectName).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
await page.getByRole('button', { name: 'This Week' }).click();
await page.getByRole('option', { name: 'Custom Range' }).click();
await page.locator('input[name="startDate"]').fill(startDate.toISOString().split('T')[0]);
await page.locator('input[name="endDate"]').fill(endDate.toISOString().split('T')[0]);
await page.getByRole('button', { name: 'Apply' }).click();
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
// Note expected total: 1h 30min + 2h 15min = 3h 45min
await expect(page.getByText('3h 45min')).toBeVisible();
// Verify same data in public view
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify total time matches
await expect(unauthenticatedPage.getByText('3h 45min')).toBeVisible();
await expect(unauthenticatedPage.getByText('Within range 1')).toBeVisible();
await expect(unauthenticatedPage.getByText('Within range 2')).toBeVisible();
await unauthenticatedPage.close();
});
test('verify shared report shows zero data when no entries match filters', async ({
page,
browser,
}) => {
const projectName = 'NoMatch Project ' + Math.floor(Math.random() * 10000);
const tagName = 'NoMatchTag' + Math.floor(Math.random() * 10000);
const reportName = 'NoMatch Report ' + Math.floor(Math.random() * 10000);
// Create test data that won't match our filters
await createTimeEntryWithProject(page, 'Other Project', '1h', 'Other entry');
// Create and make report public with filters that won't match
await createReport(page, reportName, {
projectFilter: projectName, // This project doesn't exist
tagFilter: tagName, // This tag doesn't exist
});
const publicUrl = await makeReportPublic(page, reportName);
// Verify data in public view shows zero/empty results
const unauthenticatedPage = await createUnauthenticatedPage(browser);
await unauthenticatedPage.goto(publicUrl);
await unauthenticatedPage.waitForLoadState('networkidle');
// Verify no data is shown
await expect(unauthenticatedPage.getByText('0h 00min')).toBeVisible();
await expect(unauthenticatedPage.getByText('No data available')).toBeVisible();
await unauthenticatedPage.close();
});

View File

@@ -1,392 +0,0 @@
import { expect, Page } from '@playwright/test';
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
import { test } from '../playwright/fixtures';
async function goToSharedReports(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting/shared');
}
async function goToReporting(page: Page) {
await page.goto(PLAYWRIGHT_BASE_URL + '/reporting');
}
async function createTimeEntryWithProject(page: Page, projectName: string, duration: string) {
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
await page.getByRole('button', { name: 'Create Project' }).click();
await page.getByLabel('Project Name').fill(projectName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Project' }).click();
await page.getByText(projectName).waitFor({ state: 'visible' });
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill(`Time entry for ${projectName}`);
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await Promise.all([
page.getByRole('button', { name: 'Create Time Entry' }).click(),
page.waitForResponse(
(response) => response.url().includes('/time-entries') && response.status() === 201
),
]);
}
async function createTimeEntryWithTag(page: Page, tagName: string, duration: string) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill(`Time entry with tag ${tagName}`);
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createTimeEntryWithBillableStatus(
page: Page,
isBillable: boolean,
duration: string
) {
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page
.getByTestId('time_entry_description')
.fill(`Time entry ${isBillable ? 'billable' : 'non-billable'}`);
await page.getByRole('button', { name: 'Non-Billable' }).click();
if (!isBillable) {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
}
await page.locator('[role="dialog"] input[name="Duration"]').fill(duration);
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
}
async function createReport(
page: Page,
reportName: string,
options: {
projectFilter?: string;
tagFilter?: string;
billableFilter?: 'billable' | 'non-billable' | 'all';
timeRange?: { start: string; end: string };
} = {}
) {
await goToReporting(page);
await page.waitForLoadState('networkidle');
// Apply filters if specified
if (options.projectFilter) {
await page.getByRole('button', { name: 'Project' }).nth(0).click();
await page.getByText(options.projectFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.tagFilter) {
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText(options.tagFilter).click();
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
if (options.billableFilter && options.billableFilter !== 'all') {
await page.getByRole('button', { name: 'Billable' }).click();
if (options.billableFilter === 'billable') {
await page.getByRole('option', { name: 'Billable', exact: true }).click();
} else {
await page.getByRole('option', { name: 'Non Billable', exact: true }).click();
}
await page.keyboard.press('Escape');
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
// Set custom time range if specified
if (options.timeRange) {
await page.getByRole('button', { name: 'This Week' }).click();
await page.getByRole('option', { name: 'Custom Range' }).click();
await page.locator('input[name="startDate"]').fill(options.timeRange.start);
await page.locator('input[name="endDate"]').fill(options.timeRange.end);
await page.getByRole('button', { name: 'Apply' }).click();
await page.waitForResponse(
(response) =>
response.url().includes('/time-entries/aggregate') && response.status() === 200
);
}
await page.waitForLoadState('networkidle');
// Save the report
await page.getByRole('button', { name: 'Save Report' }).click();
await page.getByLabel('Report Name').fill(reportName);
await page.getByRole('dialog').getByRole('button', { name: 'Create Report' }).click();
await page.waitForLoadState('networkidle');
}
async function makeReportPublic(page: Page, reportName: string): Promise<string> {
await goToSharedReports(page);
await page.waitForLoadState('networkidle');
// Find the report row and click the edit button
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
// Make the report public
await page.getByRole('switch', { name: 'Make report public' }).click();
// Wait for the API response
await page.waitForResponse(
(response) => response.url().includes('/reports/') && response.status() === 200
);
// Save the changes
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Get the public URL
const copyButton = reportRow.getByRole('button', { name: 'Copy URL' });
await copyButton.click();
// Extract the URL from clipboard or from the button's data attribute
const publicUrl = await page.evaluate(() => navigator.clipboard.readText());
return publicUrl;
}
test('create shared report with project filter', async ({ page }) => {
const projectName = 'Shared Report Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Project Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '2h');
await createTimeEntryWithProject(page, 'Other Project', '1h');
// Create a report with project filter
await createReport(page, reportName, { projectFilter: projectName });
// Make the report public
const publicUrl = await makeReportPublic(page, reportName);
// Verify the report appears in shared reports list
await expect(page.getByText(reportName)).toBeVisible();
await expect(page.getByText('Public')).toBeVisible();
expect(publicUrl).toContain('/shared-report#');
});
test('create shared report with tag filter', async ({ page }) => {
const tagName = 'SharedTag' + Math.floor(Math.random() * 10000);
const reportName = 'Tag Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithTag(page, tagName, '1h 30min');
await createTimeEntryWithTag(page, 'OtherTag', '45min');
// Create a report with tag filter
await createReport(page, reportName, { tagFilter: tagName });
// Make the report public
const publicUrl = await makeReportPublic(page, reportName);
// Verify the report appears in shared reports list
await expect(page.getByText(reportName)).toBeVisible();
await expect(page.getByText('Public')).toBeVisible();
expect(publicUrl).toContain('/shared-report#');
});
test('create shared report with billable filter', async ({ page }) => {
const reportName = 'Billable Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithBillableStatus(page, true, '2h');
await createTimeEntryWithBillableStatus(page, false, '1h');
// Create a report with billable filter
await createReport(page, reportName, { billableFilter: 'billable' });
// Make the report public
const publicUrl = await makeReportPublic(page, reportName);
// Verify the report appears in shared reports list
await expect(page.getByText(reportName)).toBeVisible();
await expect(page.getByText('Public')).toBeVisible();
expect(publicUrl).toContain('/shared-report#');
});
test('create shared report with custom time range', async ({ page }) => {
const projectName = 'TimeRange Project ' + Math.floor(Math.random() * 10000);
const reportName = 'TimeRange Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '3h');
// Create a report with custom time range (last 30 days)
const startDate = new Date();
startDate.setDate(startDate.getDate() - 30);
const endDate = new Date();
await createReport(page, reportName, {
projectFilter: projectName,
timeRange: {
start: startDate.toISOString().split('T')[0],
end: endDate.toISOString().split('T')[0],
},
});
// Make the report public
const publicUrl = await makeReportPublic(page, reportName);
// Verify the report appears in shared reports list
await expect(page.getByText(reportName)).toBeVisible();
await expect(page.getByText('Public')).toBeVisible();
expect(publicUrl).toContain('/shared-report#');
});
test('create shared report with multiple filters', async ({ page }) => {
const projectName = 'MultiFilter Project ' + Math.floor(Math.random() * 10000);
const tagName = 'MultiTag' + Math.floor(Math.random() * 10000);
const reportName = 'MultiFilter Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '2h');
// Create a time entry with both project and tag
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
await page.getByRole('button', { name: 'Manual time entry' }).click();
await page.getByTestId('time_entry_description').fill('Multi-filter entry');
// Set project
await page.getByRole('button', { name: 'No Project' }).click();
await page.getByText(projectName).click();
// Set tag
await page.getByRole('button', { name: 'Tags' }).click();
await page.getByText('Create new tag').click();
await page.getByPlaceholder('Tag Name').fill(tagName);
await page.getByRole('button', { name: 'Create Tag' }).click();
await page.waitForLoadState('networkidle');
// Set as billable
await page.getByRole('button', { name: 'Non-Billable' }).click();
await page.getByRole('option', { name: 'Billable', exact: true }).click();
await page.locator('[role="dialog"] input[name="Duration"]').fill('1h 30min');
await page.locator('[role="dialog"] input[name="Duration"]').press('Tab');
await page.getByRole('button', { name: 'Create Time Entry' }).click();
// Create a report with multiple filters
await createReport(page, reportName, {
projectFilter: projectName,
tagFilter: tagName,
billableFilter: 'billable',
});
// Make the report public
const publicUrl = await makeReportPublic(page, reportName);
// Verify the report appears in shared reports list
await expect(page.getByText(reportName)).toBeVisible();
await expect(page.getByText('Public')).toBeVisible();
expect(publicUrl).toContain('/shared-report#');
});
test('toggle report visibility from public to private', async ({ page }) => {
const projectName = 'Toggle Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Toggle Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create a report
await createReport(page, reportName, { projectFilter: projectName });
// Make the report public
await makeReportPublic(page, reportName);
// Verify it's public
await expect(page.getByText('Public')).toBeVisible();
// Make it private again
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
await page.getByRole('switch', { name: 'Make report public' }).click();
await page.waitForResponse(
(response) => response.url().includes('/reports/') && response.status() === 200
);
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Verify it's now private
await expect(page.getByText('Private')).toBeVisible();
await expect(page.getByText('Public')).not.toBeVisible();
});
test('edit shared report name and description', async ({ page }) => {
const projectName = 'Edit Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Original Report ' + Math.floor(Math.random() * 10000);
const updatedName = 'Updated Report ' + Math.floor(Math.random() * 10000);
const description = 'This is an updated description';
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create a report
await createReport(page, reportName, { projectFilter: projectName });
// Make the report public
await makeReportPublic(page, reportName);
// Edit the report
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Edit' }).click();
await page.getByLabel('Report Name').fill(updatedName);
await page.getByLabel('Description').fill(description);
await page.getByRole('button', { name: 'Save' }).click();
await page.waitForLoadState('networkidle');
// Verify the changes
await expect(page.getByText(updatedName)).toBeVisible();
await expect(page.getByText(reportName)).not.toBeVisible();
});
test('delete shared report', async ({ page }) => {
const projectName = 'Delete Project ' + Math.floor(Math.random() * 10000);
const reportName = 'Delete Report ' + Math.floor(Math.random() * 10000);
// Create test data
await createTimeEntryWithProject(page, projectName, '1h');
// Create a report
await createReport(page, reportName, { projectFilter: projectName });
// Make the report public
await makeReportPublic(page, reportName);
// Delete the report
const reportRow = page.locator('tr').filter({ hasText: reportName });
await reportRow.getByRole('button', { name: 'Delete' }).click();
await page.getByRole('button', { name: 'Delete Report' }).click();
await page.waitForLoadState('networkidle');
// Verify the report is deleted
await expect(page.getByText(reportName)).not.toBeVisible();
});

View File

@@ -14,6 +14,7 @@ use App\Exceptions\Api\OnlyOwnerCanChangeOwnership;
use App\Exceptions\Api\OnlyPlaceholdersCanBeMergedIntoAnotherMember;
use App\Exceptions\Api\OrganizationHasNoSubscriptionButMultipleMembersException;
use App\Exceptions\Api\OrganizationNeedsAtLeastOneOwner;
use App\Exceptions\Api\OverlappingTimeEntryApiException;
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
use App\Exceptions\Api\PersonalAccessClientIsNotConfiguredException;
use App\Exceptions\Api\ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException;
@@ -47,6 +48,7 @@ return [
OnlyPlaceholdersCanBeMergedIntoAnotherMember::KEY => 'Only placeholders can be merged into another member',
ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException::KEY => 'This placeholder can not be invited use the merge tool instead',
InvitationForTheEmailAlreadyExistsApiException::KEY => 'The email has already been invited to the organization. Please wait for the user to accept the invitation or resend the invitation email.',
OverlappingTimeEntryApiException::KEY => 'Overlapping time entries are not allowed.',
],
'unknown_error_in_admin_panel' => 'An unknown error occurred. Please check the logs.',
];

View File

@@ -203,6 +203,7 @@ return [
'organization' => 'The :attribute does not exist.',
'task_belongs_to_project' => 'The :attribute is not part of the given project.',
'project_name_already_exists' => 'A project with the same name and client already exists in the organization.',
'overlapping_time_entry' => 'Overlapping time entries are not allowed.',
'tag_name_already_exists' => 'A tag with the same name already exists in the organization.',
'client_name_already_exists' => 'A client with the same name already exists in the organization.',
'task_name_already_exists' => 'A task with the same name already exists in the project.',

79
package-lock.json generated
View File

@@ -7,6 +7,11 @@
"dependencies": {
"@floating-ui/core": "^1.6.0",
"@floating-ui/vue": "^1.0.6",
"@fullcalendar/core": "^6.1.18",
"@fullcalendar/daygrid": "^6.1.18",
"@fullcalendar/interaction": "^6.1.18",
"@fullcalendar/timegrid": "^6.1.18",
"@fullcalendar/vue3": "^6.1.18",
"@heroicons/vue": "^2.1.1",
"@rushstack/eslint-patch": "^1.10.5",
"@tailwindcss/container-queries": "^0.1.1",
@@ -18,6 +23,7 @@
"@vue/eslint-config-typescript": "^14.3.0",
"@vueuse/core": "^12.8.2",
"@vueuse/integrations": "^12.5.0",
"chroma-js": "3.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.11",
@@ -39,6 +45,7 @@
"@playwright/test": "^1.41.1",
"@tailwindcss/forms": "^0.5.9",
"@tailwindcss/typography": "^0.5.15",
"@types/chroma-js": "2.4.5",
"@types/node": "^22.10.10",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/tsconfig": "^0.5.1",
@@ -1027,6 +1034,55 @@
"vue-demi": ">=0.13.0"
}
},
"node_modules/@fullcalendar/core": {
"version": "6.1.18",
"resolved": "https://registry.npmjs.org/@fullcalendar/core/-/core-6.1.18.tgz",
"integrity": "sha512-cD7XtZIZZ87Cg2+itnpsONCsZ89VIfLLDZ22pQX4IQVWlpYUB3bcCf878DhWkqyEen6dhi5ePtBoqYgm5K+0fQ==",
"license": "MIT",
"dependencies": {
"preact": "~10.12.1"
}
},
"node_modules/@fullcalendar/daygrid": {
"version": "6.1.18",
"resolved": "https://registry.npmjs.org/@fullcalendar/daygrid/-/daygrid-6.1.18.tgz",
"integrity": "sha512-s452Zle1SdMEzZDw+pDczm8m3JLIZzS9ANMThXTnqeqJewW1gqNFYas18aHypJSgF9Fh9rDJjTSUw04BpXB/Mg==",
"license": "MIT",
"peerDependencies": {
"@fullcalendar/core": "~6.1.18"
}
},
"node_modules/@fullcalendar/interaction": {
"version": "6.1.18",
"resolved": "https://registry.npmjs.org/@fullcalendar/interaction/-/interaction-6.1.18.tgz",
"integrity": "sha512-f/mD5RTjzw+Q6MGTMZrLCgIrQLIUUO9NV/58aM2J6ZBQZeRlNizDqmqldqyG+j49zj2vFhUfZibPrVKWm5yA4Q==",
"license": "MIT",
"peerDependencies": {
"@fullcalendar/core": "~6.1.18"
}
},
"node_modules/@fullcalendar/timegrid": {
"version": "6.1.18",
"resolved": "https://registry.npmjs.org/@fullcalendar/timegrid/-/timegrid-6.1.18.tgz",
"integrity": "sha512-T/ouhs+T1tM8JcW7Cjx+KiohL/qQWKqvRITwjol8ktJ1e1N/6noC40/obR1tyolqOxMRWHjJkYoj9fUqfoez9A==",
"license": "MIT",
"dependencies": {
"@fullcalendar/daygrid": "~6.1.18"
},
"peerDependencies": {
"@fullcalendar/core": "~6.1.18"
}
},
"node_modules/@fullcalendar/vue3": {
"version": "6.1.18",
"resolved": "https://registry.npmjs.org/@fullcalendar/vue3/-/vue3-6.1.18.tgz",
"integrity": "sha512-YMagwTumxsIx3GFYWLa9Yr73EMA+JuH6S3EeZGS+rEjvG5fDGdf+33rxGMzmw+LdO7SWi3ctbzRnJlv3fnm3RQ==",
"license": "MIT",
"peerDependencies": {
"@fullcalendar/core": "~6.1.18",
"vue": "^3.0.11"
}
},
"node_modules/@heroicons/vue": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@heroicons/vue/-/vue-2.2.0.tgz",
@@ -1842,6 +1898,13 @@
"vue": "^2.7.0 || ^3.0.0"
}
},
"node_modules/@types/chroma-js": {
"version": "2.4.5",
"resolved": "https://registry.npmjs.org/@types/chroma-js/-/chroma-js-2.4.5.tgz",
"integrity": "sha512-6ISjhzJViaPCy2q2e6PgK+8HcHQDQ0V2LDiKmYAh+jJlLqDa6HbwDh0wOevHY0kHHUx0iZwjSRbVD47WOUx5EQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
@@ -2877,6 +2940,12 @@
"node": ">= 6"
}
},
"node_modules/chroma-js": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/chroma-js/-/chroma-js-3.1.2.tgz",
"integrity": "sha512-IJnETTalXbsLx1eKEgx19d5L6SRM7cH4vINw/99p/M11HCuXGRWL+6YmCm7FWFGIo6dtWuQoQi1dc5yQ7ESIHg==",
"license": "(BSD-3-Clause AND Apache-2.0)"
},
"node_modules/class-variance-authority": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",
@@ -5140,6 +5209,16 @@
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"license": "MIT"
},
"node_modules/preact": {
"version": "10.12.1",
"resolved": "https://registry.npmjs.org/preact/-/preact-10.12.1.tgz",
"integrity": "sha512-l8386ixSsBdbreOAkqtrwqHwdvR35ID8c3rKPa8lCWuO86dBi32QWHV4vfsZK1utLLFMvw+Z5Ad4XLkZzchscg==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
}
},
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",

View File

@@ -19,6 +19,7 @@
"@playwright/test": "^1.41.1",
"@tailwindcss/forms": "^0.5.9",
"@tailwindcss/typography": "^0.5.15",
"@types/chroma-js": "2.4.5",
"@types/node": "^22.10.10",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/tsconfig": "^0.5.1",
@@ -39,6 +40,11 @@
"dependencies": {
"@floating-ui/core": "^1.6.0",
"@floating-ui/vue": "^1.0.6",
"@fullcalendar/core": "^6.1.18",
"@fullcalendar/daygrid": "^6.1.18",
"@fullcalendar/interaction": "^6.1.18",
"@fullcalendar/timegrid": "^6.1.18",
"@fullcalendar/vue3": "^6.1.18",
"@heroicons/vue": "^2.1.1",
"@rushstack/eslint-patch": "^1.10.5",
"@tailwindcss/container-queries": "^0.1.1",
@@ -50,6 +56,7 @@
"@vue/eslint-config-typescript": "^14.3.0",
"@vueuse/core": "^12.8.2",
"@vueuse/integrations": "^12.5.0",
"chroma-js": "3.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.11",

View File

@@ -46,14 +46,16 @@
--color-accent-default: rgba(var(--color-accent-300), 0.2);
--color-accent-foreground: rgb(var(--color-accent-100));
--theme-color-default-background: var(--color-bg-primary);
}
:root.light {
--color-bg-primary: #F5F5F5;
--color-bg-primary: #FFFFFF;
--color-bg-secondary: #f7f7f8;
--color-bg-tertiary: #e1e1e3;
--color-bg-quaternary: #ffffff;
--color-bg-background: #ffffff;
--color-bg-tertiary: #eeeeef;
--color-bg-quaternary: #e1e1e3;
--color-bg-background: #F5F5F5;
--color-text-primary: #18181b;
--color-text-secondary: #3f3f46;
--color-text-tertiary: #57575C;
@@ -63,14 +65,14 @@
--color-border-tertiary: #dfdfdf;
--color-border-quaternary: #d1d1d1;
--color-input-border-active: rgba(0,0,0,0.3);
--theme-color-menu-active: var(--color-bg-tertiary);
--theme-color-menu-active: var(--color-bg-quaternary);
--theme-color-card-background: var(--color-bg-quaternary);
--theme-color-card-background-active: var(--color-bg-primary);
--theme-color-card-background: var(--color-bg-primary);
--theme-color-card-background-active: var(--color-bg-tertiary);
--theme-color-chart: var(--color-accent-400);
--theme-shadow-card: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--theme-shadow-card: lch(0 0 0 / 0.022) 0px 3px 6px -2px, lch(0 0 0 / 0.044) 0px 1px 1px;
--theme-shadow-dropdown: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
--theme-color-row-background: var(--theme-color-card-background);
@@ -85,17 +87,18 @@
--theme-color-button-primary-border: rgba(var(--color-accent-600), 1);
--theme-color-button-primary-text: #FFFFFF;
--theme-color-input-background: var(--color-bg-quaternary);
--theme-color-input-background: var(--color-bg-primary);
--theme-color-input-select-active: rgb(var(--color-accent-400));
--theme-color-input-select-active-hover: rgb(var(--color-accent-500));
--color-accent-default: rgb(var(--color-accent-100));
--color-accent-foreground: rgb(var(--color-accent-800));
--theme-color-default-background: #FCFCFC;
}
:root {
--theme-color-default-background: var(--color-bg-primary);
--theme-color-icon-active: rgb(var(--color-text-tertiary));
--theme-color-card-background-separator: var(--color-border-tertiary);
--theme-color-card-border: var(--color-border-secondary);

View File

@@ -113,7 +113,7 @@ const option = computed(() => ({
},
axisLabel: {
fontSize: 12,
fontWeight: 600,
fontWeight: 400,
color: labelColor.value,
margin: 16,
fontFamily: 'Inter, sans-serif',

View File

@@ -30,10 +30,7 @@ const organization = inject<ComputedRef<Organization>>('organization');
<template>
<div
class="contents text-text-primary [&>*]:transition [&>*]:border-card-background-separator [&>*]:border-b [&>*]:h-[50px]">
<div
:class="
twMerge('pl-6 font-medium flex items-center space-x-3', props.indent ? 'pl-16' : '')
">
<div :class="twMerge('pl-6 flex items-center space-x-3', props.indent ? 'pl-16' : '')">
<GroupedItemsCountButton
v-if="entry.grouped_data && entry.grouped_data?.length > 0"
:expanded="expanded"

View File

@@ -0,0 +1,107 @@
<script setup lang="ts">
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { onMounted, ref } from 'vue';
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
import { useForm, usePage } from '@inertiajs/vue3';
import type { User } from '@/types/models';
import { useSessionStorage } from '@vueuse/core';
const show = defineModel('show', { default: false });
const saving = defineModel('saving', { default: false });
const timezone = ref('');
const userTimezone = ref('');
const page = usePage<{
auth: {
user: User;
};
}>();
const hideTimezoneMismatchModal = useSessionStorage<boolean>('hide-timezone-mismatch-modal', false);
onMounted(() => {
timezone.value = Intl.DateTimeFormat().resolvedOptions().timeZone;
userTimezone.value = getUserTimezone();
const now = getDayJsInstance()();
if (
now.tz(timezone.value).format() !== now.tz(userTimezone.value).format() &&
!hideTimezoneMismatchModal.value
) {
show.value = true;
}
});
function submit() {
saving.value = true;
const form = useForm({
_method: 'PUT',
timezone: timezone.value,
name: page.props.auth.user.name,
email: page.props.auth.user.email,
week_start: page.props.auth.user.week_start,
});
form.post(route('user-profile-information.update'), {
errorBag: 'updateProfileInformation',
preserveScroll: true,
onSuccess: () => {
saving.value = false;
show.value = false;
location.reload();
},
});
}
function cancel() {
show.value = false;
hideTimezoneMismatchModal.value = true;
}
</script>
<template>
<DialogModal closeable :show="show" @close="show = false">
<template #title>
<div class="flex justify-center">
<span> Timezone mismatch detected </span>
</div>
</template>
<template #content>
<div class="flex items-center space-x-4">
<div class="col-span-6 sm:col-span-4 flex-1 space-y-2">
<p>
The timezone of your device does not match the timezone in your user
settings. <br />
<strong
>We highly recommend that you update your timezone settings to your
current timezone.</strong
>
</p>
<p>
Want to change your timezone setting from
<strong>{{ userTimezone }}</strong> to <strong>{{ timezone }}</strong
>.
</p>
</div>
</div>
</template>
<template #footer>
<SecondaryButton @click="cancel"> Cancel</SecondaryButton>
<PrimaryButton
class="ms-3"
:class="{ 'opacity-25': saving }"
:disabled="saving"
@click="submit()">
Update timezone
</PrimaryButton>
</template>
</DialogModal>
</template>
<style scoped></style>

View File

@@ -4,9 +4,7 @@ import { computed } from 'vue';
import RecentlyTrackedTasksCardEntry from '@/Components/Dashboard/RecentlyTrackedTasksCardEntry.vue';
import DashboardCard from '@/Components/Dashboard/DashboardCard.vue';
import { CheckCircleIcon } from '@heroicons/vue/20/solid';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import { PlusCircleIcon } from '@heroicons/vue/24/solid';
import { router } from '@inertiajs/vue3';
import { getCurrentMembershipId, getCurrentOrganizationId } from '@/utils/useUser';
import { api } from '@/packages/api/src';
import { LoadingSpinner } from '@/packages/ui/src';
@@ -90,23 +88,8 @@ window.addEventListener('dashboard:refresh', () => {
<div v-else class="text-center flex flex-1 justify-center items-center">
<div>
<PlusCircleIcon class="w-8 text-icon-default inline pb-2"></PlusCircleIcon>
<h3 class="text-text-primary font-semibold text-sm">No recent tasks found</h3>
<p class="pb-5 text-sm">Create tasks inside of a project!</p>
<SecondaryButton @click="router.visit(route('projects'))"
>Go to Projects
</SecondaryButton>
</div>
</div>
<div
v-if="latestTasks && latestTasks.length === 1"
class="text-center flex flex-1 justify-center items-center text-sm">
<div>
<PlusCircleIcon class="w-8 text-icon-default inline pb-2"></PlusCircleIcon>
<h3 class="text-text-primary font-semibold">Add more tasks</h3>
<p class="pb-5">Create tasks inside of a project!</p>
<SecondaryButton @click="router.visit(route('projects'))"
>Go to Projects
</SecondaryButton>
<h3 class="text-text-primary font-semibold text-sm">No recent time entries</h3>
<p class="pb-5 text-sm">Start tracking your time!</p>
</div>
</div>
</DashboardCard>

View File

@@ -1,7 +1,7 @@
<template>
<div
aria-live="assertive"
class="pointer-events-none fixed inset-0 flex items-end px-4 py-6 sm:items-end sm:p-6 sm:pb-24 z-[70]">
class="pointer-events-none fixed inset-0 flex items-end px-4 py-6 sm:items-end sm:p-6 z-[70]">
<div class="flex w-full flex-col items-center space-y-4 sm:items-end">
<Notification
v-for="notification in notifications"

View File

@@ -1,12 +1,23 @@
<script setup lang="ts">
import { ChevronDownIcon } from '@heroicons/vue/20/solid';
import Dropdown from '@/packages/ui/src/Input/Dropdown.vue';
import DropdownLink from '@/Components/DropdownLink.vue';
import { usePage } from '@inertiajs/vue3';
import { Link, usePage } from '@inertiajs/vue3';
import {
Cog6ToothIcon,
PlusCircleIcon,
CheckCircleIcon,
ArrowRightIcon,
} from '@heroicons/vue/24/solid';
import type { Organization, User } from '@/types/models';
import { isBillingActivated } from '@/utils/billing';
import { canManageBilling } from '@/utils/permissions';
import { switchOrganization } from '@/utils/useOrganization';
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
} from '@/Components/ui/dropdown-menu';
const page = usePage<{
jetstream: {
@@ -28,84 +39,79 @@ const switchToTeam = (organization: Organization) => {
</script>
<template>
<Dropdown v-if="page.props.jetstream.hasTeamFeatures" align="center" width="60">
<template #trigger>
<div
data-testid="organization_switcher"
class="flex hover:bg-white/10 cursor-pointer transition px-2 py-1 rounded-lg w-full items-center justify-between font-medium">
<DropdownMenu v-if="page.props.jetstream.hasTeamFeatures">
<DropdownMenuTrigger
class="flex w-full text-left hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-ring cursor-pointer transition pl-2 py-1 rounded w-full items-center justify-between"
as-child>
<button data-testid="organization_switcher">
<div class="flex flex-1 space-x-2 items-center w-[calc(100%-30px)]">
<div
class="rounded sm:rounded-lg bg-blue-900 font-semibold text-xs sm:text-sm flex-shrink-0 text-white w-5 sm:w-6 h-5 sm:h-6 flex items-center justify-center">
class="rounded bg-blue-900 font-medium text-xs flex-shrink-0 text-white w-5 h-5 flex items-center justify-center">
{{ page.props.auth.user.current_team.name.slice(0, 1).toUpperCase() }}
</div>
<span class="text-sm flex-1 truncate font-semibold">
<span class="text-xs flex-1 truncate font-medium">
{{ page.props.auth.user.current_team.name }}
</span>
</div>
<div class="w-[30px]">
<button
class="p-1 transition hover:bg-white/10 rounded-full flex items-center w-8 h-8">
<ChevronDownIcon class="w-5 sm:w-full mt-[1px]"></ChevronDownIcon>
</button>
<div class="p-1 rounded-full flex items-center w-6 h-6">
<ChevronDownIcon class="w-4 sm:w-full mt-[1px]"></ChevronDownIcon>
</div>
</div>
</div>
</template>
</button>
</DropdownMenuTrigger>
<template #content>
<DropdownMenuContent align="start">
<div class="w-60">
<!-- Organization Management -->
<div class="block px-4 py-2 text-xs text-text-secondary">Manage Organization</div>
<DropdownMenuLabel>Manage Organization</DropdownMenuLabel>
<!-- Organization Settings -->
<DropdownLink :href="route('teams.show', page.props.auth.user.current_team.id)">
Organization Settings
</DropdownLink>
<DropdownMenuItem as-child>
<Link
:href="route('teams.show', page.props.auth.user.current_team.id)"
class="inline-flex items-center gap-2.5 w-full">
<Cog6ToothIcon class="w-5 h-5 text-icon-default" />
<span>Organization Settings</span>
</Link>
</DropdownMenuItem>
<DropdownLink v-if="canManageBilling() && isBillingActivated()" href="/billing">
Billing
</DropdownLink>
<DropdownMenuItem v-if="canManageBilling() && isBillingActivated()" as-child>
<Link href="/billing" class="inline-flex items-center w-full"> Billing </Link>
</DropdownMenuItem>
<DropdownLink
v-if="page.props.jetstream.canCreateTeams"
:href="route('teams.create')">
Create new organization
</DropdownLink>
<DropdownMenuItem v-if="page.props.jetstream.canCreateTeams" as-child>
<Link
:href="route('teams.create')"
class="inline-flex items-center gap-2.5 w-full">
<PlusCircleIcon class="w-5 h-5 text-icon-default" />
<span>Create new organization</span>
</Link>
</DropdownMenuItem>
<!-- Organization Switcher -->
<template v-if="page.props.auth.user.all_teams.length > 1">
<div class="border-t border-card-background-separator" />
<div class="block px-4 py-2 text-xs text-text-secondary">
Switch Organizations
</div>
<DropdownMenuLabel>Switch Organizations</DropdownMenuLabel>
<template v-for="team in page.props.auth.user.all_teams" :key="team.id">
<form @submit.prevent="switchToTeam(team)">
<DropdownLink as="button">
<div class="flex items-center">
<svg
<DropdownMenuItem
as-child
class="inline-flex gap-2.5 items-center w-full">
<button type="submit">
<CheckCircleIcon
v-if="team.id == page.props.auth.user.current_team_id"
class="me-2 h-5 w-5 text-green-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
class="h-5 w-5 text-green-400" />
<ArrowRightIcon v-else class="h-5 w-5 text-icon-default" />
<div>
<div class="w-full truncate text-left">
{{ team.name }}
</div>
</div>
</DropdownLink>
</button>
</DropdownMenuItem>
</form>
</template>
</template>
</div>
</template>
</Dropdown>
</DropdownMenuContent>
</DropdownMenu>
</template>

View File

@@ -1,10 +1,24 @@
<script setup lang="ts">
import { router, usePage } from '@inertiajs/vue3';
import { Link, router, usePage } from '@inertiajs/vue3';
import type { Organization, User } from '@/types/models';
import DropdownLink from '@/Components/DropdownLink.vue';
import Dropdown from '@/packages/ui/src/Input/Dropdown.vue';
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
} from '@/Components/ui/dropdown-menu';
import {
UserCircleIcon,
KeyIcon,
ArrowLeftOnRectangleIcon,
ChatBubbleLeftRightIcon,
} from '@heroicons/vue/24/solid';
import { openFeedback } from '@/utils/feedback';
const page = usePage<{
has_services_extension?: boolean;
has_billing_extension?: boolean;
jetstream: {
canCreateTeams: boolean;
hasTeamFeatures: boolean;
@@ -23,60 +37,58 @@ const logout = () => {
};
</script>
<template>
<div class="ms-3 relative">
<Dropdown align="center" width="48">
<template #trigger>
<button
v-if="page.props.jetstream.managesProfilePhotos"
data-testid="current_user_button"
class="flex text-sm border-2 border-transparent rounded-full focus:outline-none focus:border-gray-300 transition">
<div class="relative">
<DropdownMenu>
<DropdownMenuTrigger
class="flex text-sm border-2 outline-none border-transparent rounded-full focus-visible:ring-2 focus-visible:ring-ring transition"
as-child>
<button data-testid="current_user_button">
<img
class="h-8 w-8 rounded-full object-cover"
class="h-7 w-7 rounded-full object-cover"
:src="page.props.auth.user.profile_photo_url"
:alt="page.props.auth.user.name" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" class="max-w-48">
<DropdownMenuLabel>Manage Account</DropdownMenuLabel>
<span v-else class="inline-flex rounded-md">
<DropdownMenuItem as-child>
<Link
:href="route('profile.show')"
class="inline-flex items-center gap-2.5 w-full">
<UserCircleIcon class="w-5 h-5 text-icon-default" />
<span>Profile Settings</span>
</Link>
</DropdownMenuItem>
<DropdownMenuItem v-if="page.props.jetstream.hasApiFeatures" as-child>
<Link
:href="route('api-tokens.index')"
class="inline-flex items-center gap-2.5 w-full">
<KeyIcon class="w-5 h-5 text-icon-default" />
<span>API Tokens</span>
</Link>
</DropdownMenuItem>
<DropdownMenuItem v-if="page.props.has_services_extension" as-child>
<button
type="button"
class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:text-gray-700 focus:outline-none focus:bg-gray-50 active:bg-gray-50 transition ease-in-out duration-150">
{{ page.props.auth.user.name }}
<svg
class="ms-2 -me-0.5 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
</svg>
class="inline-flex items-center gap-2.5 w-full"
@click="openFeedback">
<ChatBubbleLeftRightIcon class="w-5 h-5 text-icon-default" />
<span>Feedback</span>
</button>
</span>
</template>
</DropdownMenuItem>
<template #content>
<!-- Account Management -->
<div class="block px-4 py-2 text-xs text-gray-400">Manage Account</div>
<DropdownLink :href="route('profile.show')"> Profile </DropdownLink>
<DropdownLink
v-if="page.props.jetstream.hasApiFeatures"
:href="route('api-tokens.index')">
API Tokens
</DropdownLink>
<div class="border-t border-card-border" />
<!-- Authentication -->
<form @submit.prevent="logout">
<DropdownLink as="button" data-testid="logout_button"> Log Out </DropdownLink>
<form class="w-full" @submit.prevent="logout">
<DropdownMenuItem as-child class="inline-flex items-center gap-2.5 w-full">
<button type="submit" data-testid="logout_button">
<ArrowLeftOnRectangleIcon class="w-5 h-5 text-icon-default" />
<span>Log Out</span>
</button>
</DropdownMenuItem>
</form>
</template>
</Dropdown>
</DropdownMenuContent>
</DropdownMenu>
</div>
</template>

View File

@@ -19,7 +19,7 @@ const forwardedProps = useForwardProps(delegatedProps);
<template>
<DropdownMenuLabel
v-bind="forwardedProps"
:class="cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', props.class)">
:class="cn('block px-2 py-2 text-xs text-gray-400', inset && 'pl-8', props.class)">
<slot />
</DropdownMenuLabel>
</template>

View File

@@ -5,6 +5,7 @@ import OrganizationSwitcher from '@/Components/OrganizationSwitcher.vue';
import CurrentSidebarTimer from '@/Components/CurrentSidebarTimer.vue';
import {
Bars3Icon,
CalendarIcon,
ChartBarIcon,
ClockIcon,
Cog6ToothIcon,
@@ -39,14 +40,19 @@ import { ArrowsRightLeftIcon } from '@heroicons/vue/16/solid';
import { fetchToken, isTokenValid } from '@/utils/session';
import UpdateSidebarNotification from '@/Components/UpdateSidebarNotification.vue';
import BillingBanner from '@/Components/Billing/BillingBanner.vue';
import UserTimezoneMismatchModal from '@/Components/Common/User/UserTimezoneMismatchModal.vue';
import { useTheme } from '@/utils/theme';
import { useQuery } from '@tanstack/vue-query';
import { api } from '@/packages/api/src';
import { getCurrentOrganizationId } from '@/utils/useUser';
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
import { twMerge } from 'tailwind-merge';
import Button from '@/Components/ui/button/Button.vue';
import { openFeedback } from '@/utils/feedback';
defineProps({
title: String,
mainClass: String,
});
const showSidebarMenu = ref(false);
@@ -90,8 +96,8 @@ onMounted(async () => {
}, 100);
};
});
const page = usePage<{
has_services_extension?: boolean;
auth: {
user: User;
};
@@ -102,7 +108,7 @@ const page = usePage<{
<div v-bind="$attrs" class="flex flex-wrap bg-background text-text-secondary">
<div
:class="{
'!flex bg-default-background w-full z-[9999999999]': showSidebarMenu,
'!flex bg-default-background w-full z-30': showSidebarMenu,
}"
class="flex-shrink-0 h-screen hidden fixed w-[230px] 2xl:w-[250px] px-2.5 2xl:px-3 py-4 lg:flex flex-col justify-between">
<div class="flex flex-col h-full">
@@ -131,6 +137,11 @@ const page = usePage<{
:icon="ClockIcon"
:current="route().current('time')"
:href="route('time')"></NavigationSidebarItem>
<NavigationSidebarItem
title="Calendar"
:icon="CalendarIcon"
:current="route().current('calendar')"
:href="route('calendar')"></NavigationSidebarItem>
<NavigationSidebarItem
title="Reporting"
:icon="ChartBarIcon"
@@ -233,35 +244,44 @@ const page = usePage<{
<div class="justify-self-end">
<UpdateSidebarNotification></UpdateSidebarNotification>
<ul
class="border-t border-default-background-separator pt-3 flex justify-between pr-4 items-center">
class="border-t border-default-background-separator pt-3 gap-1 pr-2 flex justify-between items-center">
<UserSettingsIcon></UserSettingsIcon>
<NavigationSidebarItem
class="flex-1"
title="Profile Settings"
:icon="Cog6ToothIcon"
:href="route('profile.show')"></NavigationSidebarItem>
<UserSettingsIcon></UserSettingsIcon>
<Button
v-if="page.props.has_services_extension"
variant="outline"
size="xs"
class="rounded-full ml-2 flex h-6 w-6 items-center text-xs text-icon-default justify-center"
@click="openFeedback">
?
</Button>
</ul>
</div>
</div>
</div>
<div class="flex-1 lg:ml-[230px] 2xl:ml-[250px] min-w-0">
<div
class="lg:hidden w-full px-3 py-1 border-b border-b-default-background-separator text-text-secondary flex justify-between items-center">
<Bars3Icon
class="w-7 text-text-secondary"
@click="showSidebarMenu = !showSidebarMenu"></Bars3Icon>
<OrganizationSwitcher></OrganizationSwitcher>
</div>
class="h-screen overflow-y-auto flex flex-col bg-default-background border-l border-default-background-separator">
<div
class="lg:hidden w-full px-3 py-1 border-b border-b-default-background-separator text-text-secondary flex justify-between items-center">
<Bars3Icon
class="w-7 text-text-secondary"
@click="showSidebarMenu = !showSidebarMenu"></Bars3Icon>
<OrganizationSwitcher></OrganizationSwitcher>
</div>
<Head :title="title" />
<Head :title="title" />
<Banner />
<BillingBanner v-if="isBillingActivated()" />
<div
class="min-h-screen flex flex-col bg-default-background border-l border-default-background-separator">
<!-- Page Heading -->
<Banner />
<BillingBanner v-if="isBillingActivated()" />
<header
v-if="$slots.header"
class="bg-default-background border-b border-default-background-separator shadow">
@@ -273,7 +293,7 @@ const page = usePage<{
</header>
<!-- Page Content -->
<main class="pb-28 flex-1">
<main :class="twMerge('pb-28 relative flex-1', mainClass)">
<div
v-if="isOrganizationLoading"
class="flex items-center justify-center h-screen">
@@ -285,4 +305,5 @@ const page = usePage<{
</div>
</div>
<NotificationContainer></NotificationContainer>
<UserTimezoneMismatchModal></UserTimezoneMismatchModal>
</template>

View File

@@ -0,0 +1,140 @@
<script setup lang="ts">
import AppLayout from '@/Layouts/AppLayout.vue';
import { useQuery, useQueryClient } from '@tanstack/vue-query';
import {
api,
type Client,
type CreateClientBody,
type CreateProjectBody,
type Project,
type TimeEntryResponse,
} from '@/packages/api/src';
import { getCurrentOrganizationId } from '@/utils/useUser';
import { computed, ref } from 'vue';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
import { TimeEntryCalendar } from '@/packages/ui/src';
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
import { useTimeEntriesStore } from '@/utils/useTimeEntries';
import { useTagsStore } from '@/utils/useTags';
import { useProjectsStore } from '@/utils/useProjects';
import { useClientsStore } from '@/utils/useClients';
import { storeToRefs } from 'pinia';
import { useTasksStore } from '@/utils/useTasks';
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
const calendarStart = ref<Date | undefined>(undefined);
const calendarEnd = ref<Date | undefined>(undefined);
const enableCalendarQuery = computed(() => {
return !!getCurrentOrganizationId() && !!calendarStart.value && !!calendarEnd.value;
});
// Calculate expanded date range to include previous and next periods with timezone transformations
const expandedDateRange = computed(() => {
if (!calendarStart.value || !calendarEnd.value) {
return { start: null, end: null };
}
const dayjs = getDayJsInstance();
const duration = dayjs(calendarEnd.value).diff(dayjs(calendarStart.value), 'milliseconds');
// Calculate previous period
const previousStart = dayjs(calendarStart.value).subtract(duration, 'milliseconds');
// Calculate next period
const nextEnd = dayjs(calendarEnd.value).add(duration, 'milliseconds');
// Apply timezone transformations
const formattedStart = previousStart.utc().tz(getUserTimezone(), true).utc().format();
const formattedEnd = nextEnd.utc().tz(getUserTimezone(), true).utc().format();
return {
start: formattedStart,
end: formattedEnd,
};
});
const { data: timeEntryResponse, isLoading: timeEntriesLoading } = useQuery<TimeEntryResponse>({
queryKey: computed(() => [
'timeEntry',
'calendar',
{
start: expandedDateRange.value.start,
end: expandedDateRange.value.end,
organization: getCurrentOrganizationId(),
},
]),
enabled: enableCalendarQuery,
placeholderData: (previousData) => previousData,
queryFn: () =>
api.getTimeEntries({
params: {
organization: getCurrentOrganizationId() || '',
},
queries: {
start: expandedDateRange.value.start!,
end: expandedDateRange.value.end!,
},
}),
});
const currentTimeEntries = computed(() => {
return timeEntryResponse?.value?.data || [];
});
const { createTimeEntry, updateTimeEntry, deleteTimeEntry } = useTimeEntriesStore();
async function createTag(name: string) {
return await useTagsStore().createTag(name);
}
async function createProject(project: CreateProjectBody): Promise<Project | undefined> {
return await useProjectsStore().createProject(project);
}
async function createClient(body: CreateClientBody): Promise<Client | undefined> {
return await useClientsStore().createClient(body);
}
const projectStore = useProjectsStore();
const { projects } = storeToRefs(projectStore);
const taskStore = useTasksStore();
const { tasks } = storeToRefs(taskStore);
const clientStore = useClientsStore();
const { clients } = storeToRefs(clientStore);
const tagsStore = useTagsStore();
const { tags } = storeToRefs(tagsStore);
const queryClient = useQueryClient();
function onDatesChange({ start, end }: { start: Date; end: Date }) {
calendarStart.value = start;
calendarEnd.value = end;
}
function onRefresh() {
queryClient.invalidateQueries({
queryKey: ['timeEntry', 'calendar'],
});
}
</script>
<template>
<AppLayout title="Calendar" data-testid="calendar_view" main-class="p-0">
<TimeEntryCalendar
:time-entries="currentTimeEntries"
:projects="projects"
:tasks="tasks"
:clients="clients"
:tags="tags"
:loading="timeEntriesLoading"
:enable-estimated-time="isAllowedToPerformPremiumAction()"
:create-time-entry="createTimeEntry"
:update-time-entry="updateTimeEntry"
:delete-time-entry="deleteTimeEntry"
:create-client="createClient"
:create-project="createProject"
:create-tag="createTag"
@dates-change="onDatesChange"
@refresh="onRefresh" />
</AppLayout>
</template>

View File

@@ -369,6 +369,7 @@ async function downloadExport(format: ExportFormat) {
:tags="tags"
:currency="getOrganizationCurrencyString()"
:clients="clients"
class="border-b border-default-background-separator"
:update-time-entries="
(args) =>
updateTimeEntries(
@@ -399,6 +400,7 @@ async function downloadExport(format: ExportFormat) {
:on-start-stop-click="() => startTimeEntryFromExisting(entry)"
:delete-time-entry="() => deleteTimeEntries([entry])"
:currency="getOrganizationCurrencyString()"
:duplicate-time-entry="() => createTimeEntry(entry)"
:members="members"
show-date
show-member

View File

@@ -27,7 +27,7 @@ interface FormValues {
}
const store = useOrganizationStore();
const { fetchOrganization, updateOrganization } = store;
const { updateOrganization } = store;
const { organization } = storeToRefs(store);
const queryClient = useQueryClient();
@@ -47,7 +47,6 @@ const mutation = useMutation({
});
onMounted(async () => {
await fetchOrganization();
if (organization.value) {
form.value = {
number_format: organization.value.number_format as NumberFormat,

View File

@@ -0,0 +1,68 @@
<script setup lang="ts">
import FormSection from '@/Components/FormSection.vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { onMounted, ref } from 'vue';
import InputLabel from '@/packages/ui/src/Input/InputLabel.vue';
import { Checkbox } from '@/packages/ui/src';
import type { UpdateOrganizationBody } from '@/packages/api/src';
import { useOrganizationStore } from '@/utils/useOrganization';
import { storeToRefs } from 'pinia';
import { useMutation, useQueryClient } from '@tanstack/vue-query';
const store = useOrganizationStore();
const { updateOrganization } = store;
const { organization } = storeToRefs(store);
const queryClient = useQueryClient();
const form = ref<{ prevent_overlapping_time_entries: boolean }>({
prevent_overlapping_time_entries: false,
});
onMounted(async () => {
form.value.prevent_overlapping_time_entries =
organization.value?.prevent_overlapping_time_entries ?? false;
});
const mutation = useMutation({
mutationFn: (values: Partial<UpdateOrganizationBody>) => updateOrganization(values),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['organization'] });
},
});
async function submit() {
await mutation.mutateAsync({
prevent_overlapping_time_entries: form.value.prevent_overlapping_time_entries,
});
}
</script>
<template>
<FormSection>
<template #title>Time Entry Settings</template>
<template #description>
Disallow overlapping time entries for members of this organization. When enabled, users
cannot create new time entries that overlap with their existing ones. This only affects
newly created entries.
</template>
<template #form>
<div class="col-span-6">
<div class="col-span-6 sm:col-span-4">
<div class="flex items-center space-x-2">
<Checkbox
id="preventOverlappingTimeEntries"
v-model:checked="form.prevent_overlapping_time_entries" />
<InputLabel
for="preventOverlappingTimeEntries"
value="Prevent overlapping time entries (new entries only)" />
</div>
</div>
</div>
</template>
<template #actions>
<PrimaryButton :disabled="mutation.isPending.value" @click="submit">Save</PrimaryButton>
</template>
</FormSection>
</template>

View File

@@ -8,12 +8,25 @@ import type { Permissions, Role } from '@/types/jetstream';
import { canUpdateOrganization } from '@/utils/permissions';
import OrganizationBillableRate from '@/Pages/Teams/Partials/OrganizationBillableRate.vue';
import OrganizationFormatSettings from '@/Pages/Teams/Partials/OrganizationFormatSettings.vue';
import OrganizationTimeEntrySettings from '@/Pages/Teams/Partials/OrganizationTimeEntrySettings.vue';
import { onMounted, ref } from 'vue';
import { useOrganizationStore } from '@/utils/useOrganization';
import { storeToRefs } from 'pinia';
defineProps<{
team: Organization;
availableRoles: Role[];
permissions: Permissions;
}>();
const loading = ref(true);
const orgStore = useOrganizationStore();
const { organization } = storeToRefs(orgStore);
onMounted(async () => {
await orgStore.fetchOrganization();
loading.value = false;
});
</script>
<template>
@@ -26,17 +39,25 @@ defineProps<{
<div>
<div class="max-w-7xl mx-auto py-10 sm:px-6 lg:px-8">
<UpdateTeamNameForm :team="team" :permissions="permissions" />
<div v-if="loading || !organization" class="py-16 text-center text-text-secondary">
Loading organization settings...
</div>
<template v-else>
<UpdateTeamNameForm :team="team" :permissions="permissions" />
<SectionBorder />
<OrganizationBillableRate v-if="canUpdateOrganization()" :team="team" />
<SectionBorder />
<SectionBorder />
<OrganizationBillableRate v-if="canUpdateOrganization()" :team="team" />
<SectionBorder />
<OrganizationFormatSettings v-if="canUpdateOrganization()" :team="team" />
<SectionBorder />
<OrganizationFormatSettings v-if="canUpdateOrganization()" :team="team" />
<SectionBorder />
<template v-if="permissions.canDeleteTeam && !team.personal_team">
<DeleteTeamForm class="mt-10 sm:mt-0" :team="team" />
<OrganizationTimeEntrySettings v-if="canUpdateOrganization()" />
<SectionBorder />
<template v-if="permissions.canDeleteTeam && !team.personal_team">
<DeleteTeamForm class="mt-10 sm:mt-0" :team="team" />
</template>
</template>
</div>
</div>

View File

@@ -144,6 +144,7 @@ function deleteSelected() {
:tags="tags"
:currency="getOrganizationCurrencyString()"
:clients="clients"
class="border-t border-default-background-separator"
:update-time-entries="
(args) =>
updateTimeEntries(

View File

@@ -36,20 +36,14 @@ const ClientResource = z
const ClientCollection = z.array(ClientResource);
const ClientStoreRequest = z.object({ name: z.string().min(1).max(255) }).passthrough();
const ClientUpdateRequest = z
.object({
name: z.string().min(1).max(255),
is_archived: z.boolean().optional(),
})
.object({ name: z.string().min(1).max(255), is_archived: z.boolean().optional() })
.passthrough();
const ImportRequest = z.object({ type: z.string(), data: z.string() }).passthrough();
const InvitationResource = z
.object({ id: z.string(), email: z.string(), role: z.string() })
.passthrough();
const InvitationStoreRequest = z
.object({
email: z.string().email(),
role: z.enum(['admin', 'manager', 'employee']),
})
.object({ email: z.string().email(), role: z.enum(['admin', 'manager', 'employee']) })
.passthrough();
const InvoiceResource = z
.object({
@@ -97,6 +91,7 @@ const InvoiceStoreRequest = z
billing_period_end: z.union([z.string(), z.null()]).optional(),
reference: z.string(),
currency: z.string(),
payment_iban: z.union([z.string(), z.null()]).optional(),
tax_rate: z.number().int().gte(0).lte(2147483647).optional(),
discount_amount: z.number().int().gte(0).lte(9223372036854776000).optional(),
discount_type: InvoiceDiscountType.optional(),
@@ -161,6 +156,7 @@ const DetailedInvoiceResource = z
discount_type: z.string(),
discount_amount: z.number().int(),
tax_rate: z.number().int(),
payment_iban: z.string(),
status: z.string(),
currency: z.string(),
date: z.string(),
@@ -206,6 +202,7 @@ const InvoiceUpdateRequest = z
billing_period_end: z.union([z.string(), z.null()]),
reference: z.string(),
currency: z.string(),
payment_iban: z.union([z.string(), z.null()]),
tax_rate: z.number().int().gte(0).lte(2147483647),
discount_amount: z.number().int().gte(0).lte(9223372036854776000),
discount_type: InvoiceDiscountType,
@@ -320,6 +317,7 @@ const OrganizationResource = z
is_personal: z.boolean(),
billable_rate: z.union([z.number(), z.null()]),
employees_can_see_billable_rates: z.boolean(),
prevent_overlapping_time_entries: z.boolean(),
currency: z.string(),
currency_symbol: z.string(),
number_format: NumberFormat,
@@ -334,6 +332,7 @@ const OrganizationUpdateRequest = z
name: z.string().max(255),
billable_rate: z.union([z.number(), z.null()]),
employees_can_see_billable_rates: z.boolean(),
prevent_overlapping_time_entries: z.boolean(),
number_format: NumberFormat,
currency_format: CurrencyFormat,
date_format: DateFormat,
@@ -388,10 +387,7 @@ const ProjectMemberResource = z
})
.passthrough();
const ProjectMemberStoreRequest = z
.object({
member_id: z.string(),
billable_rate: z.union([z.number(), z.null()]).optional(),
})
.object({ member_id: z.string(), billable_rate: z.union([z.number(), z.null()]).optional() })
.passthrough();
const ProjectMemberUpdateRequest = z
.object({ billable_rate: z.union([z.number(), z.null()]) })
@@ -420,6 +416,7 @@ const TimeEntryAggregationType = z.enum([
'client',
'billable',
'description',
'tag',
]);
const TimeEntryAggregationTypeInterval = z.enum(['day', 'week', 'month', 'year']);
const Weekday = z.enum([
@@ -431,6 +428,7 @@ const Weekday = z.enum([
'saturday',
'sunday',
]);
const TimeEntryRoundingType = z.enum(['up', 'down', 'nearest']);
const ReportStoreRequest = z
.object({
name: z.string().max(255),
@@ -453,6 +451,8 @@ const ReportStoreRequest = z
history_group: TimeEntryAggregationTypeInterval,
week_start: Weekday.optional(),
timezone: z.union([z.string(), z.null()]).optional(),
rounding_type: TimeEntryRoundingType.optional(),
rounding_minutes: z.union([z.number(), z.null()]).optional(),
})
.passthrough(),
})
@@ -479,6 +479,8 @@ const DetailedReportResource = z
project_ids: z.union([z.array(z.string()), z.null()]),
tag_ids: z.union([z.array(z.string()), z.null()]),
task_ids: z.union([z.array(z.string()), z.null()]),
rounding_type: z.union([z.string(), z.null()]),
rounding_minutes: z.union([z.number(), z.null()]),
})
.passthrough(),
created_at: z.string(),
@@ -592,12 +594,7 @@ const DetailedWithDataReportResource = z
})
.passthrough();
const TagResource = z
.object({
id: z.string(),
name: z.string(),
created_at: z.string(),
updated_at: z.string(),
})
.object({ id: z.string(), name: z.string(), created_at: z.string(), updated_at: z.string() })
.passthrough();
const TagCollection = z.array(TagResource);
const TagStoreRequest = z.object({ name: z.string().min(1).max(255) }).passthrough();
@@ -629,6 +626,7 @@ const TaskUpdateRequest = z
})
.passthrough();
const start = z.union([z.string(), z.null()]).optional();
const rounding_minutes = z.union([z.number(), z.null()]).optional();
const TimeEntryResource = z
.object({
id: z.string(),
@@ -749,6 +747,7 @@ export const schemas = {
TimeEntryAggregationType,
TimeEntryAggregationTypeInterval,
Weekday,
TimeEntryRoundingType,
ReportStoreRequest,
DetailedReportResource,
ReportUpdateRequest,
@@ -761,6 +760,7 @@ export const schemas = {
TaskStoreRequest,
TaskUpdateRequest,
start,
rounding_minutes,
TimeEntryResource,
TimeEntryStoreRequest,
TimeEntryUpdateMultipleRequest,
@@ -790,13 +790,7 @@ const endpoints = makeApi([
alias: 'getCurrencies',
requestFormat: 'json',
response: z.array(
z
.object({
code: z.string(),
name: z.string(),
symbol: z.string(),
})
.passthrough()
z.object({ code: z.string(), name: z.string(), symbol: z.string() }).passthrough()
),
},
{
@@ -868,10 +862,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1166,13 +1157,7 @@ const endpoints = makeApi([
},
],
response: z.array(
z
.object({
value: z.number().int(),
name: z.string(),
color: z.string(),
})
.passthrough()
z.object({ value: z.number().int(), name: z.string(), color: z.string() }).passthrough()
),
errors: [
{
@@ -1235,10 +1220,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1281,10 +1263,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1332,10 +1311,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1363,11 +1339,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -1405,11 +1377,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -1465,7 +1433,7 @@ const endpoints = makeApi([
status: 400,
schema: z.union([
z.object({ message: z.string() }).passthrough(),
z.object({ message: z.string() }).passthrough(),
z.object({ message: z.literal('Invalid base64 encoded data') }).passthrough(),
]),
},
{
@@ -1487,10 +1455,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1511,11 +1476,7 @@ const endpoints = makeApi([
.object({
data: z.array(
z
.object({
key: z.string(),
name: z.string(),
description: z.string(),
})
.object({ key: z.string(), name: z.string(), description: z.string() })
.passthrough()
),
})
@@ -1603,10 +1564,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1634,11 +1592,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -1660,10 +1614,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1809,10 +1760,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1855,10 +1803,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1901,10 +1846,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -1988,10 +1930,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2056,6 +1995,13 @@ const endpoints = makeApi([
],
response: z.object({ download_link: z.string() }).passthrough(),
errors: [
{
status: 400,
description: `API exception`,
schema: z
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
status: 401,
description: `Unauthenticated`,
@@ -2075,10 +2021,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2102,6 +2045,13 @@ const endpoints = makeApi([
],
response: z.object({ download_link: z.string() }).passthrough(),
errors: [
{
status: 400,
description: `API exception`,
schema: z
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
status: 401,
description: `Unauthenticated`,
@@ -2147,11 +2097,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2173,10 +2119,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2246,10 +2189,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2282,11 +2222,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2308,10 +2244,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2344,11 +2277,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2370,10 +2299,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2401,11 +2327,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2448,11 +2370,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2515,10 +2433,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2634,10 +2549,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2680,10 +2592,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2767,10 +2676,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -2798,11 +2704,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2918,11 +2820,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -2944,10 +2842,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3053,10 +2948,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3140,10 +3032,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3253,10 +3142,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3304,10 +3190,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3335,11 +3218,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -3434,10 +3313,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3480,10 +3356,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3531,10 +3404,7 @@ const endpoints = makeApi([
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3562,11 +3432,7 @@ const endpoints = makeApi([
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -3639,6 +3505,16 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
type: 'Query',
schema: z.enum(['true', 'false']).optional(),
},
{
name: 'rounding_type',
type: 'Query',
schema: z.enum(['up', 'down', 'nearest']).optional(),
},
{
name: 'rounding_minutes',
type: 'Query',
schema: rounding_minutes,
},
{
name: 'user_id',
type: 'Query',
@@ -3696,10 +3572,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3727,11 +3600,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -3753,10 +3622,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3799,10 +3665,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3845,10 +3708,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3881,11 +3741,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -3907,10 +3763,7 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -3980,6 +3833,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'client',
'billable',
'description',
'tag',
])
.optional(),
},
@@ -3998,6 +3852,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'client',
'billable',
'description',
'tag',
])
.optional(),
},
@@ -4036,6 +3891,16 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
type: 'Query',
schema: z.enum(['true', 'false']).optional(),
},
{
name: 'rounding_type',
type: 'Query',
schema: z.enum(['up', 'down', 'nearest']).optional(),
},
{
name: 'rounding_minutes',
type: 'Query',
schema: rounding_minutes,
},
{
name: 'member_ids',
type: 'Query',
@@ -4120,10 +3985,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -4158,6 +4020,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'client',
'billable',
'description',
'tag',
]),
},
{
@@ -4174,6 +4037,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'client',
'billable',
'description',
'tag',
]),
},
{
@@ -4221,6 +4085,16 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
type: 'Query',
schema: z.enum(['true', 'false']).optional(),
},
{
name: 'rounding_type',
type: 'Query',
schema: z.enum(['up', 'down', 'nearest']).optional(),
},
{
name: 'rounding_minutes',
type: 'Query',
schema: rounding_minutes,
},
{
name: 'member_ids',
type: 'Query',
@@ -4256,11 +4130,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -4282,10 +4152,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -4346,6 +4213,16 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
type: 'Query',
schema: z.enum(['true', 'false']).optional(),
},
{
name: 'rounding_type',
type: 'Query',
schema: z.enum(['up', 'down', 'nearest']).optional(),
},
{
name: 'rounding_minutes',
type: 'Query',
schema: rounding_minutes,
},
{
name: 'member_ids',
type: 'Query',
@@ -4376,11 +4253,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -4402,10 +4275,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -4487,11 +4357,7 @@ Please note that the access token is only shown in this response and cannot be r
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -4508,10 +4374,7 @@ Please note that the access token is only shown in this response and cannot be r
status: 422,
description: `Validation error`,
schema: z
.object({
message: z.string(),
errors: z.record(z.array(z.string())),
})
.object({ message: z.string(), errors: z.record(z.array(z.string())) })
.passthrough(),
},
],
@@ -4534,11 +4397,7 @@ Please note that the access token is only shown in this response and cannot be r
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{
@@ -4576,11 +4435,7 @@ Please note that the access token is only shown in this response and cannot be r
status: 400,
description: `API exception`,
schema: z
.object({
error: z.boolean(),
key: z.string(),
message: z.string(),
})
.object({ error: z.boolean(), key: z.string(), message: z.string() })
.passthrough(),
},
{

View File

@@ -10,7 +10,8 @@ const props = withDefaults(
icon?: Component;
size?: 'small' | 'base';
loading?: boolean;
class?: string;
// Accept any valid Vue class binding shape (string | object | array)
class?: Parameters<typeof twMerge>[0];
}>(),
{
type: 'button',

View File

@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed, inject, type ComputedRef } from 'vue';
import { formatDate, formatHumanReadableDuration } from '../utils/time';
import type { Organization } from '@/packages/api/src';
import type { Dayjs } from 'dayjs';
const props = defineProps<{
date: Dayjs;
totalMinutes?: number;
}>();
const totalSeconds = computed(() => (props.totalMinutes ?? 0) * 60);
// Injected organization for formatting settings
const organization = inject('organization') as ComputedRef<Organization | undefined> | undefined;
const intervalFormat = computed(() => organization?.value?.interval_format);
const numberFormat = computed(() => organization?.value?.number_format);
const dateFormat = computed(() => organization?.value?.date_format);
</script>
<template>
<div class="fc-day-header-custom">
<div class="text-xs text-muted-foreground font-medium">
{{ date.format('ddd') }}
</div>
<span>{{ formatDate(date.toISOString(), dateFormat) }}</span>
<span class="block text-xs text-muted-foreground font-medium mt-1">
{{ formatHumanReadableDuration(totalSeconds, intervalFormat, numberFormat) }}
</span>
</div>
</template>

View File

@@ -0,0 +1,58 @@
<script setup lang="ts">
import { computed, inject, type ComputedRef } from 'vue';
import { formatHumanReadableDuration, getDayJsInstance } from '../utils/time';
import type { Organization } from '@/packages/api/src';
const props = defineProps<{
title: string;
projectName?: string | null;
taskName?: string | null;
clientName?: string | null;
durationSeconds?: number;
start?: string | Date | null;
end?: string | Date | null;
}>();
const effectiveDurationSeconds = computed(() => {
if (typeof props.durationSeconds === 'number') {
return props.durationSeconds;
}
if (props.start && props.end) {
const end = getDayJsInstance()(props.end as unknown as string | Date);
const start = getDayJsInstance()(props.start as unknown as string | Date);
const minutes = end.diff(start, 'minutes');
return minutes * 60;
}
return 0;
});
const organization = inject('organization') as ComputedRef<Organization | undefined> | undefined;
const intervalFormat = computed(() => organization?.value?.interval_format);
const numberFormat = computed(() => organization?.value?.number_format);
const formattedDuration = computed(() =>
formatHumanReadableDuration(
effectiveDurationSeconds.value,
intervalFormat.value,
numberFormat.value
)
);
</script>
<template>
<div class="text-xs leading-tight">
<div class="font-semibold mb-0.5">{{ title }}</div>
<div v-if="projectName" class="font-medium text-[0.6875rem] opacity-90">
{{ projectName }}
</div>
<div v-if="taskName" class="font-medium text-[0.6875rem] opacity-90">
{{ taskName }}
</div>
<div v-if="clientName" class="text-[0.625rem] italic opacity-85">
{{ clientName }}
</div>
<div class="text-[0.625rem] font-semibold opacity-90 mt-0.5">
{{ formattedDuration }}
</div>
</div>
</template>

View File

@@ -0,0 +1,603 @@
<script setup lang="ts">
import FullCalendar from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';
import type { DatesSetArg, EventClickArg, EventDropArg, EventChangeArg } from '@fullcalendar/core';
import { computed, ref, watch, inject, type ComputedRef } from 'vue';
import chroma from 'chroma-js';
import { useCssVariable } from '@/utils/useCssVariable';
import { getDayJsInstance, getLocalizedDayJs } from '../utils/time';
import { getUserTimezone, getWeekStart } from '../utils/settings';
import { LoadingSpinner, TimeEntryCreateModal, TimeEntryEditModal } from '..';
import FullCalendarEventContent from './FullCalendarEventContent.vue';
import FullCalendarDayHeader from './FullCalendarDayHeader.vue';
import type {
TimeEntry,
Project,
Client,
Task,
CreateProjectBody,
CreateClientBody,
Tag,
Organization,
} from '@/packages/api/src';
import type { Dayjs } from 'dayjs';
type CalendarExtendedProps = { timeEntry: TimeEntry } & Record<string, unknown>;
const emit = defineEmits<{
(e: 'dates-change', payload: { start: Date; end: Date }): void;
(e: 'refresh'): void;
}>();
const props = defineProps<{
timeEntries: TimeEntry[];
projects: Project[];
tasks: Task[];
clients: Client[];
tags: Tag[];
loading?: boolean;
// Permissions / feature flags
enableEstimatedTime: boolean;
createTimeEntry: (
entry: Omit<TimeEntry, 'id' | 'organization_id' | 'user_id'>
) => Promise<void>;
updateTimeEntry: (entry: TimeEntry) => Promise<void>;
deleteTimeEntry: (timeEntryId: string) => Promise<void>;
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
createTag: (name: string) => Promise<Tag | undefined>;
}>();
// Local component state
const newEventStart = ref<Dayjs | null>(null);
const newEventEnd = ref<Dayjs | null>(null);
const showCreateTimeEntryModal = ref<boolean>(false);
const showEditTimeEntryModal = ref<boolean>(false);
const selectedTimeEntry = ref<TimeEntry | null>(null);
const calendarRef = ref<InstanceType<typeof FullCalendar> | null>(null);
// Inject organization data for settings
const organization = inject<ComputedRef<Organization>>('organization');
// Helper function to convert week start to FullCalendar firstDay value
const getFirstDay = () => {
const weekStart = getWeekStart();
const weekStartMap: Record<string, number> = {
'sunday': 0,
'monday': 1,
'tuesday': 2,
'wednesday': 3,
'thursday': 4,
'friday': 5,
'saturday': 6,
};
return weekStartMap[weekStart] ?? 1; // Default to Monday if not found
};
// Helper function to get time format for slot labels
const getSlotLabelFormat = () => {
const timeFormat = organization?.value?.time_format || '24-hours';
if (timeFormat === '12-hours') {
return {
hour: 'numeric' as const,
hour12: true,
};
} else {
return {
hour: '2-digit' as const,
minute: '2-digit' as const,
hour12: false,
};
}
};
const cssBackground = useCssVariable('--color-bg-background');
const events = computed(() => {
const themeBackground = (() => {
return cssBackground.value?.trim();
})();
return props.timeEntries
?.filter((timeEntry) => timeEntry.end !== null)
?.map((timeEntry) => {
const project = props.projects.find((p) => p.id === timeEntry.project_id);
const client = props.clients.find((c) => c.id === project?.client_id);
const task = props.tasks.find((t) => t.id === timeEntry.task_id);
const duration = getDayJsInstance()(timeEntry.end!).diff(
getDayJsInstance()(timeEntry.start),
'minutes'
);
const title = timeEntry.description || 'No description';
const baseColor = project?.color || '#6B7280';
const backgroundColor = chroma.mix(baseColor, themeBackground, 0.65, 'lab').hex();
const borderColor = chroma.mix(baseColor, themeBackground, 0.5, 'lab').hex();
// For 0-duration events, display them with minimum visual duration but preserve actual duration
const startTime = getLocalizedDayJs(timeEntry.start);
const endTime =
duration === 0
? startTime.add(1, 'second') // Show as 1 second for minimal visibility
: getLocalizedDayJs(timeEntry.end!);
return {
id: timeEntry.id,
start: startTime.format(),
end: endTime.format(),
title,
backgroundColor,
borderColor,
textColor: 'var(--foreground)',
extendedProps: {
timeEntry,
project,
client,
task,
duration,
},
};
});
});
// Daily totals used in day header
const dailyTotals = computed(() => {
const totals: Record<string, number> = {};
props.timeEntries
.filter((entry) => entry.end !== null)
.forEach((entry) => {
const date = getDayJsInstance()(entry.start).format('YYYY-MM-DD');
const duration = getDayJsInstance()(entry.end!).diff(
getDayJsInstance()(entry.start),
'minutes'
);
totals[date] = (totals[date] || 0) + duration;
});
return totals;
});
function emitDatesChange(arg: DatesSetArg) {
emit('dates-change', { start: arg.start, end: arg.end });
}
function handleDateSelect(arg: { start: Date; end: Date }) {
const startTime = getDayJsInstance()(arg.start.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc();
const endTime = getDayJsInstance()(arg.end.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc();
newEventStart.value = startTime;
newEventEnd.value = endTime;
showCreateTimeEntryModal.value = true;
}
function handleEventClick(arg: EventClickArg) {
const ext = arg.event.extendedProps as CalendarExtendedProps;
selectedTimeEntry.value = ext.timeEntry;
showEditTimeEntryModal.value = true;
}
async function handleEventDrop(arg: EventDropArg) {
const ext = arg.event.extendedProps as CalendarExtendedProps;
const timeEntry = ext.timeEntry;
if (!arg.event.start || !arg.event.end) return;
const updatedTimeEntry = {
...timeEntry,
start: getDayJsInstance()(arg.event.start.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc()
.format(),
end: getDayJsInstance()(arg.event.end.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc()
.format(),
} as TimeEntry;
await props.updateTimeEntry(updatedTimeEntry);
emit('refresh');
}
async function handleEventResize(arg: EventChangeArg) {
const ext = arg.event.extendedProps as CalendarExtendedProps;
const timeEntry = ext.timeEntry;
if (!arg.event.start || !arg.event.end) return;
const updatedTimeEntry = {
...timeEntry,
start: getDayJsInstance()(arg.event.start.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc()
.format(),
end: getDayJsInstance()(arg.event.end.toISOString())
.utc()
.tz(getUserTimezone(), true)
.utc()
.format(),
} as TimeEntry;
await props.updateTimeEntry(updatedTimeEntry);
emit('refresh');
}
const calendarOptions = computed(() => ({
plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
initialView: 'timeGridWeek',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'timeGridWeek,timeGridDay',
},
height: 'parent',
slotMinTime: '00:00:00',
slotMaxTime: '24:00:00',
slotDuration: '00:15:00',
slotLabelInterval: '01:00:00',
slotLabelFormat: getSlotLabelFormat(),
snapDuration: '00:15:00',
firstDay: getFirstDay(),
allDaySlot: false,
nowIndicator: true,
selectable: true,
selectMirror: true,
editable: true,
eventResizableFromStart: true,
eventDurationEditable: true,
timeZone: getUserTimezone(),
eventStartEditable: true,
select: handleDateSelect,
eventClick: handleEventClick,
eventDrop: handleEventDrop,
eventResize: handleEventResize,
datesSet: emitDatesChange,
events: events.value,
}));
watch(showCreateTimeEntryModal, (value) => {
if (!value) {
newEventStart.value = null;
newEventEnd.value = null;
// Ensure FullCalendar clears the selection mirror when modal closes
calendarRef.value?.getApi().unselect();
emit('refresh');
}
});
watch(showEditTimeEntryModal, (value) => {
if (!value) {
selectedTimeEntry.value = null;
emit('refresh');
}
});
</script>
<template>
<div class="w-full relative h-full flex-1">
<div v-if="loading" class="flex items-center justify-center h-full">
<div class="flex flex-col items-center space-y-4">
<LoadingSpinner class="h-8 w-8" />
<p class="text-muted-foreground">Loading calendar data...</p>
</div>
</div>
<TimeEntryCreateModal
v-model:show="showCreateTimeEntryModal"
:enable-estimated-time="enableEstimatedTime"
:create-time-entry="createTimeEntry"
:create-client="createClient"
:create-project="createProject"
:create-tag="createTag"
:tags="tags as any"
:projects="projects"
:tasks="tasks"
:clients="clients"
:start="newEventStart ? newEventStart.toISOString() : undefined"
:end="newEventEnd ? newEventEnd.toISOString() : undefined" />
<TimeEntryEditModal
v-model:show="showEditTimeEntryModal"
:time-entry="selectedTimeEntry as any"
:enable-estimated-time="enableEstimatedTime"
:update-time-entry="updateTimeEntry"
:delete-time-entry="deleteTimeEntry"
:create-client="createClient"
:create-project="createProject"
:create-tag="createTag"
:tags="tags as any"
:projects="projects"
:tasks="tasks"
:clients="clients" />
<FullCalendar ref="calendarRef" class="fullcalendar" :options="calendarOptions">
<template #eventContent="arg">
<FullCalendarEventContent
:title="arg.event.title"
:project-name="(arg.event.extendedProps as any).project?.name"
:task-name="(arg.event.extendedProps as any).task?.name"
:client-name="(arg.event.extendedProps as any).client?.name"
:duration-seconds="
((arg.event.extendedProps as any).duration ?? undefined)
? (arg.event.extendedProps as any).duration * 60
: undefined
"
:start="arg.event.start as any"
:end="arg.event.end as any" />
</template>
<template #dayHeaderContent="arg">
<FullCalendarDayHeader
:date="
getDayJsInstance()(arg.date.toISOString()).utc().tz(getUserTimezone(), true)
"
:total-minutes="
dailyTotals[
getDayJsInstance()(arg.date)
.utc()
.tz(getUserTimezone(), true)
.format('YYYY-MM-DD')
] || 0
" />
</template>
</FullCalendar>
</div>
</template>
<style scoped>
.fullcalendar {
height: 100%;
--fc-border-color: var(--border);
}
/* FullCalendar theme customization */
.fullcalendar :deep(.fc) {
background-color: var(--theme-color-default-background);
color: var(--foreground);
font-family: inherit;
}
.fullcalendar :deep(.fc-timegrid-slot) {
height: 25px;
transition: height 0.2s ease;
}
.fullcalendar :deep(.fc-timegrid-slot-label) {
background-color: var(--theme-color-default-background);
}
.fullcalendar :deep(.fc-toolbar) {
background-color: var(--theme-color-default-background);
padding: 0.5rem;
margin-bottom: 0;
}
.fullcalendar :deep(.fc-toolbar-title) {
color: var(--foreground);
font-size: 1rem;
font-weight: 600;
}
.fullcalendar :deep(.fc-button) {
background-color: var(--secondary);
border: 1px solid var(--border);
color: var(--foreground);
font-weight: 500;
font-size: 14px !important;
}
.fullcalendar :deep(.fc-button:hover) {
background-color: var(--muted);
border-color: var(--border);
}
.fullcalendar :deep(.fc-button:focus) {
box-shadow: 0 0 0 2px var(--ring);
}
.fullcalendar :deep(.fc-button-active) {
background-color: var(--primary);
border-color: var(--primary);
color: var(--primary-foreground);
}
.fullcalendar :deep(.fc-col-header) {
border-bottom: 1px solid var(--border);
}
.fullcalendar :deep(.fc-col-header-cell) {
border-right: 1px solid var(--border);
border-bottom: 1px solid var(--border);
padding: 0.75rem 0.5rem;
background-color: var(--theme-color-default-background);
}
.fullcalendar :deep(.fc-timegrid-axis) {
background-color: var(--theme-color-default-background) !important;
}
.fullcalendar :deep(.fc-col-header-cell .fc-col-header-cell-cushion) {
padding: 0;
}
.fullcalendar :deep(.fc-timegrid-axis) {
background-color: var(--theme-color-default-background);
border-right: 1px solid var(--border);
}
/* Quarter-hour slots - transparent borders */
.fullcalendar :deep(.fc-timegrid-slot-minor.fc-timegrid-slot-label) {
border-top: 1px solid transparent;
}
.fullcalendar :deep(.fc-timegrid-slot-minor.fc-timegrid-slot-lane) {
--tw-border-opacity: 0;
}
.fullcalendar :deep(.fc-day-today.fc-col-header-cell) {
background-color: var(--color-accent-default);
}
.fullcalendar :deep(.fc-day-today) {
background-color: var(--theme-color-default-background);
}
.fullcalendar :deep(.fc-now-indicator) {
border-color: var(--primary);
border-width: 2px;
}
.fullcalendar :deep(.fc-event) {
border-radius: var(--radius);
padding: 0.45rem 0.25rem;
font-size: 0.75rem;
cursor: pointer;
box-shadow: var(--theme-shadow-card);
opacity: 0.9;
overflow: hidden;
}
.fullcalendar :deep(.fc-v-event) {
background-color: var(--muted);
border-color: var(--muted);
}
.fullcalendar :deep(.fc-event-title) {
font-weight: 500;
line-height: 1.2;
}
/* Enhanced FullCalendar resize handles */
.fullcalendar :deep(.fc-event-resizer) {
position: absolute;
z-index: 99;
background: '#FFF';
border-radius: 2px;
width: 100%;
height: 4px;
left: 0;
transition: all 0.2s ease;
opacity: 0;
}
.fullcalendar :deep(.fc-event-resizer-start) {
top: -2px;
cursor: n-resize;
}
.fullcalendar :deep(.fc-event-resizer-end) {
bottom: -2px;
cursor: s-resize;
}
.fullcalendar :deep(.fc-event:hover .fc-event-resizer) {
opacity: 1;
}
.fullcalendar :deep(.fc-event-resizer:hover) {
background: '#FFF';
height: 6px;
}
/* Update the earlier hover rule to include the shadow */
.fullcalendar :deep(.fc-event:hover) {
opacity: 1;
transition: all 0.2s ease;
box-shadow: var(--theme-shadow-dropdown);
}
.fullcalendar :deep(.fc-timegrid-event-harness) {
margin: 0 1px;
}
.fullcalendar :deep(.fc-highlight) {
background-color: var(--theme-color-default-background);
}
.fullcalendar :deep(.fc-select-mirror) {
background-color: var(--accent);
border: 1px solid var(--primary);
}
.fullcalendar :deep(.fc-scrollgrid) {
border: 1px solid var(--border);
border-left: 1px solid transparent;
}
.fullcalendar :deep(.fc-scrollgrid-section > td) {
border-right: 1px solid var(--border);
}
.fullcalendar :deep(.fc-timegrid-body) {
background-color: var(--theme-color-default-background);
}
.fullcalendar :deep(.fc-timegrid-col) {
border-right: 1px solid var(--border);
}
.fullcalendar :deep(.fc-timegrid-axis-cushion) {
color: var(--theme-text-secondary);
font-size: 0.75rem;
font-weight: 500;
}
.fullcalendar :deep(.fc-timegrid-slot-label-cushion) {
font-size: 0.8125rem;
color: var(--muted-foreground);
}
.fullcalendar :deep(.fc-col-header-cell-cushion) {
color: var(--foreground);
font-size: 0.875rem;
font-weight: 600;
}
/* Daily totals styling */
.fullcalendar :deep(.fc-col-header-cell .text-muted-foreground) {
color: var(--muted-foreground);
margin-top: 0.125rem;
}
/* Reduce visibility of time slot dividers */
.fullcalendar :deep(.fc-timegrid-divider) {
display: none;
}
/* Make scrollbars gray */
.fullcalendar :deep(.fc-scroller) {
scrollbar-width: thin;
scrollbar-color: var(--muted-foreground) transparent;
}
.fullcalendar :deep(.fc-scroller::-webkit-scrollbar) {
width: 8px;
}
.fullcalendar :deep(.fc-scroller::-webkit-scrollbar-track) {
background: transparent;
}
.fullcalendar :deep(.fc-scroller::-webkit-scrollbar-thumb) {
background-color: var(--muted-foreground);
border-radius: 4px;
}
.fullcalendar :deep(.fc-scroller::-webkit-scrollbar-thumb:hover) {
background-color: var(--foreground);
}
/* Improve time axis styling */
.fullcalendar :deep(.fc-timegrid-axis-chunk) {
background-color: var(--theme-color-default-background);
}
/* Simple event main styling */
.fullcalendar :deep(.fc-event-main) {
padding: 0.125rem 0.25rem;
}
</style>

View File

@@ -33,6 +33,7 @@ const props = defineProps<{
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
onStartStopClick: (timeEntry: TimeEntry) => void;
duplicateTimeEntry: (timeEntry: TimeEntry) => void;
updateTimeEntries: (ids: string[], changes: Partial<TimeEntry>) => void;
updateTimeEntry: (timeEntry: TimeEntry) => void;
deleteTimeEntries: (timeEntries: TimeEntry[]) => void;
@@ -92,7 +93,7 @@ function onSelectChange(checked: boolean) {
class="border-b border-default-background-separator bg-row-background min-w-0 transition"
data-testid="time_entry_row">
<MainContainer class="min-w-0">
<div class="sm:flex py-1.5 items-center min-w-0 justify-between group">
<div class="sm:flex py-2 items-center min-w-0 justify-between group">
<div class="flex space-x-3 items-center min-w-0">
<Checkbox
:checked="
@@ -172,6 +173,8 @@ function onSelectChange(checked: boolean) {
class="opacity-20 flex group-hover:opacity-100 focus-visible:opacity-100"
@changed="onStartStopClick(timeEntry)"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
:show-edit="false"
:show-duplicate="false"
@delete="
deleteTimeEntries(timeEntry?.timeEntries ?? [])
"></TimeEntryMoreOptionsDropdown>
@@ -201,6 +204,7 @@ function onSelectChange(checked: boolean) {
:update-time-entry="(timeEntry: TimeEntry) => updateTimeEntry(timeEntry)"
:on-start-stop-click="() => onStartStopClick(subEntry)"
:delete-time-entry="() => deleteTimeEntries([subEntry])"
:duplicate-time-entry="() => duplicateTimeEntry(subEntry)"
:currency="currency"
:create-tag
:time-entry="subEntry"

View File

@@ -41,6 +41,8 @@ const props = defineProps<{
projects: Project[];
tasks: Task[];
clients: Client[];
start?: string;
end?: string;
}>();
const description = ref<HTMLInputElement | null>(null);
@@ -63,7 +65,27 @@ const timeEntryDefaultValues = {
end: getDayJsInstance().utc().format(),
};
const timeEntry = ref({ ...timeEntryDefaultValues });
const timeEntry = ref({
...timeEntryDefaultValues,
});
// update the localStart and localEnd when props.start or props.end get updates
watch(
() => props.start,
(value) => {
if (value) {
localStart.value = getLocalizedDayJs(value).format();
}
}
);
watch(
() => props.end,
(value) => {
if (value) {
localEnd.value = getLocalizedDayJs(value).format();
}
}
);
watch(
() => timeEntry.value.project_id,

View File

@@ -0,0 +1,311 @@
<script setup lang="ts">
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { computed, nextTick, ref, watch } from 'vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import InputLabel from '@/packages/ui/src/Input/InputLabel.vue';
import { TagIcon } from '@heroicons/vue/20/solid';
import { getLocalizedDayJs } from '@/packages/ui/src/utils/time';
import type {
CreateClientBody,
CreateProjectBody,
Project,
Client,
TimeEntry,
} from '@/packages/api/src';
import { getOrganizationCurrencyString } from '@/utils/money';
import { canCreateProjects } from '@/utils/permissions';
import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
import { Badge } from '@/packages/ui/src';
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
import SelectDropdown from '@/packages/ui/src/Input/SelectDropdown.vue';
import DatePicker from '@/packages/ui/src/Input/DatePicker.vue';
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
import type { Tag, Task } from '@/packages/api/src';
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
const show = defineModel('show', { default: false });
const saving = ref(false);
const deleting = ref(false);
const props = defineProps<{
timeEntry: TimeEntry | null;
enableEstimatedTime: boolean;
updateTimeEntry: (entry: TimeEntry) => Promise<void>;
deleteTimeEntry: (timeEntryId: string) => Promise<void>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createTag: (name: string) => Promise<Tag | undefined>;
tags: Tag[];
projects: Project[];
tasks: Task[];
clients: Client[];
}>();
const description = ref<HTMLInputElement | null>(null);
watch(show, (value) => {
if (value) {
nextTick(() => {
description.value?.focus();
});
}
});
const editableTimeEntry = ref<TimeEntry | null>(null);
watch(
() => props.timeEntry,
(newTimeEntry) => {
if (newTimeEntry) {
editableTimeEntry.value = { ...newTimeEntry };
}
},
{ immediate: true }
);
watch(
() => editableTimeEntry.value?.project_id,
(value) => {
if (value && editableTimeEntry.value) {
// check if project is billable by default and set billable accordingly
const project = props.projects.find((p) => p.id === value);
if (project) {
editableTimeEntry.value.billable = project.is_billable;
}
}
}
);
const localStart = computed({
get: () =>
editableTimeEntry.value ? getLocalizedDayJs(editableTimeEntry.value.start).format() : '',
set: (value: string) => {
if (editableTimeEntry.value) {
editableTimeEntry.value.start = getLocalizedDayJs(value).utc().format();
if (getLocalizedDayJs(localEnd.value).isBefore(getLocalizedDayJs(value))) {
localEnd.value = value;
}
}
},
});
const localEnd = computed({
get: () =>
editableTimeEntry.value ? getLocalizedDayJs(editableTimeEntry.value.end).format() : '',
set: (value: string) => {
if (editableTimeEntry.value) {
editableTimeEntry.value.end = getLocalizedDayJs(value).utc().format();
}
},
});
async function submit() {
if (editableTimeEntry.value) {
saving.value = true;
try {
await props.updateTimeEntry(editableTimeEntry.value);
show.value = false;
} finally {
saving.value = false;
}
}
}
async function deleteEntry() {
if (editableTimeEntry.value) {
deleting.value = true;
try {
await props.deleteTimeEntry(editableTimeEntry.value.id);
show.value = false;
} finally {
deleting.value = false;
}
}
}
const billableProxy = computed({
get: () =>
editableTimeEntry.value ? (editableTimeEntry.value.billable ? 'true' : 'false') : 'false',
set: (value: string) => {
if (editableTimeEntry.value) {
editableTimeEntry.value.billable = value === 'true';
}
},
});
type BillableOption = {
label: string;
value: string;
};
</script>
<template>
<DialogModal closeable :show="show" @close="show = false">
<template #title>
<div class="flex space-x-2">
<span> Edit time entry </span>
</div>
</template>
<template #content>
<div v-if="editableTimeEntry" class="space-y-4">
<div class="sm:flex items-end space-y-2 sm:space-y-0 sm:space-x-4">
<div class="flex-1">
<TextInput
id="description"
ref="description"
v-model="editableTimeEntry.description"
placeholder="What did you work on?"
type="text"
class="mt-1 block w-full"
@keydown.enter="submit" />
</div>
</div>
<div
class="sm:flex justify-between items-end space-y-2 sm:space-y-0 pt-4 sm:space-x-4">
<div class="flex w-full items-center space-x-2 justify-between">
<div class="flex-1 min-w-0">
<TimeTrackerProjectTaskDropdown
v-model:project="editableTimeEntry.project_id"
v-model:task="editableTimeEntry.task_id"
:clients
:create-project
:create-client
:can-create-project="canCreateProjects()"
:currency="getOrganizationCurrencyString()"
size="xlarge"
class="bg-input-background"
:projects="projects"
:tasks="tasks"
:enable-estimated-time="
enableEstimatedTime
"></TimeTrackerProjectTaskDropdown>
</div>
<div class="flex items-center space-x-2">
<div class="flex-col">
<TagDropdown
v-model="editableTimeEntry.tags"
:create-tag
:tags="tags">
<template #trigger>
<Badge
class="bg-input-background"
tag="button"
size="xlarge">
<TagIcon
v-if="editableTimeEntry.tags.length === 0"
class="w-4"></TagIcon>
<div
v-else
class="bg-accent-300/20 w-5 h-5 font-medium rounded flex items-center transition justify-center">
{{ editableTimeEntry.tags.length }}
</div>
<span>Tags</span>
</Badge>
</template>
</TagDropdown>
</div>
<div class="flex-col">
<SelectDropdown
v-model="billableProxy"
:get-key-from-item="(item: BillableOption) => item.value"
:get-name-for-item="(item: BillableOption) => item.label"
:items="[
{
label: 'Billable',
value: 'true',
},
{
label: 'Non Billable',
value: 'false',
},
]">
<template #trigger>
<Badge
class="bg-input-background"
tag="button"
size="xlarge">
<BillableIcon class="h-4"></BillableIcon>
<span>{{
editableTimeEntry.billable
? 'Billable'
: 'Non-Billable'
}}</span>
</Badge>
</template>
</SelectDropdown>
</div>
</div>
</div>
</div>
<div class="flex pt-4 space-x-4">
<div class="flex-1">
<InputLabel>Duration</InputLabel>
<div class="space-y-2 mt-1 flex flex-col">
<DurationHumanInput
v-model:start="localStart"
v-model:end="localEnd"
name="Duration"></DurationHumanInput>
<div class="text-sm flex space-x-1">
<InformationCircleIcon
class="w-4 text-text-quaternary"></InformationCircleIcon>
<span class="text-text-secondary text-xs">
You can type natural language here f.e.
<span class="font-semibold"> 2h 30m</span>
</span>
</div>
</div>
</div>
<div class="">
<InputLabel>Start</InputLabel>
<div class="flex flex-col items-center space-y-2 mt-1">
<TimePickerSimple v-model="localStart" size="large"></TimePickerSimple>
<DatePicker
v-model="localStart"
tabindex="1"
class="text-xs text-text-tertiary max-w-28 px-1.5 py-1.5"></DatePicker>
</div>
</div>
<div class="">
<InputLabel>End</InputLabel>
<div class="flex flex-col items-center space-y-2 mt-1">
<TimePickerSimple v-model="localEnd" size="large"></TimePickerSimple>
<DatePicker
v-model="localEnd"
tabindex="1"
class="text-xs text-text-tertiary max-w-28 px-1.5 py-1.5"></DatePicker>
</div>
</div>
</div>
</div>
</template>
<template #footer>
<div class="flex justify-between w-full">
<SecondaryButton
tabindex="2"
class="bg-red-600 hover:bg-red-700 text-white border-red-600 hover:border-red-700"
:disabled="deleting || saving"
@click="deleteEntry">
{{ deleting ? 'Deleting...' : 'Delete' }}
</SecondaryButton>
<div class="flex space-x-3">
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>
<PrimaryButton
tabindex="2"
:class="{ 'opacity-25': saving }"
:disabled="saving || deleting"
@click="submit">
{{ saving ? 'Updating...' : 'Update Time Entry' }}
</PrimaryButton>
</div>
</div>
</template>
</DialogModal>
</template>
<style scoped></style>

View File

@@ -108,6 +108,7 @@ function startTimeEntryFromExisting(entry: TimeEntry) {
tags: [...entry.tags],
});
}
function sumDuration(timeEntries: TimeEntry[]) {
return timeEntries.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
}
@@ -158,6 +159,7 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
:tags="tags"
:clients
:on-start-stop-click="startTimeEntryFromExisting"
:duplicate-time-entry="createTimeEntry"
:update-time-entries
:update-time-entry
:delete-time-entries
@@ -198,6 +200,7 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
:update-time-entry
:on-start-stop-click="() => startTimeEntryFromExisting(entry)"
:delete-time-entry="() => deleteTimeEntries([entry])"
:duplicate-time-entry="() => createTimeEntry(entry)"
:currency="currency"
:time-entry="entry.timeEntries[0]"
@selected="selectedTimeEntries.push(entry)"

View File

@@ -63,7 +63,7 @@ const showMassUpdateModal = ref(false);
:class="
twMerge(
props.class,
'text-sm py-1.5 font-medium border-t border-b bg-secondary border-border-secondary flex items-center space-x-3'
'text-sm py-1.5 font-medium bg-secondary flex items-center space-x-3'
)
">
<Checkbox

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import { TrashIcon } from '@heroicons/vue/20/solid';
import { TrashIcon, PencilIcon, DocumentDuplicateIcon } from '@heroicons/vue/20/solid';
import {
DropdownMenu,
DropdownMenuContent,
@@ -7,8 +7,21 @@ import {
DropdownMenuTrigger,
} from '@/Components/ui/dropdown-menu';
const props = withDefaults(
defineProps<{
showEdit?: boolean;
showDuplicate?: boolean;
}>(),
{
showDuplicate: true,
showEdit: true,
}
);
const emit = defineEmits<{
edit: [];
delete: [];
duplicate: [];
}>();
</script>
@@ -33,6 +46,22 @@ const emit = defineEmits<{
</button>
</DropdownMenuTrigger>
<DropdownMenuContent class="min-w-[150px]" align="end">
<DropdownMenuItem
v-if="props.showEdit"
data-testid="time_entry_edit"
class="flex items-center space-x-3 cursor-pointer"
@click="emit('edit')">
<PencilIcon class="w-5" />
<span>Edit</span>
</DropdownMenuItem>
<DropdownMenuItem
v-if="props.showDuplicate"
data-testid="time_entry_duplicate"
class="flex items-center space-x-3 cursor-pointer"
@click="emit('duplicate')">
<DocumentDuplicateIcon class="w-5" />
<span>Duplicate</span>
</DropdownMenuItem>
<DropdownMenuItem
data-testid="time_entry_delete"
class="flex items-center space-x-3 cursor-pointer text-destructive focus:text-destructive"

View File

@@ -16,8 +16,9 @@ import TimeEntryDescriptionInput from '@/packages/ui/src/TimeEntry/TimeEntryDesc
import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTagDropdown.vue';
import TimeEntryRowDurationInput from '@/packages/ui/src/TimeEntry/TimeEntryRowDurationInput.vue';
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
import { TimeEntryEditModal } from '@/packages/ui/src';
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
import { computed } from 'vue';
import { computed, ref } from 'vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import { Checkbox } from '@/packages/ui/src';
import { twMerge } from 'tailwind-merge';
@@ -35,6 +36,7 @@ const props = defineProps<{
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
onStartStopClick: () => void;
deleteTimeEntry: () => void;
duplicateTimeEntry?: () => void;
updateTimeEntry: (timeEntry: TimeEntry) => void;
currency: string;
showMember?: boolean;
@@ -46,6 +48,8 @@ const props = defineProps<{
const emit = defineEmits<{ selected: []; unselected: [] }>();
const showEditModal = ref(false);
function updateTimeEntryDescription(description: string) {
props.updateTimeEntry({ ...props.timeEntry, description });
}
@@ -87,6 +91,20 @@ function onSelectChange(checked: boolean) {
emit('unselected');
}
}
function handleEdit() {
showEditModal.value = true;
}
async function handleUpdateTimeEntry(updatedEntry: TimeEntry) {
props.updateTimeEntry(updatedEntry);
showEditModal.value = false;
}
async function handleDeleteTimeEntry() {
props.deleteTimeEntry();
showEditModal.value = false;
}
</script>
<template>
@@ -148,11 +166,27 @@ function onSelectChange(checked: boolean) {
class="opacity-20 flex focus-visible:opacity-100 group-hover:opacity-100"
@changed="onStartStopClick"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
@edit="handleEdit"
@duplicate="duplicateTimeEntry"
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
</div>
</div>
</MainContainer>
</div>
<TimeEntryEditModal
v-model:show="showEditModal"
:time-entry="timeEntry"
:enable-estimated-time="enableEstimatedTime"
:update-time-entry="handleUpdateTimeEntry"
:delete-time-entry="handleDeleteTimeEntry"
:create-client="createClient"
:create-project="createProject"
:create-tag="createTag"
:tags="tags"
:projects="projects"
:tasks="tasks"
:clients="clients" />
</template>
<style scoped></style>

View File

@@ -27,7 +27,11 @@ import Checkbox from './Input/Checkbox.vue';
import TimeEntryGroupedTable from './TimeEntry/TimeEntryGroupedTable.vue';
import TimeEntryMassActionRow from './TimeEntry/TimeEntryMassActionRow.vue';
import TimeEntryCreateModal from './TimeEntry/TimeEntryCreateModal.vue';
import TimeEntryEditModal from './TimeEntry/TimeEntryEditModal.vue';
import MoreOptionsDropdown from './MoreOptionsDropdown.vue';
import FullCalendarEventContent from './FullCalendar/FullCalendarEventContent.vue';
import FullCalendarDayHeader from './FullCalendar/FullCalendarDayHeader.vue';
import TimeEntryCalendar from './FullCalendar/TimeEntryCalendar.vue';
export {
money,
@@ -52,4 +56,8 @@ export {
TimeEntryMassActionRow,
MoreOptionsDropdown,
TimeEntryCreateModal,
TimeEntryEditModal,
FullCalendarEventContent,
FullCalendarDayHeader,
TimeEntryCalendar,
};

View File

@@ -0,0 +1,9 @@
export function openFeedback(): void {
if (
typeof window !== 'undefined' &&
'showChatWindow' in window &&
typeof window.showChatWindow === 'function'
) {
window.showChatWindow();
}
}

View File

@@ -12,11 +12,19 @@ import { useProjectsStore } from '@/utils/useProjects';
import { useMembersStore } from '@/utils/useMembers';
import { useTasksStore } from '@/utils/useTasks';
import { useClientsStore } from '@/utils/useClients';
import { useTagsStore } from '@/utils/useTags';
import { CheckCircleIcon, UserCircleIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
import { DocumentTextIcon, FolderIcon } from '@heroicons/vue/16/solid';
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
export type GroupingOption = 'project' | 'task' | 'user' | 'billable' | 'client' | 'description';
export type GroupingOption =
| 'project'
| 'task'
| 'user'
| 'billable'
| 'client'
| 'description'
| 'tag';
export const useReportingStore = defineStore('reporting', () => {
const reportingGraphResponse = ref<ReportingResponse | null>(null);
@@ -73,6 +81,7 @@ export const useReportingStore = defineStore('reporting', () => {
billable: 'Non-Billable',
client: 'No Client',
description: 'No Description',
tag: 'No Tag',
} as Record<string, string>;
function getNameForReportingRowEntry(key: string | null, type: string | null) {
@@ -106,6 +115,11 @@ export const useReportingStore = defineStore('reporting', () => {
const { clients } = storeToRefs(clientsStore);
return clients.value.find((client) => client.id === key)?.name;
}
if (type === 'tag') {
const tagsStore = useTagsStore();
const { tags } = storeToRefs(tagsStore);
return tags.value.find((tag) => tag.id === key)?.name;
}
if (type === 'billable') {
if (key === '0') {
return 'Non-Billable';
@@ -151,6 +165,11 @@ export const useReportingStore = defineStore('reporting', () => {
value: 'description',
icon: DocumentTextIcon,
},
{
label: 'Tags',
value: 'tag',
icon: DocumentTextIcon,
},
];
return {

View File

@@ -36,6 +36,10 @@ Route::middleware([
return Inertia::render('Time');
})->name('time');
Route::get('/calendar', function () {
return Inertia::render('Calendar');
})->name('calendar');
Route::get('/reporting', function () {
return Inertia::render('Reporting');
})->name('reporting');

View File

@@ -34,6 +34,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
'clients:view:all',
]);
$clients = Client::factory()->forOrganization($data->organization)->randomCreatedAt()->createMany(4);
Passport::actingAs($data->user);
@@ -57,11 +58,43 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
);
}
public function test_index_endpoint_returns_list_of_clients_assigned_to_employee_user(): void
{
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
]);
$clients = Client::factory()->forOrganization($data->organization)->createMany(2);
$projectWithMembership1 = Project::factory()->forOrganization($data->organization)->forClient($clients->get(0))->addMember($data->member)->isPrivate()->create();
$projectWithMembership2 = Project::factory()->forOrganization($data->organization)->forClient($clients->get(1))->addMember($data->member)->isPrivate()->create();
$otherClients = Client::factory()->forOrganization($data->organization)->createMany(2);
$projectWithoutMembership = Project::factory()->forOrganization($data->organization)->forClient($otherClients->get(0))->isPrivate()->create();
Passport::actingAs($data->user);
// Act
$response = $this->getJson(route('api.v1.clients.index', [$data->organization->getKey()]));
// Assert
$response->assertStatus(200);
$response->assertJsonCount(2, 'data');
$response->assertJson(fn (AssertableJson $json) => $json
->has('data')
->has('links')
->has('meta')
->count('data', 2)
->where('data.0.id', $clients->get(0)->getKey())
->where('data.1.id', $clients->get(1)->getKey())
);
}
public function test_index_endpoint_without_filter_archived_returns_only_non_archived_clients(): void
{
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
'clients:view:all',
]);
$archivedClients = Client::factory()->forOrganization($data->organization)->archived()->createMany(2);
$nonArchivedClients = Client::factory()->forOrganization($data->organization)->createMany(2);
@@ -81,6 +114,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
'clients:view:all',
]);
$archivedClients = Client::factory()->forOrganization($data->organization)->archived()->createMany(2);
$nonArchivedClients = Client::factory()->forOrganization($data->organization)->createMany(2);
@@ -103,6 +137,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
'clients:view:all',
]);
$archivedClients = Client::factory()->forOrganization($data->organization)->archived()->createMany(2);
$nonArchivedClients = Client::factory()->forOrganization($data->organization)->createMany(2);
@@ -125,6 +160,7 @@ class ClientEndpointTest extends ApiEndpointTestAbstract
// Arrange
$data = $this->createUserWithPermission([
'clients:view',
'clients:view:all',
]);
$archivedClients = Client::factory()->forOrganization($data->organization)->archived()->createMany(2);
$nonArchivedClients = Client::factory()->forOrganization($data->organization)->createMany(2);

View File

@@ -3393,6 +3393,241 @@ class TimeEntryEndpointTest extends ApiEndpointTestAbstract
]);
}
public function test_store_endpoint_blocks_overlapping_entries_when_start_overlaps(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 13, 0, 0, 'UTC');
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $baseStart->copy()->addMinutes(30)->toIso8601ZuluString(),
'end' => $baseEnd->copy()->addMinutes(30)->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_store_endpoint_blocks_overlapping_entries_when_end_overlaps(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 13, 0, 0, 'UTC');
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $baseStart->copy()->subMinutes(30)->toIso8601ZuluString(),
'end' => $baseStart->copy()->addMinutes(30)->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_store_endpoint_blocks_overlapping_entries_when_new_entry_is_within_existing(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 13, 0, 0, 'UTC');
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $baseStart->copy()->addMinutes(15)->toIso8601ZuluString(),
'end' => $baseStart->copy()->addMinutes(45)->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_store_endpoint_blocks_overlapping_entries_when_new_entry_surrounds_existing(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 13, 0, 0, 'UTC');
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $baseStart->copy()->subMinutes(30)->toIso8601ZuluString(),
'end' => $baseEnd->copy()->addMinutes(30)->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_store_endpoint_blocks_starting_active_entry_when_it_overlaps_with_existing(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 13, 0, 0, 'UTC');
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $baseStart->copy()->addMinutes(30)->toIso8601ZuluString(),
'end' => null,
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_store_endpoint_allows_future_time_entries_even_with_running_now(): void
{
// Arrange
$now = Carbon::create(2025, 1, 1, 12, 0, 0, 'UTC');
$this->travelTo($now);
$data = $this->createUserWithPermission([
'time-entries:create:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $now->copy()->subHour(),
'end' => null,
]);
Passport::actingAs($data->user);
// Act
$response = $this->postJson(route('api.v1.time-entries.store', [$data->organization->getKey()]), [
'member_id' => $data->member->getKey(),
'billable' => true,
'start' => $now->copy()->addDay()->toIso8601ZuluString(),
'end' => $now->copy()->addDay()->addHour()->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(201);
}
public function test_update_endpoint_blocks_overlap_and_excludes_current_entry(): void
{
// Arrange
$data = $this->createUserWithPermission([
'time-entries:update:own',
]);
$data->organization->prevent_overlapping_time_entries = true;
$data->organization->save();
$baseStart = Carbon::create(2025, 1, 1, 14, 0, 0, 'UTC');
$baseEnd = Carbon::create(2025, 1, 1, 15, 0, 0, 'UTC');
$base = TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseStart,
'end' => $baseEnd,
]);
$toUpdate = TimeEntry::factory()->forOrganization($data->organization)->forMember($data->member)
->create([
'start' => $baseEnd->copy()->addMinutes(30),
'end' => $baseEnd->copy()->addHour(),
]);
Passport::actingAs($data->user);
// Act
$response = $this->putJson(route('api.v1.time-entries.update', [$data->organization->getKey(), $toUpdate->getKey()]), [
'start' => $baseStart->copy()->addMinutes(30)->toIso8601ZuluString(),
]);
// Assert
$response->assertStatus(400);
$response->assertExactJson([
'error' => true,
'key' => 'overlapping_time_entry',
'message' => 'Overlapping time entries are not allowed.',
]);
}
public function test_update_multiple_refreshes_billable_rate_on_updates_time_entries(): void
{
// Arrange

View File

@@ -9,6 +9,7 @@ use App\Enums\TimeEntryRoundingType;
use App\Enums\Weekday;
use App\Models\Client;
use App\Models\Project;
use App\Models\Tag;
use App\Models\TimeEntry;
use App\Service\TimeEntryAggregationService;
use Illuminate\Support\Carbon;
@@ -1007,4 +1008,201 @@ class TimeEntryAggregationServiceTest extends TestCaseWithDatabase
],
], $result);
}
public function test_aggregate_time_entries_group_by_tag_includes_no_tag_and_avoids_double_counting_overall(): void
{
// Arrange
$tag1 = Tag::factory()->create();
$tag2 = Tag::factory()->create();
$start = Carbon::now();
// One entry with two tags (100s)
TimeEntry::factory()->startWithDuration($start, 100)->create([
'tags' => [$tag1->getKey(), $tag2->getKey()],
]);
// One entry with one tag (50s)
TimeEntry::factory()->startWithDuration($start, 50)->create([
'tags' => [$tag1->getKey()],
]);
// One entry with no tags (25s)
TimeEntry::factory()->startWithDuration($start, 25)->create([
'tags' => [],
]);
$query = TimeEntry::query();
// Act
$result = $this->service->getAggregatedTimeEntries(
$query,
TimeEntryAggregationType::Tag,
null,
'Europe/Vienna',
Weekday::Monday,
false,
null,
null,
true,
null,
null
);
// Assert - overall total should be 175 and groups: null=25, tag1=150, tag2=100
$expected = [
'seconds' => 175,
'cost' => 0,
'grouped_type' => 'tag',
'grouped_data' => [
[
'key' => null,
'seconds' => 25,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
[
'key' => $tag1->getKey(),
'seconds' => 150,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
[
'key' => $tag2->getKey(),
'seconds' => 100,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
],
];
$this->assertEqualsCanonicalizing($expected, $result);
}
public function test_aggregate_time_entries_group_by_project_and_subgroup_tag(): void
{
// Arrange
$project = Project::factory()->create();
$tag1 = Tag::factory()->create();
$tag2 = Tag::factory()->create();
$start = Carbon::now();
TimeEntry::factory()->startWithDuration($start, 120)->forProject($project)->create([
'tags' => [$tag1->getKey()],
]);
TimeEntry::factory()->startWithDuration($start, 60)->forProject($project)->create([
'tags' => [$tag2->getKey()],
]);
$query = TimeEntry::query();
// Act
$result = $this->service->getAggregatedTimeEntries(
$query,
TimeEntryAggregationType::Project,
TimeEntryAggregationType::Tag,
'Europe/Vienna',
Weekday::Monday,
false,
null,
null,
true,
null,
null
);
// Assert
$expected = [
'seconds' => 180,
'cost' => 0,
'grouped_type' => 'project',
'grouped_data' => [
[
'key' => $project->getKey(),
'seconds' => 180,
'cost' => 0,
'grouped_type' => 'tag',
'grouped_data' => [
[
'key' => $tag1->getKey(),
'seconds' => 120,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
[
'key' => $tag2->getKey(),
'seconds' => 60,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
],
],
],
];
$this->assertEqualsCanonicalizing($expected, $result);
}
public function test_aggregate_time_entries_group_by_project_and_subgroup_tag_avoids_double_counting(): void
{
// Arrange
$project = Project::factory()->create();
$tag1 = Tag::factory()->create();
$tag2 = Tag::factory()->create();
$start = Carbon::now();
// One entry with two tags => subgroup rows show both tags, but project total should equal entry duration
TimeEntry::factory()->startWithDuration($start, 100)->forProject($project)->create([
'tags' => [$tag1->getKey(), $tag2->getKey()],
]);
$query = TimeEntry::query();
// Act
$result = $this->service->getAggregatedTimeEntries(
$query,
TimeEntryAggregationType::Project,
TimeEntryAggregationType::Tag,
'Europe/Vienna',
Weekday::Monday,
false,
null,
null,
true,
null,
null
);
// Assert
$expected = [
'seconds' => 100,
'cost' => 0,
'grouped_type' => 'project',
'grouped_data' => [
[
'key' => $project->getKey(),
'seconds' => 100,
'cost' => 0,
'grouped_type' => 'tag',
'grouped_data' => [
[
'key' => $tag1->getKey(),
'seconds' => 100,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
[
'key' => $tag2->getKey(),
'seconds' => 100,
'cost' => 0,
'grouped_type' => null,
'grouped_data' => null,
],
],
],
],
];
$this->assertEqualsCanonicalizing($expected, $result);
}
}