add break time entries and simplified time tracker ui

This commit is contained in:
Gregor Vostrak
2026-07-21 16:48:37 +02:00
parent 114a32536d
commit cbcd1e51f6
128 changed files with 6252 additions and 437 deletions

View File

@@ -1,7 +1,8 @@
<script setup lang="ts">
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import { CheckCircleIcon, TagIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
import { FolderIcon } from '@heroicons/vue/16/solid';
import { Check } from '@lucide/vue';
import { Check, Coffee } from '@lucide/vue';
import { RadioGroupIndicator, RadioGroupItem, RadioGroupRoot, type AcceptableValue } from 'reka-ui';
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
import ReportingRoundingControls from '@/Components/Common/Reporting/ReportingRoundingControls.vue';
@@ -27,6 +28,7 @@ const selectedClients = defineModel<string[]>('selectedClients', { required: tru
const selectedTags = defineModel<string[]>('selectedTags', { required: true });
const tagMatchType = defineModel<TagMatchType>('tagMatchType', { required: true });
const billable = defineModel<'true' | 'false' | null>('billable', { required: true });
const entryType = defineModel<'work' | 'break' | null>('entryType', { required: true });
const roundingEnabled = defineModel<boolean>('roundingEnabled', { required: true });
const roundingType = defineModel<TimeEntryRoundingType>('roundingType', { required: true });
const roundingMinutes = defineModel<number>('roundingMinutes', { required: true });
@@ -37,6 +39,8 @@ const emit = defineEmits<{
submit: [];
}>();
const breaksEnabled = useBreaksEnabled();
const { tags } = useTagsQuery();
const tagMatchOptions: { value: TagMatchType; label: string }[] = [
@@ -162,6 +166,38 @@ async function createTag(name: string) {
<SelectItem value="false">Non Billable</SelectItem>
</SelectContent>
</Select>
<Select
v-if="breaksEnabled"
v-model="entryType"
@update:model-value="emit('submit')">
<SelectTrigger
size="sm"
variant="outline"
:active="entryType !== null"
:show-chevron="false">
<SelectValue class="flex items-center gap-2">
<Coffee
class="h-4 w-4"
:class="
entryType !== null
? 'dark:text-accent-300/80 text-accent-400/80'
: 'text-text-quaternary'
" />
<span class="text-text-secondary">{{
entryType === null
? 'Type'
: entryType === 'break'
? 'Breaks'
: 'Work time'
}}</span>
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem :value="null">Both</SelectItem>
<SelectItem value="work">Work time</SelectItem>
<SelectItem value="break">Breaks</SelectItem>
</SelectContent>
</Select>
<ReportingRoundingControls
v-model:enabled="roundingEnabled"
v-model:type="roundingType"

View File

@@ -71,6 +71,7 @@ const selectedClients = ref<string[]>([]);
const tagMatchType = ref<TagMatchType>('contains');
const billable = ref<'true' | 'false' | null>(null);
const entryType = ref<'work' | 'break' | null>('work');
const roundingEnabled = ref<boolean>(false);
const roundingType = ref<TimeEntryRoundingType>('nearest');
const roundingMinutes = ref<number>(15);
@@ -126,6 +127,7 @@ const filterParams = computed<AggregatedTimeEntriesQueryParams>(() => {
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
billable: billable.value !== null ? billable.value : undefined,
type: entryType.value !== null ? entryType.value : undefined,
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
@@ -160,7 +162,7 @@ const aggregatedTableTimeEntries = computed<AggregatedTimeEntries | undefined>((
});
const reportProperties = computed(() => {
const { billable: billableFilter, ...rest } = filterParams.value;
const { billable: billableFilter, type: typeFilter, ...rest } = filterParams.value;
let billableValue: boolean | null = null;
if (billableFilter === 'true') {
@@ -172,6 +174,7 @@ const reportProperties = computed(() => {
return {
...rest,
billable: billableValue,
time_entry_type: typeFilter ?? null,
group: group.value,
sub_group: subGroup.value,
history_group: getOptimalGroupingOption(startDate.value, endDate.value),
@@ -371,6 +374,7 @@ const tableData = computed(() => {
v-model:selected-tags="selectedTags"
v-model:tag-match-type="tagMatchType"
v-model:billable="billable"
v-model:entry-type="entryType"
v-model:rounding-enabled="roundingEnabled"
v-model:rounding-type="roundingType"
v-model:rounding-minutes="roundingMinutes"

View File

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

View File

@@ -62,6 +62,8 @@ const queryParams = computed<AggregatedTimeEntriesQueryParams>(() => {
group: group.value,
sub_group: subGroup.value,
member_id: getCurrentRole() === 'employee' ? getCurrentMembershipId() : undefined,
// Breaks are excluded from all dashboard stats (see DashboardService workTime())
type: 'work',
};
});

View File

@@ -4,13 +4,13 @@ import CardTitle from '@/packages/ui/src/CardTitle.vue';
import { usePage } from '@inertiajs/vue3';
import { type User } from '@/types/models';
import { computed, onMounted, watch } from 'vue';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import duration from 'dayjs/plugin/duration';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import { useCurrentTimeEntryStore } from '@/utils/useCurrentTimeEntry';
import { getLastWorkTimeEntry, useCurrentTimeEntryStore } from '@/utils/useCurrentTimeEntry';
import { storeToRefs } from 'pinia';
import { getCurrentOrganizationId } from '@/utils/useUser';
import { useLocalStorage } from '@vueuse/core';
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
import { switchOrganization } from '@/utils/useOrganization';
import { useProjectsQuery } from '@/utils/useProjectsQuery';
@@ -20,6 +20,7 @@ import { useClientsQuery } from '@/utils/useClientsQuery';
import { useTagsStore } from '@/utils/useTags';
import { useProjectsStore } from '@/utils/useProjects';
import TimeTrackerControls from '@/packages/ui/src/TimeTracker/TimeTrackerControls.vue';
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
import type {
CreateClientBody,
CreateProjectBody,
@@ -44,15 +45,15 @@ const page = usePage<{
user: User;
};
}>();
dayjs.extend(duration);
dayjs.extend(utc);
const dayjs = getDayJsInstance();
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const breaksEnabled = useBreaksEnabled(organization);
const currentTimeEntryStore = useCurrentTimeEntryStore();
const { currentTimeEntry, isActive, now } = storeToRefs(currentTimeEntryStore);
const { startLiveTimer, stopLiveTimer, setActiveState } = currentTimeEntryStore;
const { currentTimeEntry, isActive, isOnBreak, now } = storeToRefs(currentTimeEntryStore);
const { startLiveTimer, stopLiveTimer, setActiveState, startBreak, resumeWorkAfterBreak } =
currentTimeEntryStore;
const { projects } = useProjectsQuery();
const { tasks } = useTasksQuery();
@@ -67,6 +68,8 @@ const showManualTimeEntryModal = ref(false);
const { createTimeEntry: createTimeEntryMutation, deleteTimeEntry } = useTimeEntriesMutations();
const { data: timeEntriesData } = useTimeEntriesInfiniteQuery();
const timeEntries = computed(() => timeEntriesData.value?.pages.flatMap((page) => page.data) || []);
const lastWorkTimeEntry = computed(() => getLastWorkTimeEntry(timeEntries.value));
const canResumeAfterBreak = computed(() => lastWorkTimeEntry.value !== null);
watch(isActive, () => {
if (isActive.value) {
@@ -123,6 +126,14 @@ async function createTimeEntry(timeEntry: Omit<CreateTimeEntryBody, 'member_id'>
showManualTimeEntryModal.value = false;
}
async function resumePreviousWorkAfterBreak() {
const timeEntry = lastWorkTimeEntry.value;
if (!timeEntry) {
return;
}
await resumeWorkAfterBreak(timeEntry);
}
async function createTimeEntryFromCurrentEntry() {
const { start, end, description, project_id, task_id, billable, tags } = currentTimeEntry.value;
await createTimeEntry({ start, end, description, project_id, task_id, billable, tags });
@@ -142,6 +153,16 @@ async function discardCurrentTimeEntry() {
}
}
// Time tracker UI mode is a per-device UI preference, stored client-side and keyed by organization
const timeTrackerMode = useLocalStorage<TimeTrackerMode>(
`solidtime/time-tracker-mode/${getCurrentOrganizationId()}`,
'project'
);
function toggleTimeTrackerMode() {
timeTrackerMode.value = timeTrackerMode.value === 'simple' ? 'project' : 'simple';
}
const { tags } = useTagsQuery();
</script>
@@ -186,17 +207,29 @@ const { tags } = useTagsQuery();
:time-entries
:create-tag
:is-active
:is-on-break="isOnBreak"
:breaks-enabled="breaksEnabled"
:can-resume-after-break="canResumeAfterBreak"
:resume-description="lastWorkTimeEntry?.description ?? null"
:time-tracker-mode="timeTrackerMode"
:currency="getOrganizationCurrencyString()"
@start-live-timer="startLiveTimer"
@stop-live-timer="stopLiveTimer"
@start-timer="setActiveState(true)"
@stop-timer="setActiveState(false)"
@start-break="startBreak"
@resume-after-break="resumePreviousWorkAfterBreak"
@update-time-entry="updateTimeEntry"
@create-time-entry="createTimeEntryFromCurrentEntry"></TimeTrackerControls>
</div>
<TimeTrackerMoreOptionsDropdown
:has-active-timer="isActive"
:time-tracker-mode="timeTrackerMode"
:is-on-break="isOnBreak"
:breaks-enabled="breaksEnabled"
@manual-entry="showManualTimeEntryModal = true"
@start-break="startBreak"
@toggle-time-tracker-mode="toggleTimeTrackerMode"
@discard="discardCurrentTimeEntry"></TimeTrackerMoreOptionsDropdown>
</div>
</div>

View File

@@ -0,0 +1,225 @@
<script setup lang="ts">
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
import { formatTime, getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
import { Coffee } from '@lucide/vue';
import { computed, inject, ref, watch, type ComputedRef } from 'vue';
import type { Organization } from '@/packages/api/src';
import {
BREAK_GAP_TOLERANCE_SECONDS,
placementMode,
planMoveInsert,
planSplitEntry,
type BreakPlacementRequest,
} from '@/utils/timesheet/breakPlacementMath';
import { BREAK_GAP_TOLERANCE_MINUTES } from '@/packages/ui/src/utils/breakPlacement';
const props = defineProps<{
request: BreakPlacementRequest | null;
apply: (breakStart: string, durationSeconds: number) => Promise<void>;
}>();
const emit = defineEmits<{ cancel: [] }>();
const organization = inject<ComputedRef<Organization>>('organization');
const show = computed(() => props.request !== null);
const mode = computed(() => (props.request ? placementMode(props.request) : null));
const saving = ref(false);
const localStart = ref('');
const localEnd = ref('');
// Seed the pickers from the suggested placement whenever a new request arrives.
watch(
() => props.request,
(request) => {
if (!request) return;
localStart.value = getLocalizedDayJs(request.defaultBreakStart).format();
localEnd.value = getLocalizedDayJs(request.defaultBreakStart)
.add(request.durationSeconds, 'second')
.format();
},
{ immediate: true }
);
const utcStart = computed(() => getLocalizedDayJs(localStart.value).utc().format());
const durationSeconds = computed(() =>
getLocalizedDayJs(localEnd.value)
.utc()
.diff(getLocalizedDayJs(localStart.value).utc(), 'second')
);
const splitPlan = computed(() => {
if (!props.request || mode.value !== 'split' || durationSeconds.value <= 0) return null;
return planSplitEntry(props.request.workEntries[0]!, durationSeconds.value, utcStart.value);
});
const movePlan = computed(() => {
if (!props.request || mode.value !== 'move' || durationSeconds.value <= 0) return null;
return planMoveInsert(
[...props.request.workEntries, ...props.request.otherEntries],
props.request.dayStart,
props.request.dayEnd,
utcStart.value,
durationSeconds.value
);
});
// Non-blocking heads-up: the placement is feasible but the break would end up
// further than the tolerance from work on either side, so it would carry the
// misaligned warning right after being created. Mirrors getBreakPlacementHint,
// but computed against the planned (post-shift) layout.
const resultMisaligned = computed<boolean>(() => {
const req = props.request;
const plan = movePlan.value;
if (!req || mode.value !== 'move' || !plan) return false;
const dayjs = getDayJsInstance();
const toMs = (iso: string) => dayjs.utc(iso).valueOf();
const breakStartMs = toMs(plan.breakSlot.start);
const breakEndMs = toMs(plan.breakSlot.end);
const shiftedById = new Map(plan.shifted.map((s) => [s.id, s]));
let prevWorkEndMs: number | null = null;
let nextWorkStartMs: number | null = null;
for (const entry of req.workEntries) {
const planned = shiftedById.get(entry.id) ?? entry;
const startMs = toMs(planned.start);
const endMs = toMs(planned.end);
if (endMs <= breakStartMs && (prevWorkEndMs === null || endMs > prevWorkEndMs)) {
prevWorkEndMs = endMs;
}
if (startMs >= breakEndMs && (nextWorkStartMs === null || startMs < nextWorkStartMs)) {
nextWorkStartMs = startMs;
}
}
const toleranceMs = BREAK_GAP_TOLERANCE_SECONDS * 1000;
return (
prevWorkEndMs === null ||
breakStartMs - prevWorkEndMs > toleranceMs ||
nextWorkStartMs === null ||
nextWorkStartMs - breakEndMs > toleranceMs
);
});
const feasible = computed(() =>
mode.value === 'split' ? splitPlan.value !== null : movePlan.value !== null
);
function fmt(iso: string): string {
return formatTime(iso, organization?.value?.time_format);
}
const explanation = computed(() => {
if (!props.request) return '';
return mode.value === 'split'
? "There's no free gap that fits this break, so the work entry will be split and the break placed inside it."
: "There's no free gap that fits this break, so the surrounding entries will be shifted to make room.";
});
// Human-readable summary of what will change, so the user can confirm the edit.
const changeSummary = computed<string[]>(() => {
if (mode.value === 'split') {
const plan = splitPlan.value;
if (!plan) return [];
return [
`${fmt(plan.firstHalf.start)}${fmt(plan.firstHalf.end)} (work)`,
`${fmt(plan.breakSlot.start)}${fmt(plan.breakSlot.end)} (break)`,
`${fmt(plan.secondHalf.start)}${fmt(plan.secondHalf.end)} (work)`,
];
}
const plan = movePlan.value;
if (!plan) return [];
if (plan.shifted.length === 0) return ['No entries need to move.'];
return plan.shifted.map((shift) => {
const isBreak = props.request!.otherEntries.some((e) => e.id === shift.id);
const original =
props.request!.workEntries.find((e) => e.id === shift.id) ??
props.request!.otherEntries.find((e) => e.id === shift.id)!;
const label = `${fmt(original.start)}${fmt(original.end)}${fmt(shift.start)}${fmt(shift.end)}`;
return isBreak ? `${label} (break)` : label;
});
});
async function submit() {
if (!feasible.value || durationSeconds.value <= 0) return;
saving.value = true;
try {
await props.apply(utcStart.value, durationSeconds.value);
} catch {
// apply surfaces its own error toast; keep the modal open so the user can retry
} finally {
saving.value = false;
}
}
</script>
<template>
<DialogModal closeable :show="show" @close="emit('cancel')">
<template #title>
<div class="flex items-center space-x-2">
<Coffee class="w-5 h-5 text-text-secondary" />
<span>Add break</span>
</div>
</template>
<template #content>
<div class="space-y-4">
<p class="text-sm text-text-secondary">{{ explanation }}</p>
<TimeRangeFields
v-model:start="localStart"
v-model:end="localEnd"
date-picker-size="sm"></TimeRangeFields>
<div
v-if="feasible"
data-testid="break_placement_summary"
class="rounded-lg border border-card-border bg-secondary/40 px-3 py-2 text-sm text-text-secondary space-y-1">
<div class="text-xs uppercase tracking-wide text-text-tertiary">
{{ mode === 'split' ? 'Result' : 'Entries that move' }}
</div>
<div v-for="(line, index) in changeSummary" :key="index" class="tabular-nums">
{{ line }}
</div>
</div>
<div
v-if="feasible && resultMisaligned"
data-testid="break_placement_misaligned_warning"
class="rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-700 dark:text-yellow-400">
At this time the break would sit more than
{{ BREAK_GAP_TOLERANCE_MINUTES }} minutes away from your work entries and will
be flagged as misaligned.
</div>
<!-- `request` guard (not just !feasible): when the request is cleared on save,
the dialog fades out with content still mounted don't flash the error then -->
<div
v-if="!feasible && request"
data-testid="break_placement_infeasible"
class="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
{{
mode === 'split'
? "This break doesn't fit there it must lie inside the work entry, leaving at least a minute of work on each side."
: "This break doesn't fit at that time without pushing an entry outside the day. Try a shorter break or a different time."
}}
</div>
</div>
</template>
<template #footer>
<SecondaryButton @click="emit('cancel')">Cancel</SecondaryButton>
<PrimaryButton
class="ms-3"
:class="{ 'opacity-25': saving || !feasible }"
:disabled="saving || !feasible"
@click="submit">
Add break
</PrimaryButton>
</template>
</DialogModal>
</template>
<style scoped></style>

View File

@@ -93,4 +93,26 @@ describe('TimesheetCell', () => {
expect((wrapper.get('input').element as HTMLInputElement).disabled).toBe(true);
});
it('renders read-only and emits nothing when the row is read-only', async () => {
const wrapper = mount(TimesheetCell, {
props: {
cell: buildCell(2 * 3600),
dayIndex: 0,
date: '2026-04-13',
isToday: false,
hasRunningEntry: false,
readonly: true,
},
});
const input = wrapper.get('input');
expect((input.element as HTMLInputElement).disabled).toBe(true);
await input.trigger('focus');
await input.setValue('4h');
await input.trigger('blur');
expect(wrapper.emitted('update')).toBeUndefined();
});
});

View File

@@ -18,6 +18,7 @@ const props = defineProps<{
date: string;
isToday: boolean;
hasRunningEntry: boolean;
readonly?: boolean;
saveStatus?: CellSaveStatus;
pendingSeconds?: number;
}>();
@@ -30,6 +31,16 @@ const emit = defineEmits<{
const displaySeconds = computed(() => props.pendingSeconds ?? props.cell?.totalSeconds ?? 0);
const isSaving = computed(() => props.saveStatus === 'saving');
// A cell is non-editable while its entry is running or when the row itself is
// read-only (e.g. a leftover break row after breaks were disabled). Both render
// the same disabled input, differing only in the tooltip explanation.
const isReadonly = computed(() => props.hasRunningEntry || props.readonly === true);
const readonlyTooltip = computed(() =>
props.hasRunningEntry
? 'Stop the running time entry to edit the timesheet'
: 'Breaks are disabled for this organization'
);
// Swap the border color (don't layer) to avoid same-specificity fights.
const inputClass = computed(() => {
const border = props.saveStatus === 'error' ? 'border-red-500/70' : 'border-input-border';
@@ -51,7 +62,7 @@ const inputClass = computed(() => {
data-testid="timesheet_cell"
class="flex items-center justify-center border-t border-default-background-separator"
:class="{ 'bg-default-background': isToday }">
<TooltipProvider v-if="hasRunningEntry" :delay-duration="100">
<TooltipProvider v-if="isReadonly" :delay-duration="100">
<Tooltip>
<TooltipTrigger as-child>
<span class="inline-block cursor-not-allowed">
@@ -68,7 +79,7 @@ const inputClass = computed(() => {
disabled:opacity-50 disabled:cursor-not-allowed" />
</span>
</TooltipTrigger>
<TooltipContent> Stop the running time entry to edit the timesheet </TooltipContent>
<TooltipContent>{{ readonlyTooltip }}</TooltipContent>
</Tooltip>
</TooltipProvider>
<template v-else>

View File

@@ -2,6 +2,9 @@
import { inject, type ComputedRef } from 'vue';
import { Button } from '@/packages/ui/src/Buttons';
import { PlusIcon } from '@heroicons/vue/20/solid';
import { ExclamationTriangleIcon, ArrowRightIcon } from '@heroicons/vue/16/solid';
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/packages/ui/src';
import { Link } from '@inertiajs/vue3';
import TimesheetRow from '@/Components/Timesheet/TimesheetRow.vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
@@ -26,6 +29,8 @@ defineProps<{
todayDate: string;
dayTotals: number[];
weekTotalFormatted: string;
breakDayTotals: number[];
breakGrandTotal: number;
projects: Project[];
tasks: Task[];
clients: Client[];
@@ -39,6 +44,7 @@ defineProps<{
formatDuration: (seconds: number) => string;
cellStatuses: Record<string, CellSaveStatus>;
cellPendingSeconds: Record<string, number>;
misplacedBreakDates?: Set<string>;
}>();
const emit = defineEmits<{
@@ -74,9 +80,34 @@ const emit = defineEmits<{
<div
v-for="day in weekDays"
:key="day"
data-testid="timesheet_day_header"
class="bg-background dark:bg-secondary px-2 py-1 text-center">
<div class="text-xs font-medium text-text-secondary">
{{ dayjs(day).format('ddd D') }}
<div
class="flex items-center justify-center gap-1 text-xs font-medium text-text-secondary">
<span>{{ dayjs(day).format('ddd D') }}</span>
<DropdownMenu v-if="misplacedBreakDates?.has(day)">
<DropdownMenuTrigger as-child>
<button
type="button"
title="A break on this day does not align with your work entries"
class="flex items-center justify-center shrink-0 rounded-full p-0.5 text-amber-500 hover:bg-amber-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<ExclamationTriangleIcon class="w-3.5 h-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent class="min-w-[240px]" align="start">
<div class="px-3 py-2 space-y-1.5">
<p class="text-xs text-text-secondary">
A break on this day is not directly between work entries.
</p>
<Link
:href="`/calendar?date=${day}`"
class="inline-flex items-center gap-1 text-sm font-medium text-accent-400 hover:underline">
Fix in calendar
<ArrowRightIcon class="w-3.5 h-3.5" />
</Link>
</div>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div
@@ -85,7 +116,7 @@ const emit = defineEmits<{
</div>
<div class="bg-background dark:bg-secondary"></div>
<!-- Data rows -->
<!-- Data rows (break row is pinned last) -->
<TimesheetRow
v-for="row in rows"
:key="row.key"
@@ -140,9 +171,9 @@ const emit = defineEmits<{
</TimeTrackerProjectTaskDropdown>
</div>
<!-- Totals row -->
<!-- Totals row: worked time, with break time annotated below (calendar-style) -->
<div
class="border-t border-default-background-separator bg-background dark:bg-secondary pl-7 pr-3 py-1 text-xs text-text-tertiary md:sticky md:left-0 md:z-10">
class="flex items-center border-t border-default-background-separator bg-background dark:bg-secondary pl-7 pr-3 py-1 text-xs text-text-tertiary md:sticky md:left-0 md:z-10">
Total
</div>
<div
@@ -150,18 +181,24 @@ const emit = defineEmits<{
:key="dayIndex"
data-testid="timesheet_day_total"
:class="[
'flex items-center justify-center border-t border-default-background-separator bg-background dark:bg-secondary px-2 py-1 text-xs font-medium',
'flex flex-col items-center justify-center border-t border-default-background-separator bg-background dark:bg-secondary px-2 py-1 text-xs font-medium leading-tight',
weekDays[dayIndex] === todayDate
? 'text-text-primary'
: 'text-text-secondary',
]">
<span class="w-[80px] text-center">
{{ total > 0 ? formatDuration(total) : '-' }}
<span>{{ total > 0 ? formatDuration(total) : '-' }}</span>
<span
v-if="(breakDayTotals[dayIndex] ?? 0) > 0"
class="font-normal text-text-tertiary">
+{{ formatDuration(breakDayTotals[dayIndex] ?? 0) }} break
</span>
</div>
<div
class="flex items-center justify-end border-t border-default-background-separator bg-background dark:bg-secondary pl-3 pr-3 py-1 text-xs font-semibold text-text-primary">
{{ weekTotalFormatted }}
class="flex flex-col items-end justify-center border-t border-default-background-separator bg-background dark:bg-secondary pl-3 pr-3 py-1 text-xs font-semibold text-text-primary leading-tight">
<span>{{ weekTotalFormatted }}</span>
<span v-if="breakGrandTotal > 0" class="font-normal text-text-tertiary">
+{{ formatDuration(breakGrandTotal) }} break
</span>
</div>
<div
class="border-t border-default-background-separator bg-background dark:bg-secondary"></div>

View File

@@ -1,6 +1,8 @@
<script setup lang="ts">
import { computed, inject, type ComputedRef } from 'vue';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import { XMarkIcon } from '@heroicons/vue/16/solid';
import { Coffee } from '@lucide/vue';
import TimesheetCell from './TimesheetCell.vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTagDropdown.vue';
@@ -22,6 +24,7 @@ import {
import { Button } from '@/packages/ui/src/Buttons';
const organization = inject<ComputedRef<Organization>>('organization');
const breaksEnabled = useBreaksEnabled();
const props = defineProps<{
row: TimesheetRow;
@@ -62,6 +65,11 @@ const selectedTask = computed({
const rowTotalFormatted = computed(() => props.formatDuration(props.row.totalSeconds));
// A break row can survive after breaks are disabled (its entries are
// grandfathered). Those cells become read-only — creating/editing break time is
// rejected server-side — leaving the remove button as the only action.
const cellsReadonly = computed(() => props.row.type === 'break' && !breaksEnabled.value);
function hasRunningEntry(dayIndex: number): boolean {
const cell = props.row.cells.get(dayIndex);
if (!cell) return false;
@@ -74,7 +82,13 @@ function hasRunningEntry(dayIndex: number): boolean {
<!-- Project/Task column -->
<div
class="flex items-center gap-1 border-t border-default-background-separator bg-default-background pl-4 pr-3 py-2 md:sticky md:left-0 md:z-10">
<div class="flex-1 min-w-0">
<div
v-if="row.type === 'break'"
class="flex flex-1 items-center gap-1.5 min-w-0 px-2 py-1 text-sm text-text-secondary">
<Coffee class="w-4 h-4" />
<span>Break</span>
</div>
<div v-else class="flex-1 min-w-0">
<TimeTrackerProjectTaskDropdown
v-model:project="selectedProject"
v-model:task="selectedTask"
@@ -94,11 +108,13 @@ function hasRunningEntry(dayIndex: number): boolean {
</div>
<div class="flex items-center gap-1 flex-shrink-0 ml-auto">
<TimeEntryRowTagDropdown
v-if="row.type !== 'break'"
:create-tag="createTag"
:tags="tags"
:model-value="row.tags"
@changed="emit('tagsChange', $event)" />
<BillableToggleButton
v-if="row.type !== 'break'"
:model-value="row.billable"
size="small"
faded
@@ -115,6 +131,7 @@ function hasRunningEntry(dayIndex: number): boolean {
:date="day"
:is-today="day === todayDate"
:has-running-entry="hasRunningEntry(dayIndex)"
:readonly="cellsReadonly"
:save-status="cellStatuses[makeCellStatusKey(row.key, dayIndex)]"
:pending-seconds="cellPendingSeconds[makeCellStatusKey(row.key, dayIndex)]"
@update="(seconds) => emit('cellUpdate', dayIndex, seconds)" />
@@ -126,10 +143,11 @@ function hasRunningEntry(dayIndex: number): boolean {
{{ rowTotalFormatted }}
</div>
<!-- Remove action -->
<!-- Remove action (the break row is permanent while breaks are enabled) -->
<div
class="flex items-center justify-center border-t border-default-background-separator pr-4 py-3">
<Button
v-if="!(row.type === 'break' && breaksEnabled)"
variant="ghost"
size="icon"
aria-label="Remove row"

View File

@@ -31,6 +31,9 @@ const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const calendarStart = ref<Dayjs | undefined>(undefined);
const calendarEnd = ref<Dayjs | undefined>(undefined);
// Optional deep link (e.g. "Fix in calendar") that opens the calendar on a specific day
const initialDate = new URLSearchParams(window.location.search).get('date');
// Test-injectable activity periods (for E2E testing).
// These hooks are no-ops in production — they only take effect when test code
// explicitly sets window globals, so they are safe to ship.
@@ -128,6 +131,7 @@ function onRefresh() {
:enable-estimated-time="isAllowedToPerformPremiumAction()"
:currency="getOrganizationCurrencyString()"
:can-create-project="canCreateProjects()"
:initial-date="initialDate"
:organization-billable-rate="organization?.billable_rate ?? null"
:create-time-entry="createTimeEntry"
:update-time-entry="updateTimeEntry"

View File

@@ -74,6 +74,7 @@ const selectedTasks = ref<string[]>([]);
const selectedClients = ref<string[]>([]);
const tagMatchType = ref<TagMatchType>('contains');
const billable = ref<'true' | 'false' | null>(null);
const entryType = ref<'work' | 'break' | null>('work');
const roundingEnabled = ref<boolean>(false);
const roundingType = ref<TimeEntryRoundingType>('nearest');
const roundingMinutes = ref<number>(15);
@@ -106,6 +107,7 @@ function getFilterAttributes() {
tag_ids: selectedTags.value.length > 0 ? selectedTags.value : undefined,
tag_match_type: selectedTags.value.length > 0 ? tagMatchType.value : undefined,
billable: billable.value !== null ? billable.value : undefined,
type: entryType.value !== null ? entryType.value : undefined,
rounding_type: roundingEnabled.value ? roundingType.value : undefined,
rounding_minutes: roundingEnabled.value ? roundingMinutes.value : undefined,
};
@@ -329,6 +331,7 @@ async function downloadExport(format: ExportFormat) {
v-model:selected-tags="selectedTags"
v-model:tag-match-type="tagMatchType"
v-model:billable="billable"
v-model:entry-type="entryType"
v-model:rounding-enabled="roundingEnabled"
v-model:rounding-type="roundingType"
v-model:rounding-minutes="roundingMinutes"

View File

@@ -17,15 +17,18 @@ const queryClient = useQueryClient();
const form = ref<{
prevent_overlapping_time_entries: boolean;
employees_can_manage_tasks: boolean;
breaks_enabled: boolean;
}>({
prevent_overlapping_time_entries: false,
employees_can_manage_tasks: false,
breaks_enabled: false,
});
onMounted(async () => {
form.value.prevent_overlapping_time_entries =
organization.value?.prevent_overlapping_time_entries ?? false;
form.value.employees_can_manage_tasks = organization.value?.employees_can_manage_tasks ?? false;
form.value.breaks_enabled = organization.value?.breaks_enabled ?? false;
});
const mutation = useMutation({
@@ -39,6 +42,7 @@ async function submit() {
await mutation.mutateAsync({
prevent_overlapping_time_entries: form.value.prevent_overlapping_time_entries,
employees_can_manage_tasks: form.value.employees_can_manage_tasks,
breaks_enabled: form.value.breaks_enabled,
});
}
</script>
@@ -69,6 +73,10 @@ async function submit() {
>Allow Employees to manage tasks</FieldLabel
>
</Field>
<Field orientation="horizontal">
<Checkbox id="breaksEnabled" v-model:checked="form.breaks_enabled" />
<FieldLabel for="breaksEnabled">Allow tracking breaks</FieldLabel>
</Field>
</div>
</template>

View File

@@ -1,6 +1,7 @@
<script setup lang="ts">
import AppLayout from '@/Layouts/AppLayout.vue';
import TimeTracker from '@/Components/TimeTracker.vue';
import { router } from '@inertiajs/vue3';
import { computed, ref, watch } from 'vue';
import MainContainer from '@/packages/ui/src/MainContainer.vue';
import { storeToRefs } from 'pinia';
@@ -102,6 +103,11 @@ function deleteSelected() {
deleteTimeEntries(selectedTimeEntries.value);
selectedTimeEntries.value = [];
}
// SPA-navigate the calendar to a break's day so its placement can be fixed there.
function goToCalendarDay(date: string) {
router.visit(`/calendar?date=${date}`);
}
</script>
<template>
@@ -153,6 +159,7 @@ function deleteSelected() {
:currency="getOrganizationCurrencyString()"
:time-entries="timeEntries"
:group-similar-time-entries="groupSimilarTimeEntriesSetting"
:fix-in-calendar="goToCalendarDay"
:tags="tags"></TimeEntryGroupedTable>
<div v-if="isPending" class="flex justify-center items-center py-12">
<LoadingSpinner></LoadingSpinner>

View File

@@ -1,12 +1,14 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import AppLayout from '@/Layouts/AppLayout.vue';
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
import TimesheetHeader from '@/Components/Timesheet/TimesheetHeader.vue';
import TimesheetGrid from '@/Components/Timesheet/TimesheetGrid.vue';
import TimesheetFooterActions from '@/Components/Timesheet/TimesheetFooterActions.vue';
import RemoveRowDialog from '@/Components/Timesheet/RemoveRowDialog.vue';
import BreakPlacementModal from '@/Components/Timesheet/BreakPlacementModal.vue';
import { useTimesheetQuery } from '@/utils/useTimesheetQuery';
import { useTimesheetGrid } from '@/utils/useTimesheetGrid';
import { useTimeEntriesMutations } from '@/utils/useTimeEntriesMutations';
@@ -22,7 +24,12 @@ import { getCurrentOrganizationId } from '@/utils/useUser';
import { getOrganizationCurrencyString } from '@/utils/money';
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
import { canCreateProjects } from '@/utils/permissions';
import { formatHumanReadableDuration } from '@/packages/ui/src/utils/time';
import {
formatHumanReadableDuration,
getLocalizedDateFromTimestamp,
getLocalizedDayJs,
} from '@/packages/ui/src/utils/time';
import { getBreakPlacementHint } from '@/packages/ui/src/utils/breakPlacement';
import { useTimesheetWeek } from '@/utils/timesheet/useTimesheetWeek';
import { useTimesheetCellMutations } from '@/utils/timesheet/useTimesheetCellMutations';
import { useTimesheetRowMutations } from '@/utils/timesheet/useTimesheetRowMutations';
@@ -45,8 +52,17 @@ const {
} = useTimesheetWeek();
// ── Data fetching ─────────────────────────────────────────────────
// The query fetches one padding day on each side of the week so that entries
// crossing midnight at the week edges are known to the break-placement solver.
const { data, isPending } = useTimesheetQuery(weekStart, weekEnd);
const timeEntries = computed(() => data.value?.data ?? []);
const allTimeEntries = computed(() => data.value?.data ?? []);
// The grid and week-scoped features only see entries starting in the visible week.
const timeEntries = computed(() => {
const weekDaySet = new Set(weekDays.value);
return allTimeEntries.value.filter((entry) =>
weekDaySet.has(getLocalizedDateFromTimestamp(entry.start))
);
});
const { projects } = useProjectsQuery();
const { tasks } = useTasksQuery();
@@ -56,19 +72,31 @@ const { now: currentTimerNow } = storeToRefs(useCurrentTimeEntryStore());
const mutations = useTimeEntriesMutations();
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const breaksEnabled = useBreaksEnabled(organization);
// ── Grid computation ──────────────────────────────────────────────
const { rows, dayTotals, grandTotal, addSlot, removeSlot, updateSlot, clearSlots } =
useTimesheetGrid(timeEntries, weekDays, projects, tasks, currentTimerNow);
const {
rows,
dayTotals,
grandTotal,
breakDayTotals,
breakGrandTotal,
addSlot,
removeSlot,
updateSlot,
clearSlots,
} = useTimesheetGrid(timeEntries, weekDays, projects, tasks, currentTimerNow, breaksEnabled);
// Wipe slots on week navigation so the new week starts fresh — the
// grid's watcher will reseed from the newly fetched entries.
watch(weekStart, () => clearSlots());
// flush: 'sync' so the wipe happens the moment weekStart is assigned, BEFORE
// the same flush recomputes `timeEntries` (it depends on weekDays) and lets
// the grid seed the new week — otherwise a cached (prefetched) week seeds
// first, gets wiped here, and nothing re-triggers the seeding afterwards.
watch(weekStart, () => clearSlots(), { flush: 'sync' });
// ── Formatters ────────────────────────────────────────────────────
// Pull number/interval format off the org via its query rather than
// inject('organization'), which is undefined during the page's setup
// (AppLayout provides it later in the lifecycle).
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
const intervalFormat = computed(() => organization.value?.interval_format ?? 'hours-minutes');
const numberFormat = computed(() => organization.value?.number_format ?? 'point');
@@ -90,12 +118,28 @@ const weekRangeDisplay = computed(() => {
});
// ── Cell / row mutation handlers ──────────────────────────────────
const { handleCellUpdate, cellStatus, cellPendingSeconds } = useTimesheetCellMutations(
weekDays,
timeEntries,
rows,
removeSlot
);
const {
handleCellUpdate,
cellStatus,
cellPendingSeconds,
breakPlacementRequest,
applyBreakPlacement,
dismissBreakPlacement,
} = useTimesheetCellMutations(weekDays, allTimeEntries, rows, removeSlot);
// Local dates (YYYY-MM-DD) that have a misplaced break. There is only one break
// row, so a flat set is enough — its cells show a warning for dates in the set.
const misplacedBreakDates = computed<Set<string>>(() => {
const dates = new Set<string>();
for (const entry of timeEntries.value) {
if (entry.type !== 'break') continue;
// Hint against the padded list so work just across midnight counts.
if (getBreakPlacementHint(entry, allTimeEntries.value)?.misplaced) {
dates.add(getLocalizedDayJs(entry.start).format('YYYY-MM-DD'));
}
}
return dates;
});
const { handleRowIdentityChange, handleAddRow } = useTimesheetRowMutations(
mutations,
@@ -125,7 +169,8 @@ const { isCopyingLastWeek, copyLastWeekRows, copyLastWeekWithTime } = useCopyLas
weekDays,
rows,
timeEntries,
addSlot
addSlot,
breaksEnabled
);
// ── Inline creation helpers (passed to TimesheetRow) ──────────────
@@ -161,6 +206,8 @@ async function createTag(name: string): Promise<Tag | undefined> {
:today-date="todayDate"
:day-totals="dayTotals"
:week-total-formatted="weekTotalFormatted"
:break-day-totals="breakDayTotals"
:break-grand-total="breakGrandTotal"
:projects="projects"
:tasks="tasks"
:clients="clients"
@@ -174,6 +221,7 @@ async function createTag(name: string): Promise<Tag | undefined> {
:format-duration="formatDuration"
:cell-statuses="cellStatus"
:cell-pending-seconds="cellPendingSeconds"
:misplaced-break-dates="misplacedBreakDates"
@remove-row="handleRemoveRow"
@cell-update="handleCellUpdate"
@project-task-change="
@@ -199,5 +247,10 @@ async function createTag(name: string): Promise<Tag | undefined> {
:entry-count="deleteRowEntryCount"
:project-name="deleteRowProjectName"
@confirm="confirmDeleteRow" />
<BreakPlacementModal
:request="breakPlacementRequest"
:apply="applyBreakPlacement"
@cancel="dismissBreakPlacement" />
</AppLayout>
</template>

View File

@@ -16,6 +16,7 @@ export type Invitation = InvitationsIndexResponse['data'][0];
export type TimeEntryResponse = ZodiosResponseByAlias<SolidTimeApi, 'getTimeEntries'>;
export type TimeEntry = TimeEntryResponse['data'][0];
export type TimeEntryType = TimeEntry['type'];
export type CreateTimeEntryBody = ZodiosBodyByAlias<SolidTimeApi, 'createTimeEntry'>;

View File

@@ -319,6 +319,7 @@ const OrganizationResource = z
employees_can_see_billable_rates: z.boolean(),
employees_can_manage_tasks: z.boolean(),
prevent_overlapping_time_entries: z.boolean(),
breaks_enabled: z.boolean(),
currency: z.string(),
currency_symbol: z.string(),
number_format: NumberFormat,
@@ -336,6 +337,7 @@ const OrganizationUpdateRequest = z
employees_can_see_billable_rates: z.boolean(),
employees_can_manage_tasks: z.boolean(),
prevent_overlapping_time_entries: z.boolean(),
breaks_enabled: z.boolean(),
number_format: NumberFormat,
currency_format: CurrencyFormat,
date_format: DateFormat,
@@ -420,6 +422,7 @@ const TimeEntryAggregationType = z.enum([
'billable',
'description',
'tag',
'type',
]);
const TimeEntryAggregationTypeInterval = z.enum(['day', 'week', 'month', 'year']);
const Weekday = z.enum([
@@ -479,6 +482,7 @@ const DetailedReportResource = z
active: z.union([z.boolean(), z.null()]),
member_ids: z.union([z.array(z.string()), z.null()]),
billable: z.union([z.boolean(), z.null()]),
time_entry_type: z.union([z.enum(['work', 'break']), z.null()]),
client_ids: z.union([z.array(z.string()), z.null()]),
project_ids: z.union([z.array(z.string()), z.null()]),
tag_ids: z.union([z.array(z.string()), z.null()]),
@@ -631,6 +635,7 @@ const TaskUpdateRequest = z
.passthrough();
const start = z.union([z.string(), z.null()]).optional();
const rounding_minutes = z.union([z.number(), z.null()]).optional();
const TimeEntryType = z.enum(['work', 'break']);
const TimeEntryResource = z
.object({
id: z.string(),
@@ -644,6 +649,7 @@ const TimeEntryResource = z
user_id: z.string(),
tags: z.array(z.string()),
billable: z.boolean(),
type: TimeEntryType,
})
.passthrough();
const TimeEntryStoreRequest = z
@@ -654,6 +660,7 @@ const TimeEntryStoreRequest = z
start: z.string(),
end: z.union([z.string(), z.null()]).optional(),
billable: z.boolean(),
type: TimeEntryType.optional(),
description: z.union([z.string(), z.null()]).optional(),
tags: z.union([z.array(z.string()), z.null()]).optional(),
})
@@ -667,6 +674,7 @@ const TimeEntryUpdateMultipleRequest = z
project_id: z.union([z.string(), z.null()]),
task_id: z.union([z.string(), z.null()]),
billable: z.boolean(),
type: TimeEntryType,
description: z.union([z.string(), z.null()]),
tags: z.union([z.array(z.string()), z.null()]),
})
@@ -682,6 +690,7 @@ const TimeEntryUpdateRequest = z
start: z.string(),
end: z.union([z.string(), z.null()]),
billable: z.boolean(),
type: TimeEntryType,
description: z.union([z.string(), z.null()]),
tags: z.union([z.array(z.string()), z.null()]),
})
@@ -774,6 +783,7 @@ export const schemas = {
TaskUpdateRequest,
start,
rounding_minutes,
TimeEntryType,
TimeEntryResource,
TimeEntryStoreRequest,
TimeEntryUpdateMultipleRequest,
@@ -3736,6 +3746,11 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
type: 'Query',
schema: z.enum(['true', 'false']).optional(),
},
{
name: 'type',
type: 'Query',
schema: TimeEntryType.optional(),
},
{
name: 'limit',
type: 'Query',
@@ -3895,7 +3910,9 @@ Users with the permission &#x60;time-entries:view:own&#x60; can only use this en
schema: z.string(),
},
],
response: z.object({ success: z.string(), error: z.string() }).passthrough(),
response: z
.object({ success: z.array(z.string()), error: z.array(z.string()) })
.passthrough(),
errors: [
{
status: 401,
@@ -4085,6 +4102,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'billable',
'description',
'tag',
'type',
])
.optional(),
},
@@ -4104,6 +4122,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'billable',
'description',
'tag',
'type',
])
.optional(),
},
@@ -4137,6 +4156,11 @@ 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: 'type',
type: 'Query',
schema: TimeEntryType.optional(),
},
{
name: 'fill_gaps_in_time_groups',
type: 'Query',
@@ -4277,6 +4301,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'billable',
'description',
'tag',
'type',
]),
},
{
@@ -4294,6 +4319,7 @@ If the group parameters are all set to &#x60;null&#x60; or are all missing, the
'billable',
'description',
'tag',
'type',
]),
},
{
@@ -4331,6 +4357,11 @@ 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: 'type',
type: 'Query',
schema: TimeEntryType.optional(),
},
{
name: 'fill_gaps_in_time_groups',
type: 'Query',
@@ -4459,6 +4490,11 @@ 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: 'type',
type: 'Query',
schema: TimeEntryType.optional(),
},
{
name: 'limit',
type: 'Query',

View File

@@ -9,7 +9,7 @@ export const buttonVariants = cva(
variant: {
default: 'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 dark:bg-destructive/70',
outline:
'border shadow-xs hover:text-text-primary bg-card-background dark:bg-transparent border-input dark:border-input hover:bg-white/5',
secondary: 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',

View File

@@ -94,6 +94,7 @@ const emit = defineEmits<{
getEventOpacityClass(dayEvent, dayStr),
{
'running-entry rounded-b-none': dayEvent.event.isRunning,
'fc-event-break': dayEvent.event.isBreak,
'fc-event-dragging': isDragging && dragEventId === dayEvent.event.id,
'fc-event-resizing': resizeEventId === dayEvent.event.id,
'rounded-t-none': dayEvent.isClippedStart,
@@ -121,6 +122,8 @@ const emit = defineEmits<{
:project-name="dayEvent.event.project?.name"
:task-name="dayEvent.event.task?.name"
:client-name="dayEvent.event.client?.name"
:is-break="dayEvent.event.isBreak"
:is-misplaced-break="dayEvent.event.isMisplacedBreak"
:duration-seconds="getEventDurationSeconds(dayEvent, dayStr)" />
</div>
<div
@@ -413,4 +416,15 @@ const emit = defineEmits<{
.fc-events-inset-expanded {
left: 204px;
}
/* Breaks get a hatched texture so they can not be confused with a project color */
.fc-event-break {
background-image: repeating-linear-gradient(
-45deg,
transparent,
transparent 5px,
rgba(217, 119, 6, 0.15) 5px,
rgba(217, 119, 6, 0.15) 7px
);
}
</style>

View File

@@ -7,10 +7,12 @@ import type { Dayjs } from 'dayjs';
const props = defineProps<{
date: Dayjs;
totalSeconds?: number;
breakSeconds?: number;
isToday?: boolean;
}>();
const totalSecondsValue = computed(() => props.totalSeconds ?? 0);
const breakSecondsValue = computed(() => props.breakSeconds ?? 0);
const organization = inject('organization') as ComputedRef<Organization | undefined> | undefined;
const intervalFormat = computed(() => organization?.value?.interval_format);
@@ -24,6 +26,10 @@ const numberFormat = computed(() => organization?.value?.number_format);
</div>
<span class="block text-xs text-muted-foreground font-medium mt-0.5">
{{ formatHumanReadableDuration(totalSecondsValue, intervalFormat, numberFormat) }}
<template v-if="breakSecondsValue > 0">
· {{ formatHumanReadableDuration(breakSecondsValue, intervalFormat, numberFormat) }}
break
</template>
</span>
</div>
</template>

View File

@@ -2,6 +2,8 @@
import { computed, inject, type ComputedRef } from 'vue';
import { formatHumanReadableDuration, getDayJsInstance } from '../utils/time';
import type { Organization } from '@/packages/api/src';
import { Coffee } from '@lucide/vue';
import { ExclamationTriangleIcon } from '@heroicons/vue/20/solid';
const props = defineProps<{
title: string;
@@ -11,6 +13,8 @@ const props = defineProps<{
durationSeconds?: number;
start?: string | Date | null;
end?: string | Date | null;
isBreak?: boolean;
isMisplacedBreak?: boolean;
}>();
const effectiveDurationSeconds = computed(() => {
@@ -41,7 +45,15 @@ const formattedDuration = computed(() =>
<template>
<div class="text-2xs leading-tight px-0.5 py-1">
<div class="font-semibold">{{ title }}</div>
<div class="font-semibold flex items-center gap-1">
<Coffee v-if="isBreak" class="w-3 h-3 shrink-0" />
<span class="truncate">{{ title }}</span>
<ExclamationTriangleIcon
v-if="isMisplacedBreak"
data-testid="calendar_break_placement_hint"
title="This break does not align with your work entries"
class="w-3 h-3 shrink-0 text-amber-600 dark:text-amber-400" />
</div>
<div v-if="projectName" class="font-medium opacity-90">
{{ projectName }}
</div>

View File

@@ -12,8 +12,10 @@ import {
} from 'vue';
import { useLocalStorage } from '@vueuse/core';
import { useCssVariable } from '../utils/useCssVariable';
import { getLocalizedDayJs } from '../utils/time';
import { useBreaksEnabled } from '../utils/useBreaksEnabled';
import { getLocalizedDayJs, getLocalizedDayJsFromMinutes } from '../utils/time';
import { LoadingSpinner, TimeEntryCreateModal, TimeEntryEditModal } from '..';
import BreakCreateModal from '../TimeEntry/BreakCreateModal.vue';
import FullCalendarDayHeader from './FullCalendarDayHeader.vue';
import CalendarToolbar from './CalendarToolbar.vue';
import CalendarDayColumn from './CalendarDayColumn.vue';
@@ -34,6 +36,7 @@ import {
StopIcon,
XMarkIcon,
} from '@heroicons/vue/20/solid';
import { Coffee } from '@lucide/vue';
import type { ActivityPeriod } from './activityTypes';
import { SLOT_HEIGHT, TIME_AXIS_WIDTH, type DayEvent } from './calendarTypes';
import { useCalendarGrid } from './useCalendarGrid';
@@ -74,6 +77,8 @@ const props = defineProps<{
currency: string;
canCreateProject: boolean;
organizationBillableRate: number | null;
// Local date (YYYY-MM-DD) to open the calendar on, e.g. from a "Fix in calendar" deep link
initialDate?: string | null;
createTimeEntry: (
entry: Omit<TimeEntry, 'id' | 'organization_id' | 'user_id'>
@@ -87,6 +92,9 @@ const props = defineProps<{
const newEventStart = ref<Dayjs | null>(null);
const newEventEnd = ref<Dayjs | null>(null);
const showCreateBreakModal = ref(false);
const newBreakStart = ref<Dayjs | null>(null);
const newBreakEnd = ref<Dayjs | null>(null);
const showCreateTimeEntryModal = ref<boolean>(false);
const showEditTimeEntryModal = ref<boolean>(false);
const selectedTimeEntry = ref<TimeEntry | null>(null);
@@ -114,6 +122,7 @@ const currentTime = ref(getLocalizedDayJs());
let currentTimeInterval: ReturnType<typeof setInterval> | null = null;
const organization = inject<ComputedRef<Organization>>('organization');
const breaksEnabled = useBreaksEnabled();
const {
slots,
@@ -138,23 +147,34 @@ const {
} = useCalendarNavigation({
onDatesChange: (payload) => emit('dates-change', payload),
scrollToCurrentTime: () => scrollToCurrentTime(),
// Parse as local midnight in the user's timezone — getLocalizedDayJs would
// treat the bare date as UTC midnight, landing on the previous local day
// for negative UTC offsets
initialDate: props.initialDate ? getLocalizedDayJsFromMinutes(props.initialDate, 0) : null,
});
const cssBackground = useCssVariable('--color-bg-background');
const { optimisticOverrides, calendarEvents, eventsByDay, dailyTotals, isToday, nowIndicatorTop } =
useCalendarEvents({
timeEntries: () => props.timeEntries,
projects: () => props.projects,
clients: () => props.clients,
tasks: () => props.tasks,
calendarSettings,
viewDays,
currentTime,
cssBackground,
minutesToPixels,
timeToMinutesFromMidnight,
});
const {
optimisticOverrides,
calendarEvents,
eventsByDay,
dailyTotals,
dailyBreakTotals,
isToday,
nowIndicatorTop,
} = useCalendarEvents({
timeEntries: () => props.timeEntries,
projects: () => props.projects,
clients: () => props.clients,
tasks: () => props.tasks,
calendarSettings,
viewDays,
currentTime,
cssBackground,
minutesToPixels,
timeToMinutesFromMidnight,
});
const {
activityBoxesForDay,
@@ -244,6 +264,7 @@ const {
handleContextStop,
handleContextDiscard,
handleContextCreate,
handleContextCreateBreak,
} = useContextMenu({
calendarSettings,
calendarEvents,
@@ -262,6 +283,11 @@ const {
newEventEnd.value = end;
showCreateTimeEntryModal.value = true;
},
onCreateBreak: (start, end) => {
newBreakStart.value = start;
newBreakEnd.value = end;
showCreateBreakModal.value = true;
},
emitRefresh: () => emit('refresh'),
});
@@ -274,6 +300,14 @@ watch(showCreateTimeEntryModal, (value) => {
}
});
watch(showCreateBreakModal, (value) => {
if (!value) {
newBreakStart.value = null;
newBreakEnd.value = null;
emit('refresh');
}
});
watch(showEditTimeEntryModal, (value) => {
if (!value) {
selectedTimeEntry.value = null;
@@ -455,6 +489,12 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
:start="newEventStart ? newEventStart.toISOString() : undefined"
:end="newEventEnd ? newEventEnd.toISOString() : undefined" />
<BreakCreateModal
v-model:show="showCreateBreakModal"
:create-time-entry="createTimeEntry"
:start="newBreakStart ? newBreakStart.toISOString() : undefined"
:end="newBreakEnd ? newBreakEnd.toISOString() : undefined" />
<TimeEntryEditModal
v-model:show="showEditTimeEntryModal"
:time-entry="selectedTimeEntry as any"
@@ -516,8 +556,9 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
<FullCalendarDayHeader
:date="day"
:is-today="isToday(day)"
:total-seconds="
dailyTotals[day.format('YYYY-MM-DD')] || 0
:total-seconds="dailyTotals[day.format('YYYY-MM-DD')] || 0"
:break-seconds="
dailyBreakTotals[day.format('YYYY-MM-DD')] || 0
" />
</div>
</div>
@@ -682,11 +723,19 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
<PencilIcon class="w-4 h-4 text-icon-default" />
<span>Edit</span>
</ContextMenuItem>
<ContextMenuItem class="space-x-3" @select="handleContextDuplicate()">
<!-- Duplicate/Split create a new entry of the same type, which the
server rejects for breaks when breaks are disabled -->
<ContextMenuItem
v-if="contextMenuTimeEntry.type !== 'break' || breaksEnabled"
class="space-x-3"
@select="handleContextDuplicate()">
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
<span>Duplicate</span>
</ContextMenuItem>
<ContextMenuItem class="space-x-3" @select="handleContextSplit()">
<ContextMenuItem
v-if="contextMenuTimeEntry.type !== 'break' || breaksEnabled"
class="space-x-3"
@select="handleContextSplit()">
<ScissorsIcon class="w-4 h-4 text-icon-default" />
<span>Split</span>
</ContextMenuItem>
@@ -716,6 +765,13 @@ function getEventDurationSeconds(dayEvent: DayEvent, dayStr: string): number {
<PlusIcon class="w-4 h-4 text-icon-default" />
<span>Create Time Entry</span>
</ContextMenuItem>
<ContextMenuItem
v-if="breaksEnabled"
class="space-x-3"
@select="handleContextCreateBreak()">
<Coffee class="w-4 h-4 text-icon-default" />
<span>Add Break</span>
</ContextMenuItem>
</template>
</ContextMenuContent>
</ContextMenu>

View File

@@ -13,6 +13,8 @@ export interface CalendarEvent {
client?: Client;
task?: Task;
isRunning: boolean;
isBreak: boolean;
isMisplacedBreak: boolean;
durationMinutes: number;
title: string;
backgroundColor: string;

View File

@@ -2,6 +2,7 @@ import { computed, ref, type Ref, type ComputedRef } from 'vue';
import chroma from 'chroma-js';
import type { Dayjs } from 'dayjs';
import type { TimeEntry, Project, Client, Task } from '@/packages/api/src';
import { getBreakPlacementHint } from '../utils/breakPlacement';
import { getDayJsInstance, getLocalizedDayJs } from '../utils/time';
import type { CalendarSettings } from './calendarSettings';
import type { CalendarEvent, DayEvent } from './calendarTypes';
@@ -181,7 +182,8 @@ export function useCalendarEvents(params: {
const calendarEvents = computed<CalendarEvent[]>(() => {
const themeBackground = params.cssBackground.value?.trim();
return params.timeEntries().map((rawEntry) => {
const allEntries = params.timeEntries();
return allEntries.map((rawEntry) => {
const timeEntry = optimisticOverrides.value.get(rawEntry.id) || rawEntry;
const isRunning = timeEntry.end === null;
const project = params.projects().find((p) => p.id === timeEntry.project_id);
@@ -196,9 +198,20 @@ export function useCalendarEvents(params: {
'minutes'
);
const title = timeEntry.description || 'No description';
const baseColor = project?.color || '#6B7280';
const backgroundColor = chroma.mix(baseColor, themeBackground, 0.65, 'lab').hex();
const isBreak = timeEntry.type === 'break';
const isMisplacedBreak = isBreak
? (getBreakPlacementHint(timeEntry, allEntries)?.misplaced ?? false)
: false;
let title: string;
if (isBreak) {
title = timeEntry.description ? `Break · ${timeEntry.description}` : 'Break';
} else {
title = timeEntry.description || 'No description';
}
const baseColor = isBreak ? '#F59E0B' : project?.color || '#6B7280';
const backgroundColor = chroma
.mix(baseColor, themeBackground, isBreak ? 0.75 : 0.65, 'lab')
.hex();
const borderColor = chroma.mix(baseColor, themeBackground, 0.5, 'lab').hex();
const startTime = getLocalizedDayJs(timeEntry.start);
@@ -215,6 +228,8 @@ export function useCalendarEvents(params: {
client,
task,
isRunning,
isBreak,
isMisplacedBreak,
durationMinutes,
title,
backgroundColor,
@@ -253,28 +268,37 @@ export function useCalendarEvents(params: {
return result;
});
const dailyTotals = computed(() => {
function computeDailyTotals(filter: (entry: TimeEntry) => boolean): Record<string, number> {
const totals: Record<string, number> = {};
params.timeEntries().forEach((entry) => {
const date = getLocalizedDayJs(entry.start).format('YYYY-MM-DD');
let durationSeconds: number;
params
.timeEntries()
.filter(filter)
.forEach((entry) => {
const date = getLocalizedDayJs(entry.start).format('YYYY-MM-DD');
let durationSeconds: number;
if (entry.end !== null) {
durationSeconds = getDayJsInstance()(entry.end).diff(
getDayJsInstance()(entry.start),
'seconds'
);
} else {
durationSeconds = Math.max(
0,
params.currentTime.value.diff(getDayJsInstance()(entry.start), 'seconds')
);
}
if (entry.end !== null) {
durationSeconds = getDayJsInstance()(entry.end).diff(
getDayJsInstance()(entry.start),
'seconds'
);
} else {
durationSeconds = Math.max(
0,
params.currentTime.value.diff(getDayJsInstance()(entry.start), 'seconds')
);
}
totals[date] = (totals[date] || 0) + durationSeconds;
});
totals[date] = (totals[date] || 0) + durationSeconds;
});
return totals;
});
}
// Breaks are not working time: the day total only sums work entries,
// the break portion is exposed separately
const dailyTotals = computed(() => computeDailyTotals((entry) => entry.type !== 'break'));
const dailyBreakTotals = computed(() => computeDailyTotals((entry) => entry.type === 'break'));
function isToday(day: Dayjs): boolean {
return day.isSame(getLocalizedDayJs(), 'day');
@@ -294,6 +318,7 @@ export function useCalendarEvents(params: {
calendarEvents,
eventsByDay,
dailyTotals,
dailyBreakTotals,
isToday,
nowIndicatorTop,
};

View File

@@ -6,9 +6,10 @@ import { getWeekStartDayNumber } from '../utils/settings';
export function useCalendarNavigation(callbacks: {
onDatesChange: (payload: { start: Dayjs; end: Dayjs }) => void;
scrollToCurrentTime: () => void;
initialDate?: Dayjs | null;
}) {
const activeView = ref('timeGridWeek');
const currentDate = ref(getLocalizedDayJs());
const currentDate = ref(callbacks.initialDate ?? getLocalizedDayJs());
function getFirstDay(): number {
return getWeekStartDayNumber();

View File

@@ -0,0 +1,95 @@
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { TimeEntry } from '@/packages/api/src';
import type { CalendarEvent } from './calendarTypes';
import { useContextMenu } from './useContextMenu';
function breakEntry(): TimeEntry {
return {
id: 'break-1',
start: '2026-07-14T10:00:00Z',
end: '2026-07-14T11:00:00Z',
duration: 3600,
description: 'Lunch',
project_id: null,
task_id: null,
organization_id: 'organization-1',
user_id: 'user-1',
tags: [],
billable: false,
type: 'break',
} as TimeEntry;
}
describe('useContextMenu break actions', () => {
const createTimeEntry = vi.fn().mockResolvedValue(undefined);
const updateTimeEntry = vi.fn().mockResolvedValue(undefined);
beforeEach(() => {
vi.clearAllMocks();
});
function contextMenu() {
const entry = breakEntry();
const calendarEvents = computed(() => [
{
id: entry.id,
timeEntry: entry,
} as CalendarEvent,
]);
const menu = useContextMenu({
calendarSettings: ref({
snapMinutes: 15,
startHour: 0,
endHour: 24,
slotMinutes: 15,
}),
calendarEvents,
pixelsToMinutesFromMidnight: () => 0,
getDayFromClientX: () => null,
clientYToGridPixels: () => 0,
createTimeEntry,
updateTimeEntry,
deleteTimeEntry: vi.fn().mockResolvedValue(undefined),
onEditEvent: vi.fn(),
onCreateEvent: vi.fn(),
onCreateBreak: vi.fn(),
emitRefresh: vi.fn(),
});
menu.handleCalendarContextMenu({
target: {
closest: () => ({
getAttribute: () => entry.id,
}),
},
} as unknown as MouseEvent);
return menu;
}
it('preserves the type when duplicating a break', async () => {
await contextMenu().handleContextDuplicate();
expect(createTimeEntry).toHaveBeenCalledWith(
expect.objectContaining({
type: 'break',
})
);
});
it('preserves the type when creating the second half of a split break', async () => {
await contextMenu().handleContextSplit();
expect(updateTimeEntry).toHaveBeenCalledWith(
expect.objectContaining({
type: 'break',
})
);
expect(createTimeEntry).toHaveBeenCalledWith(
expect.objectContaining({
type: 'break',
})
);
});
});

View File

@@ -1,7 +1,7 @@
import { ref, type Ref, type ComputedRef } from 'vue';
import type { Dayjs } from 'dayjs';
import type { TimeEntry } from '@/packages/api/src';
import { getDayJsInstance, getLocalizedDayJsFromMinutes } from '../utils/time';
import { getDayJsInstance, getLocalizedDayJs, getLocalizedDayJsFromMinutes } from '../utils/time';
import type { CalendarSettings } from './calendarSettings';
import type { CalendarEvent } from './calendarTypes';
@@ -19,6 +19,7 @@ export function useContextMenu(params: {
deleteTimeEntry: (id: string) => Promise<void>;
onEditEvent: (entry: TimeEntry) => void;
onCreateEvent: (start: Dayjs, end: Dayjs) => void;
onCreateBreak: (start: Dayjs, end: Dayjs) => void;
emitRefresh: () => void;
}) {
const contextMenuTimeEntry = ref<TimeEntry | null>(null);
@@ -73,6 +74,7 @@ export function useContextMenu(params: {
start: entry.start,
end: entry.end,
billable: entry.billable,
type: entry.type,
description: entry.description,
project_id: entry.project_id,
task_id: entry.task_id,
@@ -108,6 +110,7 @@ export function useContextMenu(params: {
start: midpoint.utc().format(),
end: entry.end,
billable: entry.billable,
type: entry.type,
description: entry.description,
project_id: entry.project_id,
task_id: entry.task_id,
@@ -154,6 +157,47 @@ export function useContextMenu(params: {
}
}
function handleContextCreateBreak() {
const dayjs = getDayJsInstance();
if (!contextMenuCreateTime.value) {
params.onCreateBreak(dayjs().utc().subtract(30, 'minute'), dayjs().utc());
return;
}
const clickTime = contextMenuCreateTime.value.start;
// Day matching must use the user's configured timezone (the calendar renders
// its day columns in that timezone), not the browser's local timezone
const clickDate = getLocalizedDayJs(clickTime.format()).format('YYYY-MM-DD');
// When the click lands in a gap between two entries of the same day,
// the break is prefilled to exactly fill that gap
let previousEnd: Dayjs | null = null;
let nextStart: Dayjs | null = null;
for (const calendarEvent of params.calendarEvents.value) {
const entry = calendarEvent.timeEntry;
const entryStart = dayjs.utc(entry.start);
if (getLocalizedDayJs(entry.start).format('YYYY-MM-DD') !== clickDate) {
continue;
}
const entryEnd = entry.end === null ? null : dayjs.utc(entry.end);
if (entryEnd !== null && !entryEnd.isAfter(clickTime)) {
if (previousEnd === null || entryEnd.isAfter(previousEnd)) {
previousEnd = entryEnd;
}
}
if (!entryStart.isBefore(clickTime)) {
if (nextStart === null || entryStart.isBefore(nextStart)) {
nextStart = entryStart;
}
}
}
if (previousEnd !== null && nextStart !== null && previousEnd.isBefore(nextStart)) {
params.onCreateBreak(previousEnd, nextStart);
return;
}
params.onCreateBreak(contextMenuCreateTime.value.start, contextMenuCreateTime.value.end);
}
return {
contextMenuTimeEntry,
contextMenuCreateTime,
@@ -165,5 +209,6 @@ export function useContextMenu(params: {
handleContextStop,
handleContextDiscard,
handleContextCreate,
handleContextCreateBreak,
};
}

View File

@@ -0,0 +1,121 @@
<script setup lang="ts">
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
import DialogModal from '@/packages/ui/src/DialogModal.vue';
import { computed, ref, watch } from 'vue';
import PrimaryButton from '@/packages/ui/src/Buttons/PrimaryButton.vue';
import { Field, FieldLabel } from '../field';
import { getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
import type { CreateTimeEntryBody } from '@/packages/api/src';
import TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
import { Coffee } from '@lucide/vue';
const show = defineModel('show', { default: false });
const saving = ref(false);
const props = defineProps<{
createTimeEntry: (entry: Omit<CreateTimeEntryBody, 'member_id'>) => Promise<void>;
start?: string;
end?: string;
}>();
function defaultStart() {
return getDayJsInstance().utc().subtract(30, 'm').second(0).format();
}
function defaultEnd() {
return getDayJsInstance().utc().second(0).format();
}
const note = ref('');
const localStart = ref(getLocalizedDayJs(defaultStart()).format());
const localEnd = ref(getLocalizedDayJs(defaultEnd()).format());
// Prefill start/end when the modal is opened with a given range (e.g. from the calendar)
watch(
() => props.start,
(value) => {
if (value) {
localStart.value = getLocalizedDayJs(value).format();
}
}
);
watch(
() => props.end,
(value) => {
if (value) {
localEnd.value = getLocalizedDayJs(value).format();
}
}
);
const durationSeconds = computed(() =>
getLocalizedDayJs(localEnd.value).diff(getLocalizedDayJs(localStart.value), 'second')
);
async function submit() {
if (durationSeconds.value <= 0) return;
saving.value = true;
try {
await props.createTimeEntry({
description: note.value,
project_id: null,
task_id: null,
tags: [],
billable: false,
type: 'break',
start: getLocalizedDayJs(localStart.value).utc().format(),
end: getLocalizedDayJs(localEnd.value).utc().format(),
});
note.value = '';
localStart.value = getLocalizedDayJs(defaultStart()).format();
localEnd.value = getLocalizedDayJs(defaultEnd()).format();
show.value = false;
} finally {
saving.value = false;
}
}
</script>
<template>
<DialogModal closeable :show="show" @close="show = false">
<template #title>
<div class="flex items-center space-x-2 text-amber-600 dark:text-amber-400">
<Coffee class="w-5 h-5" />
<span> Add break </span>
</div>
</template>
<template #content>
<div class="space-y-4">
<TimeRangeFields
v-model:start="localStart"
v-model:end="localEnd"
date-picker-size="sm"></TimeRangeFields>
<Field>
<FieldLabel for="break_note">Note (optional)</FieldLabel>
<TextInput
id="break_note"
v-model="note"
placeholder="e.g. Lunch"
type="text"
class="block w-full"
@keydown.enter="submit" />
</Field>
</div>
</template>
<template #footer>
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>
<PrimaryButton
tabindex="2"
class="ms-3"
:class="{ 'opacity-25': saving }"
:disabled="saving || durationSeconds <= 0"
@click="submit">
Add Break
</PrimaryButton>
</template>
</DialogModal>
</template>
<style scoped></style>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import { Coffee } from '@lucide/vue';
</script>
<template>
<div
data-testid="break_badge"
class="flex items-center space-x-1.5 text-sm font-medium text-text-secondary">
<Coffee class="w-4 h-4 text-text-tertiary" />
<span>Break</span>
</div>
</template>
<style scoped></style>

View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import { ExclamationTriangleIcon, ArrowRightIcon } from '@heroicons/vue/20/solid';
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/packages/ui/src';
// Warning affordance for a misplaced break: an amber triangle that opens a small
// popover offering to jump to the break's day in the calendar. Rendered by the
// caller only when the break is actually misplaced (see `showPlacementHint`).
defineProps<{
// Local day (YYYY-MM-DD) the calendar should navigate to.
fixDate: string;
// Delegated navigation — packages/ui stays router-agnostic.
fixInCalendar?: (date: string) => void;
}>();
</script>
<template>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<button
type="button"
data-testid="break_placement_hint"
title="This break does not align with your work entries"
class="flex items-center justify-center shrink-0 rounded-full p-0.5 text-amber-500 hover:bg-amber-500/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<ExclamationTriangleIcon class="w-4 h-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent class="min-w-[260px]" align="start">
<div class="px-3 py-2 space-y-1.5">
<p class="text-xs text-text-secondary">
This break is not directly between work entries.
</p>
<button
v-if="fixInCalendar"
type="button"
data-testid="break_fix_in_calendar"
class="inline-flex items-center gap-1 text-sm font-medium text-accent-400 hover:underline"
@click="fixInCalendar(fixDate)">
Fix in calendar
<ArrowRightIcon class="w-3.5 h-3.5" />
</button>
</div>
</DropdownMenuContent>
</DropdownMenu>
</template>

View File

@@ -16,11 +16,19 @@ import TimeEntryRowTagDropdown from '@/packages/ui/src/TimeEntry/TimeEntryRowTag
import TimeEntryMoreOptionsDropdown from '@/packages/ui/src/TimeEntry/TimeEntryMoreOptionsDropdown.vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
import { ref, inject, type ComputedRef } from 'vue';
import { formatHumanReadableDuration, formatStartEnd } from '@/packages/ui/src/utils/time';
import { ref, inject, computed, type ComputedRef } from 'vue';
import {
formatHumanReadableDuration,
formatStartEnd,
getLocalizedDayJs,
} from '@/packages/ui/src/utils/time';
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
import GroupedItemsCountButton from '@/packages/ui/src/GroupedItemsCountButton.vue';
import type { TimeEntriesGroupedByType } from '@/types/time-entries';
import {
findMisplacedBreak,
type BreakPlacementHint,
} from '@/packages/ui/src/utils/breakPlacement';
import {
Checkbox,
ContextMenu,
@@ -30,6 +38,9 @@ import {
ContextMenuTrigger,
} from '@/packages/ui/src';
import { PlayIcon, TrashIcon } from '@heroicons/vue/20/solid';
import BreakLabel from '@/packages/ui/src/TimeEntry/BreakLabel.vue';
import BreakPlacementHintButton from '@/packages/ui/src/TimeEntry/BreakPlacementHintButton.vue';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import { twMerge } from 'tailwind-merge';
const props = defineProps<{
timeEntry: TimeEntriesGroupedByType;
@@ -50,6 +61,8 @@ const props = defineProps<{
selectedTimeEntries: TimeEntry[];
enableEstimatedTime: boolean;
canCreateProject: boolean;
breakPlacementHints?: Record<string, BreakPlacementHint | null>;
fixInCalendar?: (date: string) => void;
}>();
const emit = defineEmits<{
selected: [TimeEntry[]];
@@ -57,6 +70,26 @@ const emit = defineEmits<{
}>();
const organization = inject<ComputedRef<Organization>>('organization');
const breaksEnabled = useBreaksEnabled();
// Continue creates a new entry of the same type, which the server rejects
// for breaks when breaks are disabled for the organization
const canRecreate = computed(() => props.timeEntry.type !== 'break' || breaksEnabled.value);
// Grouped breaks collapse into a single summary row, so surface the placement
// warning if any entry in the group is misplaced. All grouped entries share the
// same day, so the first misplaced one supplies the calendar navigation date.
const misplacedBreakEntry = computed<TimeEntry | null>(() =>
findMisplacedBreak(props.timeEntry.timeEntries, props.breakPlacementHints ?? {})
);
const showPlacementHint = computed(
() => props.timeEntry.type === 'break' && misplacedBreakEntry.value !== null
);
const breakFixDate = computed(() =>
misplacedBreakEntry.value
? getLocalizedDayJs(misplacedBreakEntry.value.start).format('YYYY-MM-DD')
: ''
);
function updateTimeEntryDescription(description: string) {
props.updateTimeEntries(
@@ -121,12 +154,26 @@ function onSelectChange(checked: boolean) {
{{ timeEntry?.timeEntries?.length }}
</GroupedItemsCountButton>
<TimeEntryDescriptionInput
v-if="timeEntry.type !== 'break'"
class="min-w-0 mr-4 shrink"
:model-value="timeEntry.description"
@changed="
updateTimeEntryDescription
"></TimeEntryDescriptionInput>
<BreakLabel
v-if="timeEntry.type === 'break'"
class="px-2 shrink-0" />
<span
v-if="timeEntry.type === 'break' && timeEntry.description"
class="min-w-0 mr-4 shrink truncate text-sm text-text-secondary">
{{ timeEntry.description }}
</span>
<BreakPlacementHintButton
v-if="showPlacementHint"
:fix-date="breakFixDate"
:fix-in-calendar="fixInCalendar" />
<TimeTrackerProjectTaskDropdown
v-if="timeEntry.type !== 'break'"
class="min-w-0 shrink"
:clients
:create-project
@@ -147,11 +194,13 @@ function onSelectChange(checked: boolean) {
<div
class="hidden @lg:flex items-center font-medium space-x-1 @lg:space-x-2 shrink-0">
<TimeEntryRowTagDropdown
v-if="timeEntry.type !== 'break'"
:create-tag
:tags="tags"
:model-value="timeEntry.tags"
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
<BillableToggleButton
v-if="timeEntry.type !== 'break'"
:model-value="timeEntry.billable"
size="small"
faded
@@ -189,6 +238,7 @@ function onSelectChange(checked: boolean) {
</button>
<TimeTrackerStartStop
v-if="canRecreate"
:active="!!(timeEntry.start && !timeEntry.end)"
variant="secondary"
class="opacity-60 flex group-hover:opacity-100 focus-visible:opacity-100"
@@ -231,7 +281,17 @@ function onSelectChange(checked: boolean) {
</div>
<!-- Second row: project/task - tags - billable - start - more -->
<div class="flex items-center justify-between mt-1">
<div
v-if="timeEntry.type === 'break'"
class="flex items-center min-w-0">
<BreakLabel class="px-2 min-w-0" />
<BreakPlacementHintButton
v-if="showPlacementHint"
:fix-date="breakFixDate"
:fix-in-calendar="fixInCalendar" />
</div>
<TimeTrackerProjectTaskDropdown
v-else
class="min-w-0"
:clients
:create-project
@@ -249,16 +309,19 @@ function onSelectChange(checked: boolean) {
"></TimeTrackerProjectTaskDropdown>
<div class="flex items-center shrink-0">
<TimeEntryRowTagDropdown
v-if="timeEntry.type !== 'break'"
:create-tag
:tags="tags"
:model-value="timeEntry.tags"
compact
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
<BillableToggleButton
v-if="timeEntry.type !== 'break'"
:model-value="timeEntry.billable"
size="small"
@changed="updateTimeEntryBillable"></BillableToggleButton>
<TimeTrackerStartStop
v-if="canRecreate"
:active="!!(timeEntry.start && !timeEntry.end)"
variant="secondary"
class="ml-2"
@@ -278,7 +341,7 @@ function onSelectChange(checked: boolean) {
</MainContainer>
<div
v-if="expanded"
class="w-full border-t border-default-background-separator bg-black/15">
class="w-full border-t border-default-background-separator bg-black/5 dark:bg-black/15">
<TimeEntryRow
v-for="subEntry in timeEntry.timeEntries"
:key="subEntry.id"
@@ -303,6 +366,8 @@ function onSelectChange(checked: boolean) {
:duplicate-time-entry="() => duplicateTimeEntry(subEntry)"
:currency="currency"
:create-tag
:placement-hint="breakPlacementHints?.[subEntry.id] ?? null"
:fix-in-calendar="fixInCalendar"
:time-entry="subEntry"
@selected="emit('selected', [subEntry])"
@unselected="emit('unselected', [subEntry])"></TimeEntryRow>
@@ -311,12 +376,13 @@ function onSelectChange(checked: boolean) {
</ContextMenuTrigger>
<ContextMenuContent class="min-w-[160px]">
<ContextMenuItem
v-if="canRecreate"
class="space-x-3"
@select="onStartStopClick(timeEntry.timeEntries[0]!)">
<PlayIcon class="w-4 h-4 text-icon-default" />
<span>Continue</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuSeparator v-if="canRecreate" />
<ContextMenuItem
class="space-x-3 text-destructive"
@select="deleteTimeEntries(timeEntry?.timeEntries ?? [])">

View File

@@ -5,7 +5,6 @@ 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 { Field, FieldLabel } from '../field';
import { TagIcon } from '@heroicons/vue/20/solid';
import { getDayJsInstance, getLocalizedDayJs } from '@/packages/ui/src/utils/time';
import type {
@@ -19,12 +18,8 @@ import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
import { Button } from '@/packages/ui/src/Buttons';
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 TimeRangeFields from '@/packages/ui/src/TimeEntry/TimeRangeFields.vue';
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);
@@ -62,6 +57,7 @@ const timeEntryDefaultValues = {
task_id: null,
tags: [],
billable: false,
type: 'work' as CreateTimeEntryBody['type'],
start: getDayJsInstance().utc().subtract(1, 'h').second(0).format(),
end: getDayJsInstance().utc().second(0).format(),
};
@@ -107,9 +103,6 @@ const localEnd = ref(getLocalizedDayJs(timeEntryDefaultValues.end).format());
watch(localStart, (value) => {
timeEntry.value.start = getLocalizedDayJs(value).utc().format();
if (getLocalizedDayJs(localEnd.value).isBefore(getLocalizedDayJs(value))) {
localEnd.value = value;
}
});
watch(localEnd, (value) => {
@@ -202,39 +195,11 @@ const billableProxy = computed({
</Select>
</div>
</div>
<div class="grid grid-cols-2 sm:grid-cols-5 gap-4 pt-4">
<Field class="col-span-2 sm:col-span-3">
<FieldLabel>Duration</FieldLabel>
<div class="space-y-2 flex flex-col">
<DurationHumanInput
v-model:start="localStart"
v-model:end="localEnd"
name="Duration"></DurationHumanInput>
<div class="text-sm flex space-x-1">
<InformationCircleIcon
class="w-4 shrink-0 text-text-quaternary"></InformationCircleIcon>
<span class="text-text-secondary text-xs">
You can type natural language like
<span class="font-semibold"> 2h 30m</span>
</span>
</div>
</div>
</Field>
<Field>
<FieldLabel>Start</FieldLabel>
<div class="flex flex-col gap-2">
<TimePickerSimple v-model="localStart" class="w-full"></TimePickerSimple>
<DatePicker v-model="localStart" class="w-full" tabindex="1"></DatePicker>
</div>
</Field>
<Field>
<FieldLabel>End</FieldLabel>
<div class="flex flex-col gap-2">
<TimePickerSimple v-model="localEnd" class="w-full"></TimePickerSimple>
<DatePicker v-model="localEnd" class="w-full" tabindex="1"></DatePicker>
</div>
</Field>
</div>
<TimeRangeFields
v-model:start="localStart"
v-model:end="localEnd"
show-hint
class="pt-4"></TimeRangeFields>
</template>
<template #footer>
<SecondaryButton tabindex="2" @click="show = false"> Cancel</SecondaryButton>

View File

@@ -23,8 +23,14 @@ 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 { Coffee } from '@lucide/vue';
import type { Tag, Task } from '@/packages/api/src';
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
// Breaks may have been disabled after this entry was created, so an existing break can still be
// edited (and converted back), but a work entry may only offer the break option when enabled.
const breaksEnabled = useBreaksEnabled();
const show = defineModel('show', { default: false });
const saving = ref(false);
@@ -137,6 +143,24 @@ const billableProxy = computed({
}
},
});
const isBreak = computed(() => editableTimeEntry.value?.type === 'break');
const typeProxy = computed({
get: () => editableTimeEntry.value?.type ?? 'work',
set: (value: string) => {
if (editableTimeEntry.value) {
editableTimeEntry.value.type = value as TimeEntry['type'];
if (value === 'break') {
// Breaks can not be billable, have tags or belong to a project/task
editableTimeEntry.value.project_id = null;
editableTimeEntry.value.task_id = null;
editableTimeEntry.value.billable = false;
editableTimeEntry.value.tags = [];
}
}
},
});
</script>
<template>
@@ -162,7 +186,7 @@ const billableProxy = computed({
</div>
</div>
<div class="flex flex-col sm:flex-row sm:items-end gap-2">
<div class="flex-1 min-w-0">
<div v-if="!isBreak" class="flex-1 min-w-0">
<TimeTrackerProjectTaskDropdown
v-model:project="editableTimeEntry.project_id"
v-model:task="editableTimeEntry.task_id"
@@ -178,8 +202,24 @@ const billableProxy = computed({
:tasks="tasks"
:enable-estimated-time="enableEstimatedTime" />
</div>
<div v-else class="flex-1 min-w-0"></div>
<div class="flex items-center gap-2 shrink-0">
<Select v-if="breaksEnabled || isBreak" v-model="typeProxy">
<SelectTrigger :show-chevron="false">
<SelectValue class="flex items-center gap-2">
<Coffee
class="h-4 w-4"
:class="isBreak ? 'text-amber-500' : 'text-icon-default'" />
<span>{{ isBreak ? 'Break' : 'Work time' }}</span>
</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="work">Work time</SelectItem>
<SelectItem value="break">Break</SelectItem>
</SelectContent>
</Select>
<TagDropdown
v-if="!isBreak"
v-model="editableTimeEntry.tags"
:create-tag
:tags="tags"
@@ -195,7 +235,7 @@ const billableProxy = computed({
</Button>
</template>
</TagDropdown>
<Select v-model="billableProxy">
<Select v-if="!isBreak" v-model="billableProxy">
<SelectTrigger :show-chevron="false">
<SelectValue class="flex items-center gap-2">
<BillableIcon class="h-4 text-icon-default" />

View File

@@ -11,6 +11,10 @@ import type {
Client,
} from '@/packages/api/src';
import { getDayJsInstance, getLocalizedDateFromTimestamp } from '@/packages/ui/src/utils/time';
import {
getBreakPlacementHint,
type BreakPlacementHint,
} from '@/packages/ui/src/utils/breakPlacement';
import TimeEntryAggregateRow from '@/packages/ui/src/TimeEntry/TimeEntryAggregateRow.vue';
import TimeEntryRowHeading from '@/packages/ui/src/TimeEntry/TimeEntryRowHeading.vue';
import TimeEntryRow from '@/packages/ui/src/TimeEntry/TimeEntryRow.vue';
@@ -39,12 +43,24 @@ const props = withDefaults(
enableEstimatedTime: boolean;
canCreateProject: boolean;
groupSimilarTimeEntries?: boolean;
// Host-provided navigation to the calendar for a break's day (YYYY-MM-DD)
fixInCalendar?: (date: string) => void;
}>(),
{
groupSimilarTimeEntries: true,
}
);
const breakPlacementHints = computed<Record<string, BreakPlacementHint | null>>(() => {
const hints: Record<string, BreakPlacementHint | null> = {};
for (const entry of props.timeEntries) {
if (entry.type === 'break') {
hints[entry.id] = getBreakPlacementHint(entry, props.timeEntries);
}
}
return hints;
});
const groupedTimeEntries = computed(() => {
const groupedEntriesByDay: Record<string, TimeEntry[]> = {};
for (const entry of props.timeEntries) {
@@ -75,6 +91,7 @@ const groupedTimeEntries = computed(() => {
e.project_id === entry.project_id &&
e.task_id === entry.task_id &&
e.billable === entry.billable &&
e.type === entry.type &&
e.description === entry.description
);
if (oldEntriesIndex !== -1 && newDailyEntries[oldEntriesIndex]) {
@@ -113,13 +130,24 @@ function startTimeEntryFromExisting(entry: TimeEntry) {
start: getDayJsInstance().utc().format(),
end: null,
billable: entry.billable,
type: entry.type,
description: entry.description,
tags: [...entry.tags],
});
}
function sumDuration(timeEntries: TimeEntry[]) {
return timeEntries.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
// Breaks are not working time: the day total only sums work entries,
// the break portion is shown separately in the heading
return timeEntries
.filter((entry) => entry.type !== 'break')
.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
}
function sumBreakDuration(timeEntries: TimeEntry[]) {
return timeEntries
.filter((entry) => entry.type === 'break')
.reduce((acc, entry) => acc + (entry?.duration ?? 0), 0);
}
function selectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
for (const timeEntry of value) {
@@ -151,6 +179,7 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
<TimeEntryRowHeading
:date="String(key)"
:duration="sumDuration(value)"
:break-duration="sumBreakDuration(value)"
:checked="
value.every((timeEntry: TimeEntry) => selectedTimeEntries.includes(timeEntry))
"
@@ -176,6 +205,8 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
:create-tag
:currency="currency"
:organization-billable-rate="organizationBillableRate"
:break-placement-hints="breakPlacementHints"
:fix-in-calendar="fixInCalendar"
:time-entry="entry"
@selected="
(timeEntries: TimeEntry[]) => {
@@ -213,6 +244,9 @@ function unselectAllTimeEntries(value: TimeEntriesGroupedByType[]) {
:on-start-stop-click="() => startTimeEntryFromExisting(entry)"
:delete-time-entry="() => deleteTimeEntries([entry])"
:duplicate-time-entry="() => createTimeEntry(entry)"
:create-time-entry="createTimeEntry"
:placement-hint="breakPlacementHints[entry.timeEntries[0]!.id] ?? null"
:fix-in-calendar="fixInCalendar"
:currency="currency"
:time-entry="entry.timeEntries[0]!"
@selected="selectedTimeEntries.push(entry)"

View File

@@ -15,7 +15,7 @@ import {
type UpdateMultipleTimeEntriesChangeset,
} from '@/packages/api/src';
import { Checkbox } from '@/packages/ui/src';
import { TagIcon } from '@heroicons/vue/20/solid';
import { TagIcon, ExclamationTriangleIcon } from '@heroicons/vue/20/solid';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '..';
import { Button } from '@/packages/ui/src/Buttons';
import TagDropdown from '@/packages/ui/src/Tag/TagDropdown.vue';
@@ -129,6 +129,21 @@ watch(removeAllTags, () => {
selectedTags.value = [];
}
});
const selectedBreaksCount = computed(
() => props.timeEntries.filter((entry) => entry.type === 'break').length
);
// Mirrors the server-side skip in TimeEntryController::updateMultiple: a break
// entry is skipped entirely when the changeset assigns a project, makes it
// billable, or adds tags (clearing tags via removeAllTags is fine).
const showBreakWarning = computed(
() =>
selectedBreaksCount.value > 0 &&
((projectId.value !== null && projectId.value !== '') ||
billable.value === true ||
selectedTags.value.length > 0)
);
</script>
<template>
@@ -141,6 +156,20 @@ watch(removeAllTags, () => {
<template #content>
<div class="space-y-4">
<div
v-if="showBreakWarning"
data-testid="mass_update_break_warning"
class="flex items-start space-x-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-sm text-amber-600 dark:text-amber-400">
<ExclamationTriangleIcon class="w-4 h-4 mt-0.5 shrink-0" />
<span>
{{ selectedBreaksCount }}
{{ selectedBreaksCount === 1 ? 'break is' : 'breaks are' }} selected
breaks can not have a project or tags, or be billable, so
{{ selectedBreaksCount === 1 ? 'this entry' : 'these entries' }} will be
skipped entirely and none of the changes (including the description) will be
applied to {{ selectedBreaksCount === 1 ? 'it' : 'them' }}.
</span>
</div>
<Field>
<FieldLabel for="description">Description</FieldLabel>
<TextInput

View File

@@ -18,6 +18,8 @@ import TimeEntryRowDurationInput from '@/packages/ui/src/TimeEntry/TimeEntryRowD
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 { getLocalizedDayJs } from '@/packages/ui/src/utils/time';
import { useBreaksEnabled } from '@/packages/ui/src/utils/useBreaksEnabled';
import { computed, ref } from 'vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import {
@@ -29,6 +31,10 @@ import {
ContextMenuTrigger,
} from '@/packages/ui/src';
import { PlayIcon, PencilIcon, DocumentDuplicateIcon, TrashIcon } from '@heroicons/vue/20/solid';
import BreakLabel from '@/packages/ui/src/TimeEntry/BreakLabel.vue';
import BreakPlacementHintButton from '@/packages/ui/src/TimeEntry/BreakPlacementHintButton.vue';
import type { BreakPlacementHint } from '@/packages/ui/src/utils/breakPlacement';
import type { CreateTimeEntryBody } from '@/packages/api/src';
const props = defineProps<{
timeEntry: TimeEntry;
@@ -45,6 +51,9 @@ const props = defineProps<{
deleteTimeEntry: () => void;
duplicateTimeEntry?: () => void;
updateTimeEntry: (timeEntry: TimeEntry) => void;
createTimeEntry?: (entry: Omit<CreateTimeEntryBody, 'member_id'>) => void;
placementHint?: BreakPlacementHint | null;
fixInCalendar?: (date: string) => void;
currency: string;
organizationBillableRate: number | null;
showMember?: boolean;
@@ -59,6 +68,20 @@ const emit = defineEmits<{ selected: []; unselected: [] }>();
const showEditModal = ref(false);
const breaksEnabled = useBreaksEnabled();
const isBreak = computed(() => props.timeEntry.type === 'break');
// Continue/Duplicate create a new entry of the same type, which the server
// rejects for breaks when breaks are disabled for the organization
const canRecreate = computed(() => !isBreak.value || breaksEnabled.value);
const showPlacementHint = computed(
() => isBreak.value && props.placementHint != null && props.placementHint.misplaced
);
const breakFixDate = computed(() => getLocalizedDayJs(props.timeEntry.start).format('YYYY-MM-DD'));
function updateTimeEntryDescription(description: string) {
props.updateTimeEntry({ ...props.timeEntry, description });
}
@@ -131,10 +154,22 @@ async function handleDeleteTimeEntry() {
<Checkbox :checked="selected" @update:checked="onSelectChange" />
<div v-if="indent === true" class="w-10 h-7"></div>
<TimeEntryDescriptionInput
v-if="!isBreak"
class="min-w-0 mr-4 shrink"
:model-value="timeEntry.description"
@changed="updateTimeEntryDescription"></TimeEntryDescriptionInput>
<BreakLabel v-if="isBreak" class="pl-1.5 @lg:pl-3 pr-2 shrink-0" />
<span
v-if="isBreak && timeEntry.description"
class="min-w-0 mr-4 shrink truncate text-sm text-text-secondary">
{{ timeEntry.description }}
</span>
<BreakPlacementHintButton
v-if="showPlacementHint"
:fix-date="breakFixDate"
:fix-in-calendar="fixInCalendar" />
<TimeTrackerProjectTaskDropdown
v-if="!isBreak"
class="min-w-0 shrink"
:create-project
:create-client
@@ -154,11 +189,13 @@ async function handleDeleteTimeEntry() {
{{ memberName }}
</div>
<TimeEntryRowTagDropdown
v-if="!isBreak"
:create-tag
:tags="tags"
:model-value="timeEntry.tags"
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
<BillableToggleButton
v-if="!isBreak"
:model-value="timeEntry.billable"
size="small"
faded
@@ -176,11 +213,13 @@ async function handleDeleteTimeEntry() {
:is-report="props.isReport"
@changed="updateStartEndTime"></TimeEntryRowDurationInput>
<TimeTrackerStartStop
v-if="canRecreate"
:active="!!(timeEntry.start && !timeEntry.end)"
variant="secondary"
class="opacity-60 flex focus-visible:opacity-100 group-hover:opacity-100"
@changed="onStartStopClick"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
:show-duplicate="canRecreate"
@edit="handleEdit"
@duplicate="duplicateTimeEntry"
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
@@ -190,11 +229,17 @@ async function handleDeleteTimeEntry() {
<!-- First row: description + duration -->
<div class="flex items-center justify-between min-w-0">
<TimeEntryDescriptionInput
v-if="!isBreak"
class="min-w-0 flex-1"
:model-value="timeEntry.description"
@changed="
updateTimeEntryDescription
"></TimeEntryDescriptionInput>
<span
v-else
class="min-w-0 flex-1 truncate text-sm text-text-secondary pl-1.5">
{{ timeEntry.description }}
</span>
<TimeEntryRowDurationInput
:start="timeEntry.start"
:end="timeEntry.end"
@@ -203,7 +248,9 @@ async function handleDeleteTimeEntry() {
</div>
<!-- Second row: project/task - tags - billable - start - more -->
<div class="flex items-center justify-between mt-1">
<BreakLabel v-if="isBreak" class="pl-1.5 pr-2 min-w-0" />
<TimeTrackerProjectTaskDropdown
v-else
class="min-w-0"
:create-project
:create-client
@@ -221,21 +268,25 @@ async function handleDeleteTimeEntry() {
"></TimeTrackerProjectTaskDropdown>
<div class="flex items-center shrink-0">
<TimeEntryRowTagDropdown
v-if="!isBreak"
:create-tag
:tags="tags"
:model-value="timeEntry.tags"
compact
@changed="updateTimeEntryTags"></TimeEntryRowTagDropdown>
<BillableToggleButton
v-if="!isBreak"
:model-value="timeEntry.billable"
size="small"
@changed="updateTimeEntryBillable"></BillableToggleButton>
<TimeTrackerStartStop
v-if="canRecreate"
:active="!!(timeEntry.start && !timeEntry.end)"
variant="secondary"
class="ml-2"
@changed="onStartStopClick"></TimeTrackerStartStop>
<TimeEntryMoreOptionsDropdown
:show-duplicate="canRecreate"
@edit="handleEdit"
@duplicate="duplicateTimeEntry"
@delete="deleteTimeEntry"></TimeEntryMoreOptionsDropdown>
@@ -247,7 +298,7 @@ async function handleDeleteTimeEntry() {
</div>
</ContextMenuTrigger>
<ContextMenuContent class="min-w-[160px]">
<ContextMenuItem class="space-x-3" @select="onStartStopClick()">
<ContextMenuItem v-if="canRecreate" class="space-x-3" @select="onStartStopClick()">
<PlayIcon class="w-4 h-4 text-icon-default" />
<span>Continue</span>
</ContextMenuItem>
@@ -255,7 +306,7 @@ async function handleDeleteTimeEntry() {
<PencilIcon class="w-4 h-4 text-icon-default" />
<span>Edit</span>
</ContextMenuItem>
<ContextMenuItem class="space-x-3" @select="duplicateTimeEntry?.()">
<ContextMenuItem v-if="canRecreate" class="space-x-3" @select="duplicateTimeEntry?.()">
<DocumentDuplicateIcon class="w-4 h-4 text-icon-default" />
<span>Duplicate</span>
</ContextMenuItem>

View File

@@ -12,11 +12,17 @@ import { CalendarIcon } from '@heroicons/vue/20/solid';
const organization = inject<ComputedRef<Organization>>('organization');
defineProps<{
date: string;
duration: number;
checked: boolean;
}>();
withDefaults(
defineProps<{
date: string;
duration: number;
checked: boolean;
breakDuration?: number;
}>(),
{
breakDuration: 0,
}
);
const emit = defineEmits<{
selectAll: [];
unselectAll: [];
@@ -55,6 +61,19 @@ function selectUnselectAll(value: boolean) {
</span>
</div>
<div class="text-text-primary pr-2 @lg:pr-[92px]">
<span
v-if="breakDuration > 0"
data-testid="day_break_duration"
class="text-text-secondary font-normal mr-2">
{{
formatHumanReadableDuration(
breakDuration,
organization?.interval_format,
organization?.number_format
)
}}
break ·
</span>
<span class="font-medium">
{{
formatHumanReadableDuration(

View File

@@ -0,0 +1,73 @@
<script setup lang="ts">
import { watch } from 'vue';
import { InformationCircleIcon } from '@heroicons/vue/20/solid';
import { Field, FieldLabel } from '../field';
import DatePicker from '@/packages/ui/src/Input/DatePicker.vue';
import DurationHumanInput from '@/packages/ui/src/Input/DurationHumanInput.vue';
import TimePickerSimple from '@/packages/ui/src/Input/TimePickerSimple.vue';
import { getLocalizedDayJs } from '@/packages/ui/src/utils/time';
// Local (user timezone) ISO strings, as produced by getLocalizedDayJs(...).format()
const start = defineModel<string>('start', { required: true });
const end = defineModel<string>('end', { required: true });
defineProps<{
showHint?: boolean;
datePickerSize?: 'sm';
}>();
// Moving the start to or past the end drags the end along, preserving the
// range's previous duration, so the range never collapses or inverts.
watch(start, (value, oldValue) => {
if (getLocalizedDayJs(end.value).isAfter(getLocalizedDayJs(value))) return;
const previousDuration = Math.max(
0,
getLocalizedDayJs(end.value).diff(getLocalizedDayJs(oldValue), 'second')
);
end.value = getLocalizedDayJs(value).add(previousDuration, 'second').format();
});
</script>
<template>
<div class="grid grid-cols-2 sm:grid-cols-5 gap-4">
<Field class="col-span-2 sm:col-span-3">
<FieldLabel>Duration</FieldLabel>
<div class="space-y-2 flex flex-col">
<DurationHumanInput
v-model:start="start"
v-model:end="end"
name="Duration"></DurationHumanInput>
<div v-if="showHint" class="text-sm flex space-x-1">
<InformationCircleIcon
class="w-4 shrink-0 text-text-quaternary"></InformationCircleIcon>
<span class="text-text-secondary text-xs">
You can type natural language like
<span class="font-semibold"> 2h 30m</span>
</span>
</div>
</div>
</Field>
<Field>
<FieldLabel>Start</FieldLabel>
<div class="flex flex-col gap-2">
<TimePickerSimple v-model="start" class="w-full"></TimePickerSimple>
<DatePicker
v-model="start"
:size="datePickerSize"
class="w-full"
tabindex="1"></DatePicker>
</div>
</Field>
<Field>
<FieldLabel>End</FieldLabel>
<div class="flex flex-col gap-2">
<TimePickerSimple v-model="end" class="w-full"></TimePickerSimple>
<DatePicker
v-model="end"
:size="datePickerSize"
class="w-full"
tabindex="1"></DatePicker>
</div>
</Field>
</div>
</template>

View File

@@ -1,9 +1,8 @@
<script setup lang="ts">
import TimeTrackerTagDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerTagDropdown.vue';
import TimeTrackerStartStop from '@/packages/ui/src/TimeTrackerStartStop.vue';
import TimeTrackerRangeSelector from '@/packages/ui/src/TimeTracker/TimeTrackerRangeSelector.vue';
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import TimeTrackerEntryInput from '@/packages/ui/src/TimeTracker/TimeTrackerEntryInput.vue';
import TimeTrackerProjectControls from '@/packages/ui/src/TimeTracker/TimeTrackerProjectControls.vue';
import type {
CreateClientBody,
CreateProjectBody,
@@ -13,35 +12,45 @@ import type {
TimeEntry,
Client,
} from '@/packages/api/src';
import { computed, nextTick, ref, watch } from 'vue';
import { nextTick, ref, watch } from 'vue';
import type { Dayjs } from 'dayjs';
import { useFocus } from '@vueuse/core';
import { autoUpdate, flip, limitShift, offset, shift, useFloating } from '@floating-ui/vue';
import TimeTrackerRecentlyTrackedEntry from '@/packages/ui/src/TimeTracker/TimeTrackerRecentlyTrackedEntry.vue';
import { useSelectEvents } from '@/packages/ui/src/utils/select';
import { Coffee, Play } from '@lucide/vue';
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', {
required: true,
});
const liveTimer = defineModel<Dayjs | null>('liveTimer', { required: true });
const currentTimeEntryDescriptionInput = ref<HTMLInputElement | null>(null);
const props = defineProps<{
projects: Project[];
tasks: Task[];
tags: Tag[];
clients: Client[];
timeEntries: TimeEntry[];
createTag: (name: string) => Promise<Tag | undefined>;
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
isActive: boolean;
currency: string;
organizationBillableRate: number | null;
enableEstimatedTime: boolean;
canCreateProject: boolean;
}>();
const props = withDefaults(
defineProps<{
projects: Project[];
tasks: Task[];
tags: Tag[];
clients: Client[];
timeEntries: TimeEntry[];
createTag: (name: string) => Promise<Tag | undefined>;
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
isActive: boolean;
currency: string;
organizationBillableRate: number | null;
enableEstimatedTime: boolean;
canCreateProject: boolean;
isOnBreak?: boolean;
breaksEnabled?: boolean;
canResumeAfterBreak?: boolean;
resumeDescription?: string | null;
timeTrackerMode?: TimeTrackerMode;
}>(),
{
isOnBreak: false,
breaksEnabled: false,
canResumeAfterBreak: false,
resumeDescription: null,
timeTrackerMode: 'project',
}
);
const emit = defineEmits<{
startTimer: [];
@@ -50,251 +59,136 @@ const emit = defineEmits<{
startLiveTimer: [];
stopLiveTimer: [];
createTimeEntry: [];
startBreak: [];
resumeAfterBreak: [];
}>();
function updateProject() {
setBillableDefaultForProject();
emit('updateTimeEntry');
}
function setAndStartTimer(timeEntry: TimeEntry) {
setCurrentTimeEntry(timeEntry);
if (!props.isActive) {
emit('startTimer');
} else {
emit('updateTimeEntry');
}
}
function setCurrentTimeEntry(timeEntry: TimeEntry) {
currentTimeEntry.value.description = timeEntry.description;
currentTimeEntry.value.project_id = timeEntry.project_id;
currentTimeEntry.value.task_id = timeEntry.task_id;
currentTimeEntry.value.tags = timeEntry.tags;
currentTimeEntry.value.billable = timeEntry.billable;
}
function startTimerIfNotActive() {
if (highlightedDropdownEntryId.value) {
const timeEntry = filteredRecentlyTrackedTimeEntries.value.find(
(item) => item.id === highlightedDropdownEntryId.value
);
if (timeEntry) {
setCurrentTimeEntry(timeEntry);
showDropdown.value = false;
}
} else {
currentTimeEntry.value.description = tempDescription.value;
}
if (!props.isActive) {
emit('startTimer');
} else {
emit('updateTimeEntry');
}
}
function setBillableDefaultForProject() {
const project = props.projects.find(
(project) => project.id === currentTimeEntry.value.project_id
);
if (project) {
currentTimeEntry.value.billable = project.is_billable;
}
}
const blockRefocus = ref(false);
const entryInput = ref<InstanceType<typeof TimeTrackerEntryInput> | null>(null);
function onToggleButtonPress(newState: boolean) {
if (newState) {
emit('startTimer');
if (!blockRefocus.value) {
currentTimeEntryDescriptionInput.value?.focus();
}
entryInput.value?.focusAfterStart();
} else {
emit('stopTimer');
}
}
const tempDescription = ref(currentTimeEntry.value.description);
watch(
() => currentTimeEntry.value.description,
() => {
tempDescription.value = currentTimeEntry.value.description;
}
);
function updateTimeEntryDescription() {
if (currentTimeEntry.value.description !== tempDescription.value) {
currentTimeEntry.value.description = tempDescription.value;
emit('updateTimeEntry');
}
// Pressing Enter in the range selector starts the timer, same as in the description input.
function onRangeEnter() {
entryInput.value?.submit();
}
const filteredRecentlyTrackedTimeEntries = computed(() => {
// do not include running time entries
const finishedTimeEntries = props.timeEntries.filter((item) => item.end !== null);
// filter out duplicates based on description, task, project, tags and billable
const nonDuplicateTimeEntries = finishedTimeEntries.filter((item, index, self) => {
return (
index ===
self.findIndex(
(t) =>
t.description === item.description &&
t.task_id === item.task_id &&
t.project_id === item.project_id &&
t.tags.length === item.tags.length &&
t.tags.every((tag) => item.tags.includes(tag)) &&
t.billable === item.billable
)
);
});
// filter time entries based on current description
return nonDuplicateTimeEntries
.filter((item) => {
return item.description
?.toLowerCase()
?.includes(tempDescription.value?.toLowerCase()?.trim() || '');
})
.slice(0, 5);
});
const showDropdown = ref(false);
const { focused } = useFocus(currentTimeEntryDescriptionInput);
watch(focused, (focused) => {
nextTick(() => {
// make sure the click event on the dropdown does not get interrupted
showDropdown.value = focused;
// make sure that the input does not get refocused after the dropdown is closed
if (!focused) {
blockRefocus.value = true;
setTimeout(() => {
blockRefocus.value = false;
}, 100);
// After a break ends the tracker returns to the idle input; focus it so a fresh
// entry is just type + Enter.
watch(
() => props.isOnBreak,
async (isOnBreak, wasOnBreak) => {
if (wasOnBreak && !isOnBreak) {
await nextTick();
entryInput.value?.focusAfterStart();
}
});
});
const floating = ref(null);
const { floatingStyles } = useFloating(currentTimeEntryDescriptionInput, floating, {
placement: 'bottom-start',
whileElementsMounted: autoUpdate,
middleware: [
offset(10),
shift({
limiter: limitShift({
offset: 5,
}),
}),
flip({
fallbackAxisSideDirection: 'start',
}),
],
});
const highlightedDropdownEntryId = ref<string | null>(null);
useSelectEvents(
filteredRecentlyTrackedTimeEntries,
highlightedDropdownEntryId,
(item) => item.id,
showDropdown
}
);
</script>
<template>
<div class="flex items-center relative @container" data-testid="dashboard_timer">
<div
class="flex flex-col @2xl:flex-row w-full justify-between rounded-lg bg-card-background border-card-border border transition shadow-card">
class="flex flex-col @2xl:flex-row w-full justify-between rounded-lg border transition shadow-card"
:class="
isOnBreak
? 'bg-amber-500/10 border-amber-500/30'
: 'bg-card-background border-card-border'
">
<div class="flex flex-1 items-center relative">
<input
ref="currentTimeEntryDescriptionInput"
v-model="tempDescription"
placeholder="What are you working on?"
data-testid="time_entry_description"
class="w-full rounded-l-lg py-4 sm:py-2.5 px-3.5 border-b border-b-card-background-separator @2xl:px-4 text-base text-text-primary bg-transparent border-none placeholder-text-secondary focus:ring-0 transition"
type="text"
@keydown.enter="startTimerIfNotActive"
@keydown.esc="showDropdown = false"
@blur="updateTimeEntryDescription" />
<div class="@2xl:hidden pr-3 shrink-0">
<div
v-if="isOnBreak"
class="flex w-full items-center gap-2 py-4 sm:py-2.5 px-3.5 @2xl:px-4 text-base font-medium text-amber-600 dark:text-amber-400">
<Coffee class="w-5 h-5 shrink-0" />
<span>On break</span>
</div>
<TimeTrackerEntryInput
v-else
ref="entryInput"
v-model:current-time-entry="currentTimeEntry"
:time-entries="timeEntries"
:projects="projects"
:tasks="tasks"
:is-active="isActive"
@start-timer="emit('startTimer')"
@update-time-entry="emit('updateTimeEntry')"></TimeTrackerEntryInput>
<div class="@2xl:hidden pr-3 shrink-0 flex items-center space-x-2">
<button
v-if="breaksEnabled && !isOnBreak && isActive"
type="button"
title="Take a break"
aria-label="Take a break"
class="flex items-center justify-center w-8 h-8 rounded-full bg-quaternary text-text-tertiary hover:text-amber-500 focus:ring-2 focus:ring-border-tertiary transition"
@click="emit('startBreak')">
<Coffee class="w-4 h-4" />
</button>
<TimeTrackerStartStop
:active="isActive"
:variant="isOnBreak ? 'break' : 'primary'"
@changed="onToggleButtonPress"></TimeTrackerStartStop>
</div>
<div
v-if="showDropdown && filteredRecentlyTrackedTimeEntries.length > 0"
ref="floating"
class="z-50 w-[min(640px,100vw-2rem)]"
:style="floatingStyles">
<div
class="rounded-lg w-full border border-card-border overflow-hidden shadow-dropdown bg-card-background">
<div
class="text-text-tertiary text-xs font-semibold border-b border-border-tertiary px-2 py-1.5">
Recently Tracked Time Entries
</div>
<div class="text-text-secondary py-1 px-1.5">
<TimeTrackerRecentlyTrackedEntry
v-for="timeEntry in filteredRecentlyTrackedTimeEntries"
:key="timeEntry.id"
:time-entry="timeEntry"
:highlighted="highlightedDropdownEntryId === timeEntry.id"
:projects="projects"
:tasks="tasks"
@mousedown="setAndStartTimer(timeEntry)"
@mouseenter="
highlightedDropdownEntryId = timeEntry.id
"></TimeTrackerRecentlyTrackedEntry>
</div>
</div>
</div>
</div>
<div class="flex items-center justify-between pl-2 shrink min-w-0">
<div class="flex items-center w-[130px] @2xl:w-auto shrink min-w-0">
<TimeTrackerProjectTaskDropdown
v-model:project="currentTimeEntry.project_id"
v-model:task="currentTimeEntry.task_id"
variant="outline"
:create-client
:can-create-project
:clients
:create-project
:currency="currency"
:organization-billable-rate="organizationBillableRate"
:projects="projects"
:tasks="tasks"
:enable-estimated-time="enableEstimatedTime"
@changed="updateProject"></TimeTrackerProjectTaskDropdown>
</div>
<div class="flex items-center space-x-0 @4xl:space-x-2 px-2 @4xl:px-4 shrink-0">
<TimeTrackerTagDropdown
v-model="currentTimeEntry.tags"
:create-tag
:tags="tags"
@changed="$emit('updateTimeEntry')"></TimeTrackerTagDropdown>
<BillableToggleButton
v-model="currentTimeEntry.billable"
@changed="$emit('updateTimeEntry')"></BillableToggleButton>
</div>
<div class="border-l border-card-border">
<TimeTrackerProjectControls
v-if="!isOnBreak && timeTrackerMode !== 'simple'"
v-model:current-time-entry="currentTimeEntry"
:projects="projects"
:tasks="tasks"
:tags="tags"
:clients="clients"
:create-tag="createTag"
:create-project="createProject"
:create-client="createClient"
:currency="currency"
:organization-billable-rate="organizationBillableRate"
:enable-estimated-time="enableEstimatedTime"
:can-create-project="canCreateProject"
@update-time-entry="emit('updateTimeEntry')"></TimeTrackerProjectControls>
<button
v-if="isOnBreak && canResumeAfterBreak"
type="button"
class="mx-2 flex min-w-0 shrink items-center gap-1.5 h-8 px-3 rounded-md bg-transparent border border-amber-500/40 hover:bg-amber-500/15 text-sm font-medium text-amber-600 dark:text-amber-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-amber-500 transition"
@click="emit('resumeAfterBreak')">
<Play class="w-4 h-4 shrink-0" />
<span class="truncate">{{
resumeDescription ? `Resume "${resumeDescription}"` : 'Resume'
}}</span>
</button>
<div
class="border-l"
:class="isOnBreak ? 'border-amber-500/40' : 'border-card-border'">
<TimeTrackerRangeSelector
v-model:current-time-entry="currentTimeEntry"
v-model:live-timer="liveTimer"
:is-on-break="isOnBreak"
@start-live-timer="emit('startLiveTimer')"
@stop-live-timer="emit('stopLiveTimer')"
@update-timer="emit('updateTimeEntry')"
@start-timer="emit('startTimer')"
@create-time-entry="emit('createTimeEntry')"
@keydown.enter="startTimerIfNotActive"></TimeTrackerRangeSelector>
@keydown.enter="onRangeEnter"></TimeTrackerRangeSelector>
</div>
</div>
</div>
<div class="pl-4 @2xl:pl-6 pr-3 hidden @2xl:block">
<div class="pl-4 @2xl:pl-6 pr-3 hidden @2xl:flex items-center space-x-3">
<button
v-if="breaksEnabled && !isOnBreak && isActive"
type="button"
title="Take a break"
aria-label="Take a break"
class="flex items-center justify-center w-9 h-9 rounded-full bg-quaternary text-text-tertiary hover:text-amber-500 focus:ring-2 focus:ring-border-tertiary transition"
@click="emit('startBreak')">
<Coffee class="w-5 h-5" />
</button>
<TimeTrackerStartStop
:active="isActive"
:variant="isOnBreak ? 'break' : 'primary'"
size="large"
@changed="onToggleButtonPress"></TimeTrackerStartStop>
</div>

View File

@@ -0,0 +1,200 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { useFocus } from '@vueuse/core';
import { autoUpdate, flip, limitShift, offset, shift, useFloating } from '@floating-ui/vue';
import TimeTrackerRecentlyTrackedEntry from '@/packages/ui/src/TimeTracker/TimeTrackerRecentlyTrackedEntry.vue';
import { useSelectEvents } from '@/packages/ui/src/utils/select';
import type { Project, Task, TimeEntry } from '@/packages/api/src';
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', { required: true });
const props = defineProps<{
timeEntries: TimeEntry[];
projects: Project[];
tasks: Task[];
isActive: boolean;
}>();
const emit = defineEmits<{ startTimer: []; updateTimeEntry: [] }>();
const currentTimeEntryDescriptionInput = ref<HTMLInputElement | null>(null);
const tempDescription = ref(currentTimeEntry.value.description);
watch(
() => currentTimeEntry.value.description,
() => {
tempDescription.value = currentTimeEntry.value.description;
}
);
function updateTimeEntryDescription() {
if (currentTimeEntry.value.description !== tempDescription.value) {
currentTimeEntry.value.description = tempDescription.value;
emit('updateTimeEntry');
}
}
function setCurrentTimeEntry(timeEntry: TimeEntry) {
currentTimeEntry.value.description = timeEntry.description;
currentTimeEntry.value.project_id = timeEntry.project_id;
currentTimeEntry.value.task_id = timeEntry.task_id;
currentTimeEntry.value.tags = timeEntry.tags;
currentTimeEntry.value.billable = timeEntry.billable;
currentTimeEntry.value.type = timeEntry.type;
}
function setAndStartTimer(timeEntry: TimeEntry) {
setCurrentTimeEntry(timeEntry);
if (!props.isActive) {
emit('startTimer');
} else {
emit('updateTimeEntry');
}
}
// Starts the timer from the description input / range selector Enter: picks the highlighted
// recently-tracked entry if one is active, otherwise commits the typed description.
function submit() {
if (highlightedDropdownEntryId.value) {
const timeEntry = filteredRecentlyTrackedTimeEntries.value.find(
(item) => item.id === highlightedDropdownEntryId.value
);
if (timeEntry) {
setCurrentTimeEntry(timeEntry);
showDropdown.value = false;
}
} else {
currentTimeEntry.value.description = tempDescription.value;
}
if (!props.isActive) {
emit('startTimer');
} else {
emit('updateTimeEntry');
}
}
const filteredRecentlyTrackedTimeEntries = computed(() => {
// do not include running time entries and breaks (breaks are started via the break button)
const finishedTimeEntries = props.timeEntries.filter(
(item) => item.end !== null && item.type !== 'break'
);
// filter out duplicates based on description, task, project, tags and billable
const nonDuplicateTimeEntries = finishedTimeEntries.filter((item, index, self) => {
return (
index ===
self.findIndex(
(t) =>
t.description === item.description &&
t.task_id === item.task_id &&
t.project_id === item.project_id &&
t.tags.length === item.tags.length &&
t.tags.every((tag) => item.tags.includes(tag)) &&
t.billable === item.billable
)
);
});
// filter time entries based on current description
return nonDuplicateTimeEntries
.filter((item) => {
return item.description
?.toLowerCase()
?.includes(tempDescription.value?.toLowerCase()?.trim() || '');
})
.slice(0, 5);
});
const showDropdown = ref(false);
const blockRefocus = ref(false);
const { focused } = useFocus(currentTimeEntryDescriptionInput);
watch(focused, (focused) => {
nextTick(() => {
// make sure the click event on the dropdown does not get interrupted
showDropdown.value = focused;
// make sure that the input does not get refocused after the dropdown is closed
if (!focused) {
blockRefocus.value = true;
setTimeout(() => {
blockRefocus.value = false;
}, 100);
}
});
});
const floating = ref(null);
const { floatingStyles } = useFloating(currentTimeEntryDescriptionInput, floating, {
placement: 'bottom-start',
whileElementsMounted: autoUpdate,
middleware: [
offset(10),
shift({
limiter: limitShift({
offset: 5,
}),
}),
flip({
fallbackAxisSideDirection: 'start',
}),
],
});
const highlightedDropdownEntryId = ref<string | null>(null);
useSelectEvents(
filteredRecentlyTrackedTimeEntries,
highlightedDropdownEntryId,
(item) => item.id,
showDropdown
);
// Called by the shell after the start/stop button starts a timer, so typing can continue.
function focusAfterStart() {
if (!blockRefocus.value) {
currentTimeEntryDescriptionInput.value?.focus();
}
}
defineExpose({ submit, focusAfterStart });
</script>
<template>
<input
ref="currentTimeEntryDescriptionInput"
v-model="tempDescription"
placeholder="What are you working on?"
data-testid="time_entry_description"
class="w-full rounded-l-lg py-4 sm:py-2.5 px-3.5 border-b border-b-card-background-separator @2xl:px-4 text-base text-text-primary bg-transparent border-none placeholder-text-secondary focus:ring-0 transition"
type="text"
@keydown.enter="submit"
@keydown.esc="showDropdown = false"
@blur="updateTimeEntryDescription" />
<div
v-if="showDropdown && filteredRecentlyTrackedTimeEntries.length > 0"
ref="floating"
class="z-50 w-[min(640px,100vw-2rem)]"
:style="floatingStyles">
<div
class="rounded-lg w-full border border-card-border overflow-hidden shadow-dropdown bg-card-background">
<div
class="text-text-tertiary text-xs font-semibold border-b border-border-tertiary px-2 py-1.5">
Recently Tracked Time Entries
</div>
<div class="text-text-secondary py-1 px-1.5">
<TimeTrackerRecentlyTrackedEntry
v-for="timeEntry in filteredRecentlyTrackedTimeEntries"
:key="timeEntry.id"
:time-entry="timeEntry"
:highlighted="highlightedDropdownEntryId === timeEntry.id"
:projects="projects"
:tasks="tasks"
@mousedown="setAndStartTimer(timeEntry)"
@mouseenter="
highlightedDropdownEntryId = timeEntry.id
"></TimeTrackerRecentlyTrackedEntry>
</div>
</div>
</div>
</template>

View File

@@ -1,14 +1,28 @@
<script setup lang="ts">
import { PlusIcon, XMarkIcon } from '@heroicons/vue/20/solid';
import { PlusIcon, XMarkIcon, ClockIcon } from '@heroicons/vue/20/solid';
import { Coffee } from '@lucide/vue';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '..';
import type { TimeTrackerMode } from '@/packages/ui/src/TimeTracker/types';
const props = defineProps<{
hasActiveTimer: boolean;
}>();
const props = withDefaults(
defineProps<{
hasActiveTimer: boolean;
timeTrackerMode?: TimeTrackerMode;
breaksEnabled?: boolean;
isOnBreak?: boolean;
}>(),
{
timeTrackerMode: 'project',
breaksEnabled: false,
isOnBreak: false,
}
);
const emit = defineEmits<{
manualEntry: [];
startBreak: [];
discard: [];
toggleTimeTrackerMode: [];
}>();
</script>
@@ -39,6 +53,23 @@ const emit = defineEmits<{
<PlusIcon class="w-5" />
<span>Manual time entry</span>
</DropdownMenuItem>
<DropdownMenuItem
v-if="props.breaksEnabled && !props.isOnBreak"
class="flex items-center space-x-3 cursor-pointer"
@click="emit('startBreak')">
<Coffee class="w-5" />
<span>Start Break</span>
</DropdownMenuItem>
<DropdownMenuItem
class="flex items-center space-x-3 cursor-pointer"
@click="emit('toggleTimeTrackerMode')">
<ClockIcon class="w-5" />
<span>{{
props.timeTrackerMode === 'simple'
? 'Switch to project mode'
: 'Switch to simple mode'
}}</span>
</DropdownMenuItem>
<DropdownMenuItem
v-if="props.hasActiveTimer"
class="flex items-center space-x-3 cursor-pointer text-destructive focus:text-destructive"

View File

@@ -0,0 +1,56 @@
import { shallowMount } from '@vue/test-utils';
import { describe, expect, it, vi } from 'vitest';
import { nextTick } from 'vue';
import TimeTrackerProjectControls from './TimeTrackerProjectControls.vue';
import TimeTrackerProjectTaskDropdown from './TimeTrackerProjectTaskDropdown.vue';
import type { Project, TimeEntry } from '@/packages/api/src';
function timeEntry(overrides: Partial<TimeEntry> = {}): TimeEntry {
return {
id: 'te-1',
description: '',
start: '2026-07-14T09:00:00Z',
end: null,
duration: null,
project_id: null,
task_id: null,
organization_id: 'org-1',
user_id: 'user-1',
tags: [],
billable: false,
type: 'work',
...overrides,
} as TimeEntry;
}
describe('TimeTrackerProjectControls', () => {
it('adopts the billable default of a newly selected project', async () => {
const current = timeEntry({ project_id: null, billable: false });
const billableProject = { id: 'p-1', is_billable: true } as Project;
const wrapper = shallowMount(TimeTrackerProjectControls, {
props: {
currentTimeEntry: current,
projects: [billableProject],
tasks: [],
tags: [],
clients: [],
createTag: vi.fn(),
createProject: vi.fn(),
createClient: vi.fn(),
currency: 'EUR',
organizationBillableRate: null,
enableEstimatedTime: false,
canCreateProject: false,
},
});
const dropdown = wrapper.findComponent(TimeTrackerProjectTaskDropdown);
// The dropdown sets the project via v-model, then emits `changed`.
dropdown.vm.$emit('update:project', 'p-1');
dropdown.vm.$emit('changed');
await nextTick();
expect(current.billable).toBe(true);
expect(wrapper.emitted('updateTimeEntry')).toBeTruthy();
});
});

View File

@@ -0,0 +1,70 @@
<script setup lang="ts">
import TimeTrackerProjectTaskDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerProjectTaskDropdown.vue';
import TimeTrackerTagDropdown from '@/packages/ui/src/TimeTracker/TimeTrackerTagDropdown.vue';
import BillableToggleButton from '@/packages/ui/src/Input/BillableToggleButton.vue';
import type {
Client,
CreateClientBody,
CreateProjectBody,
Project,
Tag,
Task,
TimeEntry,
} from '@/packages/api/src';
const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', { required: true });
const props = defineProps<{
projects: Project[];
tasks: Task[];
tags: Tag[];
clients: Client[];
createTag: (name: string) => Promise<Tag | undefined>;
createProject: (project: CreateProjectBody) => Promise<Project | undefined>;
createClient: (client: CreateClientBody) => Promise<Client | undefined>;
currency: string;
organizationBillableRate: number | null;
enableEstimatedTime: boolean;
canCreateProject: boolean;
}>();
const emit = defineEmits<{ updateTimeEntry: [] }>();
function updateProject() {
// Adopt the project's billable default when a project is picked.
const project = props.projects.find((p) => p.id === currentTimeEntry.value.project_id);
if (project) {
currentTimeEntry.value.billable = project.is_billable;
}
emit('updateTimeEntry');
}
</script>
<template>
<div class="flex items-center w-[130px] @2xl:w-auto shrink min-w-0">
<TimeTrackerProjectTaskDropdown
v-model:project="currentTimeEntry.project_id"
v-model:task="currentTimeEntry.task_id"
variant="outline"
:create-client="createClient"
:can-create-project="canCreateProject"
:clients="clients"
:create-project="createProject"
:currency="currency"
:organization-billable-rate="organizationBillableRate"
:projects="projects"
:tasks="tasks"
:enable-estimated-time="enableEstimatedTime"
@changed="updateProject"></TimeTrackerProjectTaskDropdown>
</div>
<div class="flex items-center space-x-0 @4xl:space-x-2 px-2 @4xl:px-4 shrink-0">
<TimeTrackerTagDropdown
v-model="currentTimeEntry.tags"
:create-tag="createTag"
:tags="tags"
@changed="emit('updateTimeEntry')"></TimeTrackerTagDropdown>
<BillableToggleButton
v-model="currentTimeEntry.billable"
@changed="emit('updateTimeEntry')"></BillableToggleButton>
</div>
</template>

View File

@@ -694,8 +694,8 @@ const showCreateProject = ref(false);
class="flex items-center space-x-2 w-full px-5 py-1.5 text-start text-xs font-semibold leading-5 text-text-primary focus:outline-none transition duration-150 ease-in-out"
:class="
row.task.id === highlightedItemId
? 'bg-card-background-active'
: 'bg-quaternary'
? 'bg-quaternary dark:bg-tertiary'
: 'bg-tertiary dark:bg-quaternary'
"
@click="selectTask(row.task.id)"
@mouseenter="setHighlightItemId(row.task.id)">

View File

@@ -11,6 +11,15 @@ const currentTimeEntry = defineModel<TimeEntry>('currentTimeEntry', {
});
const now = defineModel<null | Dayjs>('liveTimer');
withDefaults(
defineProps<{
isOnBreak?: boolean;
}>(),
{
isOnBreak: false,
}
);
const emit = defineEmits<{
startLiveTimer: [];
stopLiveTimer: [];
@@ -154,7 +163,12 @@ function closeAndFocusInput() {
v-model="currentTime"
placeholder="00:00:00"
data-testid="time_entry_time"
class="w-[110px] lg:w-[120px] h-full text-text-primary py-2.5 rounded-lg border-border-secondary border text-center px-4 text-base font-semibold bg-card-background border-none placeholder-text-tertiary focus:ring-0 transition"
class="w-[110px] lg:w-[120px] h-full py-2.5 rounded-lg text-center px-4 text-base font-semibold placeholder-text-tertiary focus:ring-0 transition"
:class="
isOnBreak
? 'text-amber-600 dark:text-amber-400 bg-transparent border-none'
: 'text-text-primary bg-card-background border-border-secondary border border-none'
"
type="text"
@focusin="openModalOnTab"
@click="openModalOnClick"

View File

@@ -0,0 +1,6 @@
/**
* How the time tracker presents its controls. `project` shows the full
* project/task/tag/billable controls; `simple` hides them for plain
* description-only tracking. Persisted client-side as a UI preference.
*/
export type TimeTrackerMode = 'project' | 'simple';

View File

@@ -11,6 +11,7 @@ const timeTrackerVariants = cva(
'text-white ring-accent-200/10 focus-visible:ring-ring focus-visible:ring-2 ring-4 sm:ring-[6px]',
secondary:
'bg-quaternary text-text-tertiary hover:text-text-primary focus:ring-2 focus:ring-border-tertiary',
break: 'text-white ring-amber-200/10 focus-visible:ring-ring focus-visible:ring-2 ring-4 sm:ring-[6px]',
},
size: {
small: 'w-6 h-6',
@@ -33,6 +34,16 @@ const timeTrackerVariants = cva(
active: false,
class: 'bg-accent-300/70 hover:bg-accent-400/70 focus:bg-accent-700',
},
{
variant: 'break',
active: true,
class: 'bg-amber-500/80 hover:bg-amber-600/80 focus:bg-amber-600/80',
},
{
variant: 'break',
active: false,
class: 'bg-accent-300/70 hover:bg-accent-400/70 focus:bg-accent-700',
},
],
defaultVariants: {
variant: 'primary',

View File

@@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest';
import type { TimeEntry } from '@/packages/api/src';
import {
findMisplacedBreak,
type BreakPlacementHint,
} from '@/packages/ui/src/utils/breakPlacement';
// Decision logic behind the aggregate (collapsed grouped-break) row's placement
// warning: the row shows the hint — and navigates the calendar — based on the
// first misplaced break in the group.
function breakEntry(id: string): TimeEntry {
return { id, type: 'break', start: '2026-07-14T10:00:00Z' } as TimeEntry;
}
function hint(misplaced: boolean): BreakPlacementHint {
return {
misplaced,
previousWorkEnd: null,
nextWorkStart: null,
gapBeforeSeconds: null,
gapAfterSeconds: null,
};
}
describe('findMisplacedBreak', () => {
it('returns the first misplaced break in a group', () => {
const entries = [breakEntry('break-a'), breakEntry('break-b')];
const result = findMisplacedBreak(entries, {
'break-a': hint(false),
'break-b': hint(true),
});
expect(result?.id).toBe('break-b');
});
it('returns null when no break in the group is misplaced', () => {
const entries = [breakEntry('break-a'), breakEntry('break-b')];
const result = findMisplacedBreak(entries, {
'break-a': hint(false),
'break-b': hint(false),
});
expect(result).toBeNull();
});
it('returns null when the group has no placement hints', () => {
const entries = [breakEntry('break-a'), breakEntry('break-b')];
expect(findMisplacedBreak(entries, {})).toBeNull();
});
it('ignores hints for entries that are not in the group', () => {
const entries = [breakEntry('break-a')];
const result = findMisplacedBreak(entries, {
'break-a': hint(false),
'break-elsewhere': hint(true),
});
expect(result).toBeNull();
});
});

View File

@@ -0,0 +1,102 @@
import type { TimeEntry } from '@/packages/api/src';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
export interface BreakPlacementHint {
misplaced: boolean;
// Closest work end at or before the break start (null if none is known)
previousWorkEnd: string | null;
// Closest work start at or after the break end (null if none is known)
nextWorkStart: string | null;
gapBeforeSeconds: number | null;
gapAfterSeconds: number | null;
}
// How far a break may sit from the nearest work entry before it gets a placement hint
export const BREAK_GAP_TOLERANCE_MINUTES = 30;
/**
* Grouped breaks collapse into a single summary row, so the row needs to know
* whether any break in the group is misplaced (to show the warning) and which
* one to navigate to (all grouped entries share the same day). Returns the first
* misplaced break in the group, or null when none is flagged.
*/
export function findMisplacedBreak(
entries: TimeEntry[],
hints: Record<string, BreakPlacementHint | null>
): TimeEntry | null {
return entries.find((entry) => hints[entry.id]?.misplaced) ?? null;
}
/**
* A break only means something between work. This computes how far a break
* sits from the nearest work entry on either side — everything non-work
* (untracked gaps and other breaks) counts as distance. If either side has
* more than the tolerated gap (or no work at all), the break gets a hint.
*
* Non-blocking by design: placement can not be validated at write time
* (it depends on entries that may not exist yet), so it is derived at read
* time from the loaded entries.
*/
export function getBreakPlacementHint(
breakEntry: TimeEntry,
allEntries: TimeEntry[]
): BreakPlacementHint | null {
if (breakEntry.type !== 'break') {
return null;
}
const dayjs = getDayJsInstance();
const breakStart = dayjs.utc(breakEntry.start);
const breakEnd = breakEntry.end === null ? dayjs.utc() : dayjs.utc(breakEntry.end);
const toleranceSeconds = BREAK_GAP_TOLERANCE_MINUTES * 60;
let previousWorkEnd: ReturnType<typeof dayjs> | null = null;
let nextWorkStart: ReturnType<typeof dayjs> | null = null;
for (const entry of allEntries) {
if (entry.type === 'break' || entry.id === breakEntry.id) {
continue;
}
const entryStart = dayjs.utc(entry.start);
const entryEnd = entry.end === null ? dayjs.utc() : dayjs.utc(entry.end);
// Work overlapping the break counts as touching on both sides
if (entryEnd.isAfter(breakStart) && entryStart.isBefore(breakEnd)) {
return {
misplaced: false,
previousWorkEnd: entryEnd.format(),
nextWorkStart: entryStart.format(),
gapBeforeSeconds: 0,
gapAfterSeconds: 0,
};
}
if (!entryEnd.isAfter(breakStart)) {
if (previousWorkEnd === null || entryEnd.isAfter(previousWorkEnd)) {
previousWorkEnd = entryEnd;
}
}
if (!entryStart.isBefore(breakEnd)) {
if (nextWorkStart === null || entryStart.isBefore(nextWorkStart)) {
nextWorkStart = entryStart;
}
}
}
const gapBeforeSeconds =
previousWorkEnd !== null ? breakStart.diff(previousWorkEnd, 'second') : null;
const gapAfterSeconds = nextWorkStart !== null ? nextWorkStart.diff(breakEnd, 'second') : null;
// A running break has no "after" side yet — only judge the before side
const isRunning = breakEntry.end === null;
const beforeMisplaced = gapBeforeSeconds === null || gapBeforeSeconds > toleranceSeconds;
const afterMisplaced =
!isRunning && (gapAfterSeconds === null || gapAfterSeconds > toleranceSeconds);
return {
misplaced: beforeMisplaced || afterMisplaced,
previousWorkEnd: previousWorkEnd?.format() ?? null,
nextWorkStart: nextWorkStart?.format() ?? null,
gapBeforeSeconds,
gapAfterSeconds,
};
}

View File

@@ -0,0 +1,19 @@
import { computed, inject, type ComputedRef } from 'vue';
import type { Organization } from '@/packages/api/src';
/**
* Whether break tracking is enabled for the current organization.
*
* Components below the app layout can call this with no argument (the layout
* provides `organization`); pages that sit above the layout pass their own
* organization ref. Without an organization (e.g. public report views) breaks
* count as disabled.
*/
export function useBreaksEnabled(organization?: {
value: Organization | undefined | null;
}): ComputedRef<boolean> {
const org =
organization ??
inject<ComputedRef<Organization | undefined> | undefined>('organization', undefined);
return computed(() => org?.value?.breaks_enabled ?? false);
}

View File

@@ -88,8 +88,8 @@
--theme-shadow-card: lch(0 0 0 / 0.022) 0px 3px 6px -2px, lch(0 0 0 / 0.044) 0px 1px 1px;
--theme-shadow-dropdown: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
--theme-color-row-background: var(--theme-color-primary);
--theme-color-row-heading-background: var(--theme-color-primary);
--theme-color-row-background: var(--color-bg-primary);
--theme-color-row-heading-background: var(--color-bg-primary);
--theme-color-row-heading-border: var(--color-border-tertiary);
--theme-color-icon-default: var(--color-text-quaternary);

View File

@@ -91,12 +91,13 @@ function prefetchDashboard(queryClient: QueryClient) {
prefetchTasks(queryClient);
// Prefetch all dashboard card data
// Must match the query in RecentlyTrackedTasksCard exactly — same key, same params
queryClient.prefetchQuery({
queryKey: ['timeEntries', organizationId],
queryFn: () =>
api.getTimeEntries({
params: { organization: organizationId },
queries: { limit: 10, offset: 0, only_full_dates: 'true' },
queries: { member_id: getCurrentMembershipId(), type: 'work' },
}),
staleTime: 30000,
});

View File

@@ -0,0 +1,490 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { describe, expect, it } from 'vitest';
import {
BREAK_GAP_TOLERANCE_SECONDS,
buildDayPlacementContext,
findValidBreakGap,
findValidBreakGapNear,
planMoveInsert,
planSplitEntry,
suggestMovePlan,
type MovableInterval,
} from './breakPlacementMath';
dayjs.extend(utc);
const HALF_HOUR = 1800;
const HOUR = 3600;
const DAY = '2026-07-14';
const dayStart = `${DAY}T00:00:00Z`;
const dayEnd = `${DAY}T24:00:00Z`;
function iv(startH: number, endH: number) {
const h = (n: number) => {
const totalMin = Math.round(n * 60);
const hh = Math.floor(totalMin / 60);
const mm = totalMin % 60;
return `${DAY}T${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:00Z`;
};
return { start: h(startH), end: h(endH) };
}
describe('findValidBreakGap', () => {
it('centers the break in a gap that fits within tolerance', () => {
// 09-12 and 13-17 → 1h gap, 30m break → centered at 12:15-12:45
const gap = findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR);
expect(gap).toEqual({ start: `${DAY}T12:15:00Z`, end: `${DAY}T12:45:00Z` });
});
it('rejects a gap that is too small for the break', () => {
// 09-12 and 12:15-17 → 15m gap, 30m break does not fit
expect(findValidBreakGap([iv(9, 12), iv(12.25, 17)], HALF_HOUR)).toBeNull();
});
it('places the break flush after work in an oversized gap instead of rejecting it', () => {
// 09-12 and 14-17 → 2h gap. No placement keeps both sides within tolerance,
// but the gap easily holds the break — place it flush after the first entry
// and leave the gap otherwise untouched (distance to work is only a soft hint).
expect(findValidBreakGap([iv(9, 12), iv(14, 17)], HALF_HOUR)).toEqual({
start: `${DAY}T12:00:00Z`,
end: `${DAY}T12:30:00Z`,
});
});
it('prefers a within-tolerance gap over an earlier oversized gap', () => {
// 09-10, 13-14, 15-16: the first gap (3h) is oversized, the second (1h) is
// valid → center in the second instead of going flush-left in the first.
expect(findValidBreakGap([iv(9, 10), iv(13, 14), iv(15, 16)], HALF_HOUR)).toEqual({
start: `${DAY}T14:15:00Z`,
end: `${DAY}T14:45:00Z`,
});
});
it('slides past an obstacle when placing into an oversized gap', () => {
// 09-12 and 16-17 with an existing break flush at 12:00 → the new break
// lands right after that break.
expect(findValidBreakGap([iv(9, 12), iv(16, 17)], HALF_HOUR, [iv(12, 12.75)])).toEqual({
start: `${DAY}T12:45:00Z`,
end: `${DAY}T13:15:00Z`,
});
});
it('does not fabricate a gap from an entry contained in a longer one', () => {
// 10-11 sits inside 09-17; the only real gap is 17:00-18:00 → centered there.
expect(findValidBreakGap([iv(9, 17), iv(10, 11), iv(18, 19)], HALF_HOUR)).toEqual({
start: `${DAY}T17:15:00Z`,
end: `${DAY}T17:45:00Z`,
});
});
it('accepts a gap exactly at duration + 2*tolerance', () => {
const gapEnd = 12 + (HALF_HOUR + 2 * BREAK_GAP_TOLERANCE_SECONDS) / HOUR;
const gap = findValidBreakGap([iv(9, 12), iv(gapEnd, gapEnd + 1)], HALF_HOUR);
expect(gap).not.toBeNull();
});
it('returns null when there is only one work entry', () => {
expect(findValidBreakGap([iv(9, 17)], HALF_HOUR)).toBeNull();
});
it('skips a gap already occupied by another break', () => {
// The only valid gap (12:1512:45) is taken by an existing break → no auto placement
expect(
findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR, [
{ start: `${DAY}T12:15:00Z`, end: `${DAY}T12:45:00Z` },
])
).toBeNull();
});
it('ignores obstacles that fall outside the chosen gap', () => {
expect(findValidBreakGap([iv(9, 12), iv(13, 17)], HALF_HOUR, [iv(20, 21)])).toEqual({
start: `${DAY}T12:15:00Z`,
end: `${DAY}T12:45:00Z`,
});
});
});
describe('planSplitEntry', () => {
it('splits a single entry and centers the break', () => {
const plan = planSplitEntry(iv(9, 17), HALF_HOUR);
expect(plan).not.toBeNull();
expect(plan!.firstHalf.start).toBe(`${DAY}T09:00:00Z`);
expect(plan!.breakSlot.start).toBe(plan!.firstHalf.end);
expect(plan!.secondHalf.start).toBe(plan!.breakSlot.end);
expect(plan!.secondHalf.end).toBe(`${DAY}T17:00:00Z`);
// break is 30m and centered → 12:45-13:15
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:45:00Z`, end: `${DAY}T13:15:00Z` });
});
it('honors an explicit break start', () => {
const plan = planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T10:00:00Z`);
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T10:00:00Z` });
expect(plan!.secondHalf.start).toBe(`${DAY}T10:30:00Z`);
});
it('returns null when the entry is too short to leave work on both sides', () => {
expect(planSplitEntry(iv(9, 9.25), HALF_HOUR)).toBeNull();
});
it('rejects an explicit break start before the entry instead of clamping it', () => {
// 07:00 lies before the 09:00-17:00 entry — relocating it silently would
// leave a hair-thin first fragment at a time the user never picked.
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T07:00:00Z`)).toBeNull();
});
it('rejects an explicit break start whose break would reach past the entry end', () => {
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T16:45:00Z`)).toBeNull();
});
it('rejects an explicit break start that leaves less than the minimum fragment', () => {
// 09:00:30 would leave only 30s of work before the break.
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T09:00:30Z`)).toBeNull();
});
it('accepts an explicit break start leaving exactly the minimum fragment on each side', () => {
// 09:01 leaves 60s before; on a 09:00-09:32 entry a 30m break also leaves 60s after.
const plan = planSplitEntry(iv(9, 9 + 32 / 60), HALF_HOUR, `${DAY}T09:01:00Z`);
expect(plan).not.toBeNull();
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T09:01:00Z` });
expect(plan!.secondHalf).toEqual({ start: `${DAY}T09:31:00Z`, end: `${DAY}T09:32:00Z` });
});
it('returns null when the entry cannot hold the break plus a minimum fragment per side', () => {
// 31 minutes of work cannot hold a 30m break with 60s of work on each side.
expect(planSplitEntry(iv(9, 9 + 31 / 60), HALF_HOUR)).toBeNull();
});
});
describe('planMoveInsert', () => {
const movable = (id: string, startH: number, endH: number): MovableInterval => ({
id,
...iv(startH, endH),
});
it('pushes the right block later to open a slot for the break', () => {
// Back-to-back 09-12 and 12-17. Insert 30m break at 12:00.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 12, 17)],
dayStart,
dayEnd,
`${DAY}T12:00:00Z`,
HALF_HOUR
);
expect(plan).not.toBeNull();
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
// 'a' untouched (not in shifted), 'b' shifted +30m
expect(plan!.shifted).toEqual([
{ id: 'b', start: `${DAY}T12:30:00Z`, end: `${DAY}T17:30:00Z` },
]);
});
it('leaves an oversized gap alone instead of pulling the right block flush', () => {
// 09-12 and 15-17 (3h gap). Break flush after first at 12:00 fits in the gap
// → nothing moves; the user's gap is preserved.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 15, 17)],
dayStart,
dayEnd,
`${DAY}T12:00:00Z`,
HALF_HOUR
);
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
expect(plan!.shifted).toEqual([]);
});
it('does not drag entries flush when the break sits mid-gap', () => {
// Break at 13:00 in the middle of the 12:00-15:00 gap → neither side moves.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 15, 17)],
dayStart,
dayEnd,
`${DAY}T13:00:00Z`,
HALF_HOUR
);
expect(plan!.shifted).toEqual([]);
});
it('shifts each side only as much as needed to clear the slot', () => {
// Break 14:45-15:15 overlaps only the start of 'b' → 'b' pushed 15m later,
// 'a' untouched.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 15, 17)],
dayStart,
dayEnd,
`${DAY}T14:45:00Z`,
HALF_HOUR
);
expect(plan!.shifted).toEqual([
{ id: 'b', start: `${DAY}T15:15:00Z`, end: `${DAY}T17:15:00Z` },
]);
});
it('pulls the left block earlier only when it overlaps the slot', () => {
// Break 11:45-12:15 overlaps the end of 'a' → 'a' pulled 15m earlier;
// 'b' (15-17) already clears the slot and stays put.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 15, 17)],
dayStart,
dayEnd,
`${DAY}T11:45:00Z`,
HALF_HOUR
);
expect(plan!.shifted).toEqual([
{ id: 'a', start: `${DAY}T08:45:00Z`, end: `${DAY}T11:45:00Z` },
]);
});
it('shifts the left block earlier when the right block cannot move within the day', () => {
// Right entry ends at 23:50; pushing it later would cross midnight, so the
// left block must move earlier instead.
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 12, 23 + 50 / 60)],
dayStart,
dayEnd,
`${DAY}T12:00:00Z`,
HALF_HOUR
);
// Not feasible by pushing right; solver returns null (caller lets the user pick another spot)
expect(plan).toBeNull();
});
it('returns null when the break itself would fall outside the day', () => {
expect(
planMoveInsert([movable('a', 9, 12)], dayStart, dayEnd, `${DAY}T23:50:00Z`, HALF_HOUR)
).toBeNull();
});
it('places a break between entries without shifting when they already have exactly the gap', () => {
const plan = planMoveInsert(
[movable('a', 9, 12), movable('b', 12.5, 17)],
dayStart,
dayEnd,
`${DAY}T12:00:00Z`,
HALF_HOUR
);
// gap is exactly 30m → 'b' already starts at break end, nothing to shift
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
expect(plan!.shifted).toEqual([]);
});
});
describe('suggestMovePlan', () => {
const movable = (id: string, startH: number, endH: number): MovableInterval => ({
id,
...iv(startH, endH),
});
it('finds a flush-after placement for back-to-back entries', () => {
const plan = suggestMovePlan(
[movable('a', 9, 12), movable('b', 12, 17)],
dayStart,
dayEnd,
HALF_HOUR
);
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
});
it('falls back to a flush-before placement when the day is nearly full at the end', () => {
// 09-12 and 12-23:50: pushing right past midnight is impossible, so the break
// is placed just before the second entry, pulling the first entry earlier.
const plan = suggestMovePlan(
[movable('a', 9, 12), movable('b', 12, 23 + 50 / 60)],
dayStart,
dayEnd,
HALF_HOUR
);
expect(plan).not.toBeNull();
expect(plan!.breakSlot).toEqual({ start: `${DAY}T11:30:00Z`, end: `${DAY}T12:00:00Z` });
// first entry pulled 30m earlier, second untouched
expect(plan!.shifted.find((s) => s.id === 'a')).toEqual({
id: 'a',
start: `${DAY}T08:30:00Z`,
end: `${DAY}T11:30:00Z`,
});
});
it('returns null when the day is completely full', () => {
const plan = suggestMovePlan([movable('a', 0, 24)], dayStart, dayEnd, HALF_HOUR);
expect(plan).toBeNull();
});
it('moves existing breaks along with the surrounding work', () => {
// Fully packed day: work 09-12, break 12-12:30, work 12:30-17. Opening a
// slot after the morning work pushes the existing break and the afternoon
// work later together — the plan never lands on top of the break.
const plan = suggestMovePlan(
[movable('a', 9, 12), movable('c', 12.5, 17)],
dayStart,
dayEnd,
HALF_HOUR,
[movable('x', 12, 12.5)]
);
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
expect([...plan!.shifted].sort((a, b) => a.id.localeCompare(b.id))).toEqual([
{ id: 'c', start: `${DAY}T13:00:00Z`, end: `${DAY}T17:30:00Z` },
{ id: 'x', start: `${DAY}T12:30:00Z`, end: `${DAY}T13:00:00Z` },
]);
});
});
describe('buildDayPlacementContext', () => {
const PREV_DAY = '2026-07-13';
const entry = (id: string, start: string, end: string | null, type = 'work') => ({
id,
start,
end,
type,
});
it('separates movable work and breaks fully inside the day', () => {
const ctx = buildDayPlacementContext(
[
entry('w1', `${DAY}T09:00:00Z`, `${DAY}T12:00:00Z`),
entry('b1', `${DAY}T12:00:00Z`, `${DAY}T12:30:00Z`, 'break'),
entry('w2', `${DAY}T13:00:00Z`, `${DAY}T17:00:00Z`),
],
dayStart,
dayEnd
);
expect(ctx.work.map((e) => e.id)).toEqual(['w1', 'w2']);
expect(ctx.breaks.map((e) => e.id)).toEqual(['b1']);
expect(ctx.dayStart).toBe(`${DAY}T00:00:00Z`);
// `T24:00` normalizes to the next day's midnight
expect(ctx.dayEnd).toBe(`2026-07-15T00:00:00Z`);
});
it('excludes the break being re-placed', () => {
const ctx = buildDayPlacementContext(
[entry('b1', `${DAY}T12:00:00Z`, `${DAY}T12:30:00Z`, 'break')],
dayStart,
dayEnd,
'b1'
);
expect(ctx.breaks).toEqual([]);
});
it('turns entries crossing midnight into walls that shrink the day window', () => {
// 22:00 (prev day) - 02:00 spills in; 23:00 - 01:00 (next day) spills out.
const ctx = buildDayPlacementContext(
[
entry('overnight', `${PREV_DAY}T22:00:00Z`, `${DAY}T02:00:00Z`),
entry('w1', `${DAY}T09:00:00Z`, `${DAY}T17:00:00Z`),
entry('late', `${DAY}T23:00:00Z`, `2026-07-15T01:00:00Z`),
],
dayStart,
dayEnd
);
// Boundary-crossers are not movable...
expect(ctx.work.map((e) => e.id)).toEqual(['w1']);
// ...but clamp the usable window so nothing can be shifted into them.
expect(ctx.dayStart).toBe(`${DAY}T02:00:00Z`);
expect(ctx.dayEnd).toBe(`${DAY}T23:00:00Z`);
});
it('ignores entries on other days', () => {
const ctx = buildDayPlacementContext(
[entry('other-day', `${PREV_DAY}T09:00:00Z`, `${PREV_DAY}T10:00:00Z`)],
dayStart,
dayEnd
);
expect(ctx.work).toEqual([]);
expect(ctx.breaks).toEqual([]);
expect(ctx.blocked).toEqual([]);
});
it('turns a running entry into a blocker that caps the day window', () => {
const ctx = buildDayPlacementContext(
[
entry('w1', `${DAY}T06:00:00Z`, `${DAY}T08:00:00Z`),
entry('running', `${DAY}T09:00:00Z`, null),
],
dayStart,
dayEnd
);
// The running entry is not movable, blocks the day from its start on,
// and nothing can be shifted to or past it.
expect(ctx.work.map((e) => e.id)).toEqual(['w1']);
expect(ctx.blocked).toEqual([{ start: `${DAY}T09:00:00Z`, end: dayEnd }]);
expect(ctx.dayEnd).toBe(`${DAY}T09:00:00Z`);
});
});
describe('findValidBreakGapNear', () => {
// 09-10 and 11:30-12:30 → a 90-min gap (10:00-11:30). A 1h break has a valid
// start window of 10:00-10:30; findValidBreakGap would center it at 10:15.
const work = [iv(9, 10), iv(11.5, 12.5)];
it('keeps the break at its current start instead of recentering', () => {
const gap = findValidBreakGapNear(work, HOUR, `${DAY}T10:00:00Z`);
expect(gap).toEqual({ start: `${DAY}T10:00:00Z`, end: `${DAY}T11:00:00Z` });
});
it('clamps the anchor into the tolerance window when it sits too late', () => {
// Anchored at 11:00 (beyond the window) → clamped back to 10:30.
const gap = findValidBreakGapNear(work, HOUR, `${DAY}T11:00:00Z`);
expect(gap).toEqual({ start: `${DAY}T10:30:00Z`, end: `${DAY}T11:30:00Z` });
});
it('keeps the break in place inside an oversized gap', () => {
// 09-10 and 14-15 → 4h gap. The break stays exactly where the user left it;
// its distance from work is a soft hint, not a reason to move it.
const wideWork = [iv(9, 10), iv(14, 15)];
expect(findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T11:00:00Z`)).toEqual({
start: `${DAY}T11:00:00Z`,
end: `${DAY}T11:30:00Z`,
});
});
it('clamps the anchor so the break stays inside the gap', () => {
// Anchored at 13:50 in the 10:00-14:00 gap → a 30m break would spill into
// the next work entry, so it is clamped back to 13:30-14:00.
const wideWork = [iv(9, 10), iv(14, 15)];
expect(findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T13:50:00Z`)).toEqual({
start: `${DAY}T13:30:00Z`,
end: `${DAY}T14:00:00Z`,
});
});
it("returns null when the anchor's gap can't hold the new duration", () => {
// 09-10 and 10:30-12:30 → only a 30-min gap; a 1h break no longer fits.
const tightWork = [iv(9, 10), iv(10.5, 12.5)];
expect(findValidBreakGapNear(tightWork, HOUR, `${DAY}T10:00:00Z`)).toBeNull();
});
it('returns null when the anchor sits outside every inter-work gap', () => {
// Anchor before the first work entry — a genuinely misplaced break, which the
// caller then re-places via findValidBreakGap instead.
expect(findValidBreakGapNear(work, HOUR, `${DAY}T08:00:00Z`)).toBeNull();
});
it('returns null when no free window in the gap can hold the break', () => {
// Another break occupies 10:00-11:00; the leftover windows (none before,
// 30m after) can't hold a 1h break → fall back to findValidBreakGap.
expect(findValidBreakGapNear(work, HOUR, `${DAY}T10:00:00Z`, [iv(10, 11)])).toBeNull();
});
it('slides past a neighboring break inside the same gap instead of bailing', () => {
// Gap 10:00-12:00 between work; another break sits at 10:30-11:00. Growing
// the 10:00 break to 45m no longer fits before it, so it settles right
// after the neighbor (11:00) — not in a different gap across the day.
const wideWork = [iv(9, 10), iv(12, 13)];
expect(findValidBreakGapNear(wideWork, 2700, `${DAY}T10:00:00Z`, [iv(10.5, 11)])).toEqual({
start: `${DAY}T11:00:00Z`,
end: `${DAY}T11:45:00Z`,
});
});
it('settles in the free window closest to the anchor', () => {
// Gap 10:00-13:00 with obstacles 10:45-11:00 and 11:15-12:30. For a 30m
// break anchored at 10:50 the candidates are 10:15 (35m away) and 12:30
// (100m away); the middle window is too small.
const wideWork = [iv(9, 10), iv(13, 14)];
expect(
findValidBreakGapNear(wideWork, HALF_HOUR, `${DAY}T10:50:00Z`, [
iv(10.75, 11),
iv(11.25, 12.5),
])
).toEqual({ start: `${DAY}T10:15:00Z`, end: `${DAY}T10:45:00Z` });
});
});

View File

@@ -0,0 +1,471 @@
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
import { BREAK_GAP_TOLERANCE_MINUTES } from '@/packages/ui/src/utils/breakPlacement';
/**
* Break placement solver for the timesheet.
*
* A break only means something sitting between work, ideally within a tolerance
* of it on both sides (see BREAK_GAP_TOLERANCE_MINUTES). When a break is added
* to a day we first try to drop it into an existing gap without touching any
* other entry — preferring a gap where the tolerance holds, but accepting any
* gap big enough to hold the break. The tolerance is a soft, read-time hint
* (see getBreakPlacementHint), never a reason to rearrange entries the user
* tracked deliberately. Only when no gap can physically hold the break does the
* caller resolve it via a modal that either splits the single work entry or
* moves the surrounding entries to open a slot — always keeping everything
* inside the day.
*
* All timestamps are UTC ISO strings. Shift arithmetic is done in epoch
* milliseconds so it is DST-safe (a wall-clock day can be 23h or 25h long).
*/
export const BREAK_GAP_TOLERANCE_SECONDS = BREAK_GAP_TOLERANCE_MINUTES * 60;
export interface Interval {
start: string;
end: string;
}
export interface MovableInterval extends Interval {
id: string;
}
export interface MovePlan {
breakSlot: Interval;
// Entries whose start/end changed to make room for the break
shifted: MovableInterval[];
}
export interface SplitPlan {
firstHalf: Interval;
breakSlot: Interval;
secondHalf: Interval;
}
/**
* A break that could not be auto-placed within tolerance. The timesheet raises
* one of these so the page can open the placement modal, where the user either
* splits the single work entry or shifts entries to open a slot.
*/
export interface BreakPlacementRequest {
date: string;
durationSeconds: number;
dayStart: string;
dayEnd: string;
// Work entries on the day (finished, movable), used to split or shift
workEntries: MovableInterval[];
// Existing breaks on the day (minus the one being re-placed). They shift
// along with the surrounding work in move mode so a plan can never land
// on top of them.
otherEntries: MovableInterval[];
defaultBreakStart: string;
// When re-placing an existing break (an edit), the id to update in place
replaceBreakId: string | null;
}
/**
* How a request will be resolved: a single work entry is split around the
* break; with several, the surrounding entries move to open a slot.
*/
export function placementMode(request: BreakPlacementRequest): 'split' | 'move' {
return request.workEntries.length === 1 ? 'split' : 'move';
}
/** The minimal shape of a time entry the day-context builder needs. */
export interface DayEntryLike {
id: string;
start: string;
end: string | null;
type: string;
}
/**
* Everything the placement flow needs to know about one local day:
* finished work and break entries fully inside the day (both movable), and the
* usable day window. Entries that reach across a day boundary belong partly to
* another day and must not be moved — they shrink `dayStart`/`dayEnd` instead,
* so no plan can shift anything into them.
*/
export interface DayPlacementContext {
work: MovableInterval[];
breaks: MovableInterval[];
// Immovable blockers: a running entry keeps growing from its start, so it
// blocks placement from there through the end of the day.
blocked: Interval[];
dayStart: string;
dayEnd: string;
}
export function buildDayPlacementContext(
entries: DayEntryLike[],
dayStart: string,
dayEnd: string,
excludeBreakId: string | null = null
): DayPlacementContext {
const dayjs = getDayJsInstance();
const dayStartMs = dayjs.utc(dayStart).valueOf();
const dayEndMs = dayjs.utc(dayEnd).valueOf();
let effStartMs = dayStartMs;
let effEndMs = dayEndMs;
const work: MovableInterval[] = [];
const breaks: MovableInterval[] = [];
const blocked: Interval[] = [];
for (const entry of entries) {
if (entry.id === excludeBreakId) continue;
const startMs = dayjs.utc(entry.start).valueOf();
// A running entry keeps growing from its start: nothing can be placed
// at or after it, so it caps the usable window and blocks the rest of
// the day instead of being movable.
if (entry.end === null) {
if (startMs < dayEndMs) {
if (startMs < effEndMs) effEndMs = startMs;
blocked.push({ start: entry.start, end: dayEnd });
}
continue;
}
const endMs = dayjs.utc(entry.end).valueOf();
if (startMs >= dayEndMs || endMs <= dayStartMs) continue;
const crossesStart = startMs < dayStartMs;
const crossesEnd = endMs > dayEndMs;
if (crossesStart || crossesEnd) {
if (crossesStart && endMs > effStartMs) effStartMs = endMs;
if (crossesEnd && startMs < effEndMs) effEndMs = startMs;
continue;
}
const interval = { id: entry.id, start: entry.start, end: entry.end };
if (entry.type === 'break') {
breaks.push(interval);
} else {
work.push(interval);
}
}
return {
work: sortByStart(work),
breaks: sortByStart(breaks),
blocked: sortByStart(blocked),
dayStart: dayjs.utc(effStartMs).format(),
dayEnd: dayjs.utc(effEndMs).format(),
};
}
function sortByStart<T extends Interval>(intervals: T[]): T[] {
return [...intervals].sort((a, b) => a.start.localeCompare(b.start));
}
interface IntervalMs {
startMs: number;
endMs: number;
}
function toIntervalMs(interval: Interval): IntervalMs {
const dayjs = getDayJsInstance();
return {
startMs: dayjs.utc(interval.start).valueOf(),
endMs: dayjs.utc(interval.end).valueOf(),
};
}
/**
* Merge overlapping/touching work intervals so the space between two
* consecutive merged intervals is genuinely work-free. Without this, an entry
* contained in a longer one would fabricate a "gap" that overlaps work.
*/
function mergedWorkMs(work: Interval[]): IntervalMs[] {
const sorted = work.map(toIntervalMs).sort((a, b) => a.startMs - b.startMs);
const merged: IntervalMs[] = [];
for (const current of sorted) {
const last = merged[merged.length - 1];
if (last && current.startMs <= last.endMs) {
last.endMs = Math.max(last.endMs, current.endMs);
} else {
merged.push({ ...current });
}
}
return merged;
}
/** Work-free gaps between consecutive merged work intervals, in day order. */
function workFreeGapsMs(work: Interval[]): IntervalMs[] {
const merged = mergedWorkMs(work);
const gaps: IntervalMs[] = [];
for (let i = 0; i < merged.length - 1; i++) {
gaps.push({ startMs: merged[i]!.endMs, endMs: merged[i + 1]!.startMs });
}
return gaps;
}
/**
* Find a gap between work entries that can hold a break of `durationSeconds`,
* without touching any other entry.
*
* Preference order: first a gap where the centered break stays within
* `toleranceSeconds` of work on both sides. When no such gap exists, any gap
* big enough to physically hold the break is accepted — the break is placed
* flush after the preceding work (sliding past obstacles such as existing
* breaks) and the rest of the gap is left untouched. Such a break may end up
* further from work than the tolerance; that is surfaced as a read-time hint
* (getBreakPlacementHint), not treated as infeasible. Returns null only when
* no work-free gap can hold the break at all.
*/
export function findValidBreakGap(
work: Interval[],
durationSeconds: number,
obstacles: Interval[] = [],
toleranceSeconds: number = BREAK_GAP_TOLERANCE_SECONDS
): Interval | null {
if (durationSeconds <= 0) return null;
const dayjs = getDayJsInstance();
const durationMs = durationSeconds * 1000;
const gaps = workFreeGapsMs(work);
const obstaclesMs = obstacles.map(toIntervalMs);
const blockers = (startMs: number): IntervalMs[] =>
obstaclesMs.filter((o) => startMs < o.endMs && o.startMs < startMs + durationMs);
const slot = (startMs: number): Interval => ({
start: dayjs.utc(startMs).format(),
end: dayjs.utc(startMs + durationMs).format(),
});
// Pass 1: a gap where the centered break keeps both sides within tolerance.
for (const gap of gaps) {
const gapMs = gap.endMs - gap.startMs;
if (gapMs < durationMs || gapMs > durationMs + 2 * toleranceSeconds * 1000) continue;
const startMs = gap.startMs + Math.floor((gapMs - durationMs) / 2000) * 1000;
if (blockers(startMs).length > 0) continue;
return slot(startMs);
}
// Pass 2: any gap that can physically hold the break. Start flush after the
// preceding work and slide right past obstacles until the slot is free.
for (const gap of gaps) {
let startMs = gap.startMs;
while (startMs + durationMs <= gap.endMs) {
const blocking = blockers(startMs);
if (blocking.length === 0) return slot(startMs);
startMs = Math.max(...blocking.map((o) => o.endMs));
}
}
return null;
}
/**
* Re-place an existing break as close to `anchorStart` as possible, instead of
* jumping to the first gap (which findValidBreakGap does). Only the gap the
* anchor currently sits in is considered — the break keeps its position when
* that gap can still physically hold the new duration, clamped only to stay
* inside the gap (how far it then sits from work is a soft read-time hint, not
* a constraint). Obstacles (other breaks) don't evict the break from its gap:
* it settles into the free window of the gap closest to the anchor, sliding
* just past whatever is in the way. Returns null only when the anchor sits in
* no work-free gap or that gap has no free window big enough; the caller then
* falls back to findValidBreakGap.
*/
export function findValidBreakGapNear(
work: Interval[],
durationSeconds: number,
anchorStart: string,
obstacles: Interval[] = []
): Interval | null {
if (durationSeconds <= 0) return null;
const dayjs = getDayJsInstance();
const durationMs = durationSeconds * 1000;
const anchorMs = dayjs.utc(anchorStart).valueOf();
for (const gap of workFreeGapsMs(work)) {
// The anchor must fall inside this gap for it to be "where the break is".
if (anchorMs < gap.startMs || anchorMs >= gap.endMs) continue;
if (gap.endMs - gap.startMs < durationMs) return null;
// Walk the gap's free windows around obstacles and pick the start
// closest to the anchor, so the break moves as little as possible
// from where the user left it.
const blockers = obstacles
.map(toIntervalMs)
.filter((o) => o.startMs < gap.endMs && o.endMs > gap.startMs)
.sort((a, b) => a.startMs - b.startMs);
let best: number | null = null;
const consider = (winStartMs: number, winEndMs: number) => {
if (winEndMs - winStartMs < durationMs) return;
const candidate = Math.min(Math.max(anchorMs, winStartMs), winEndMs - durationMs);
if (best === null || Math.abs(candidate - anchorMs) < Math.abs(best - anchorMs)) {
best = candidate;
}
};
let cursor = gap.startMs;
for (const blocker of blockers) {
consider(cursor, blocker.startMs);
cursor = Math.max(cursor, blocker.endMs);
}
consider(cursor, gap.endMs);
if (best === null) return null;
return { start: dayjs.utc(best).format(), end: dayjs.utc(best + durationMs).format() };
}
return null;
}
// A split must leave a meaningful chunk of work on each side of the break;
// hair-thin fragments would only exist to make a bad placement "fit".
export const MIN_SPLIT_FRAGMENT_SECONDS = 60;
/**
* Split a single work entry to insert a break. `breakStart` (UTC ISO) lets the
* caller position it; without one the break is centered. Returns null when the
* entry is too short to leave at least MIN_SPLIT_FRAGMENT_SECONDS of work on
* both sides of the break, or when an explicit `breakStart` would not — an
* out-of-range request is rejected rather than clamped, because silently
* relocating the break would contradict the time the user picked.
*/
export function planSplitEntry(
entry: Interval,
durationSeconds: number,
breakStart?: string
): SplitPlan | null {
if (durationSeconds <= 0) return null;
const dayjs = getDayJsInstance();
const entryStart = dayjs.utc(entry.start);
const entryEnd = dayjs.utc(entry.end);
const total = entryEnd.diff(entryStart, 'second');
if (total < durationSeconds + 2 * MIN_SPLIT_FRAGMENT_SECONDS) return null;
const earliest = entryStart.add(MIN_SPLIT_FRAGMENT_SECONDS, 'second');
const latest = entryEnd.subtract(durationSeconds + MIN_SPLIT_FRAGMENT_SECONDS, 'second');
let bStart = breakStart
? dayjs.utc(breakStart)
: entryStart.add(Math.floor((total - durationSeconds) / 2), 'second');
if (breakStart) {
if (bStart.isBefore(earliest) || bStart.isAfter(latest)) return null;
} else {
// Safety net for rounding of the centered position only.
if (bStart.isBefore(earliest)) bStart = earliest;
if (bStart.isAfter(latest)) bStart = latest;
}
const bEnd = bStart.add(durationSeconds, 'second');
if (!bStart.isAfter(entryStart) || !bEnd.isBefore(entryEnd)) return null;
return {
firstHalf: { start: entryStart.format(), end: bStart.format() },
breakSlot: { start: bStart.format(), end: bEnd.format() },
secondHalf: { start: bEnd.format(), end: entryEnd.format() },
};
}
/**
* Insert a break at `breakStart`, shifting the surrounding entries only as much
* as needed to clear the slot. Entries starting before the break form the left
* block: when it reaches into the slot it is translated earlier so its latest
* end meets the break start. The rest form the right block: when the slot
* reaches into it, it is translated later so its earliest start meets the break
* end. Blocks that already clear the slot are left untouched — existing gaps
* are preserved, never tightened. Returns null if a required shift would push
* an entry outside `[dayStart, dayEnd]`.
*/
export function planMoveInsert(
entries: MovableInterval[],
dayStart: string,
dayEnd: string,
breakStart: string,
durationSeconds: number
): MovePlan | null {
if (durationSeconds <= 0) return null;
const dayjs = getDayJsInstance();
const bStartMs = dayjs.utc(breakStart).valueOf();
const bEndMs = bStartMs + durationSeconds * 1000;
const dayStartMs = dayjs.utc(dayStart).valueOf();
const dayEndMs = dayjs.utc(dayEnd).valueOf();
if (bStartMs < dayStartMs || bEndMs > dayEndMs) return null;
const toMs = (iso: string) => dayjs.utc(iso).valueOf();
const left = entries.filter((e) => toMs(e.start) < bStartMs);
const right = entries.filter((e) => toMs(e.start) >= bStartMs);
const shifted: MovableInterval[] = [];
const translate = (block: MovableInterval[], shiftMs: number) => {
for (const e of block) {
shifted.push({
id: e.id,
start: dayjs.utc(toMs(e.start) + shiftMs).format(),
end: dayjs.utc(toMs(e.end) + shiftMs).format(),
});
}
};
if (left.length > 0) {
const maxLeftEnd = Math.max(...left.map((e) => toMs(e.end)));
const minLeftStart = Math.min(...left.map((e) => toMs(e.start)));
// Only pull earlier when the block overlaps the slot, never later.
const shift = Math.min(0, bStartMs - maxLeftEnd);
if (shift !== 0) {
if (minLeftStart + shift < dayStartMs) return null;
translate(left, shift);
}
}
if (right.length > 0) {
const minRightStart = Math.min(...right.map((e) => toMs(e.start)));
const maxRightEnd = Math.max(...right.map((e) => toMs(e.end)));
// Only push later when the slot overlaps the block, never earlier.
const shift = Math.max(0, bEndMs - minRightStart);
if (shift !== 0) {
if (maxRightEnd + shift > dayEndMs) return null;
translate(right, shift);
}
}
return {
breakSlot: {
start: dayjs.utc(bStartMs).format(),
end: dayjs.utc(bEndMs).format(),
},
shifted,
};
}
/**
* Pick a feasible default break position for the move case — only reached when
* no work-free gap can hold the break, so opening a slot requires shifting.
* Only boundaries *between* two consecutive work entries are considered, so the
* break always ends up flanked by work (a break before the first entry or after
* the last one would be misplaced). For each boundary it tries pushing the
* right block later first, then pulling the left block earlier, and returns the
* first placement whose shifts stay inside the day. `otherEntries` (existing
* breaks) shift along with the work around them. Null when nothing fits.
*/
export function suggestMovePlan(
work: MovableInterval[],
dayStart: string,
dayEnd: string,
durationSeconds: number,
otherEntries: MovableInterval[] = []
): MovePlan | null {
const dayjs = getDayJsInstance();
const sorted = sortByStart(work);
const movable = [...work, ...otherEntries];
for (let i = 0; i < sorted.length - 1; i++) {
// Push the right block later: break starts where the earlier entry ends.
const pushRight = planMoveInsert(
movable,
dayStart,
dayEnd,
sorted[i]!.end,
durationSeconds
);
if (pushRight) return pushRight;
// Pull the left block earlier: break ends where the later entry starts.
const before = dayjs
.utc(sorted[i + 1]!.start)
.subtract(durationSeconds, 'second')
.format();
const pullLeft = planMoveInsert(movable, dayStart, dayEnd, before, durationSeconds);
if (pullLeft) return pullLeft;
}
return null;
}

View File

@@ -26,7 +26,7 @@ interface Interval {
end: Dayjs;
}
function localDayBounds(date: string, tz: string): { dayStart: Dayjs; dayEnd: Dayjs } {
export function localDayBounds(date: string, tz: string): { dayStart: Dayjs; dayEnd: Dayjs } {
const dayjs = getDayJsInstance();
// `.add(1, 'day')` on a Dayjs instance advances by a fixed 24h, which is
// wrong on DST-transition days (the local day is 23h or 25h long). Derive

View File

@@ -0,0 +1,191 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ref } from 'vue';
import { createPinia, setActivePinia } from 'pinia';
import { useBreakPlacement, BreakPlacementDeferred } from './useBreakPlacement';
import { api } from '@/packages/api/src';
import type { TimeEntry } from '@/packages/api/src';
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
const addNotification = vi.fn();
vi.mock('@/utils/useUser', () => ({
getCurrentOrganizationId: vi.fn(() => 'org-1'),
getCurrentMembershipId: vi.fn(() => 'mem-1'),
}));
vi.mock('@tanstack/vue-query', () => ({
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
vi.mock('@/utils/notification', () => ({
useNotificationsStore: () => ({ addNotification }),
}));
vi.mock('@/packages/api/src', () => ({
api: {
createTimeEntry: vi.fn(async () => ({ data: { id: 'new-id' } })),
updateTimeEntry: vi.fn(async () => undefined),
deleteTimeEntry: vi.fn(async () => undefined),
deleteTimeEntries: vi.fn(async () => undefined),
},
}));
const apiMocks = vi.mocked(api);
const DATE = '2026-04-10';
const HOUR = 3600;
function entry(start: string, end: string | null, overrides: Partial<TimeEntry> = {}): TimeEntry {
return {
id: overrides.id ?? `e-${start}`,
start,
end,
description: '',
member_id: 'mem-1',
project_id: 'p-1',
task_id: null,
billable: false,
tags: [],
type: 'work',
...overrides,
} as unknown as TimeEntry;
}
const breakRow: TimesheetRow = {
key: 'break-row',
projectId: null,
taskId: null,
billable: false,
tags: [],
type: 'break',
cells: new Map(),
totalSeconds: 0,
};
function setup(allEntries: TimeEntry[]) {
const createCell = vi.fn(async () => undefined);
const updateEntry = vi.fn(async () => undefined);
const bp = useBreakPlacement({
weekDays: ref([DATE, '2026-04-11', '2026-04-12']),
timeEntries: ref(allEntries),
requireOrgId: () => 'org-1',
createCell,
updateEntry,
});
return { bp, createCell, updateEntry };
}
beforeEach(() => {
setActivePinia(createPinia());
apiMocks.createTimeEntry.mockClear();
apiMocks.updateTimeEntry.mockClear();
addNotification.mockClear();
});
describe('useBreakPlacement.placeBreak', () => {
it('saves the break directly when it drops into a valid gap', async () => {
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', {
id: 'morning',
});
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
id: 'afternoon',
});
const { bp } = setup([morning, afternoon]);
await bp.placeBreak(breakRow, 0, HOUR); // exactly fills the 12:00-13:00 gap
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
expect(apiMocks.createTimeEntry.mock.calls[0]![0]).toEqual(
expect.objectContaining({
type: 'break',
start: '2026-04-10T12:00:00Z',
end: '2026-04-10T13:00:00Z',
})
);
expect(bp.breakPlacementRequest.value).toBeNull();
});
it('never places a break over a running entry', async () => {
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', { id: 'morning' });
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
id: 'afternoon',
});
const running = entry('2026-04-10T12:30:00Z', null, { id: 'running' });
const { bp } = setup([morning, afternoon, running]);
// Centered placement (12:15-12:45) would overlap the running entry, so
// the break slides to the free part of the gap instead.
await bp.placeBreak(breakRow, 0, HOUR / 2);
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
expect(apiMocks.createTimeEntry.mock.calls[0]![0]).toEqual(
expect.objectContaining({
type: 'break',
start: '2026-04-10T12:00:00Z',
end: '2026-04-10T12:30:00Z',
})
);
});
it('defers to the split modal when a single work entry blocks every gap', async () => {
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
const { bp } = setup([work]);
await expect(bp.placeBreak(breakRow, 0, HOUR)).rejects.toBeInstanceOf(
BreakPlacementDeferred
);
expect(bp.breakPlacementRequest.value).toEqual(
expect.objectContaining({
durationSeconds: HOUR,
replaceBreakId: null,
workEntries: [expect.objectContaining({ id: 'w1' })],
})
);
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
});
});
describe('useBreakPlacement.applyBreakPlacement (split)', () => {
it('shrinks the original, creates the second half, and saves the break', async () => {
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
const { bp, updateEntry } = setup([work]);
// Open the placement request, then commit the break at noon.
await bp.placeBreak(breakRow, 0, HOUR).catch(() => undefined);
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
// Original work shrunk to its first half.
expect(updateEntry).toHaveBeenCalledWith(
expect.objectContaining({
id: 'w1',
start: '2026-04-10T09:00:00Z',
end: '2026-04-10T12:00:00Z',
})
);
// Second half of work + the break both created.
const created = apiMocks.createTimeEntry.mock.calls.map((c) => c[0]);
expect(created).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'work',
start: '2026-04-10T13:00:00Z',
end: '2026-04-10T17:00:00Z',
}),
expect.objectContaining({
type: 'break',
start: '2026-04-10T12:00:00Z',
end: '2026-04-10T13:00:00Z',
}),
])
);
// Request cleared and a success toast surfaced.
expect(bp.breakPlacementRequest.value).toBeNull();
expect(addNotification).toHaveBeenCalledWith('success', 'Break added', expect.any(String));
});
it('does nothing when there is no pending placement request', async () => {
const { bp, updateEntry } = setup([]);
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
expect(updateEntry).not.toHaveBeenCalled();
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,323 @@
import { ref, type Ref } from 'vue';
import { useQueryClient } from '@tanstack/vue-query';
import { api, type TimeEntry } from '@/packages/api/src';
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
import { getCurrentMembershipId } from '@/utils/useUser';
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
import { useNotificationsStore } from '@/utils/notification';
import { localDayBounds, NoFreeWindowError } from './cellMath';
import {
buildDayPlacementContext,
findValidBreakGap,
findValidBreakGapNear,
placementMode,
planMoveInsert,
planSplitEntry,
suggestMovePlan,
type BreakPlacementRequest,
type DayPlacementContext,
} from './breakPlacementMath';
/** Signals the caller that a break create/edit is waiting on the placement modal. */
export class BreakPlacementDeferred extends Error {
constructor() {
super('Break placement deferred to modal');
this.name = 'BreakPlacementDeferred';
}
}
/**
* Generic entry primitives the break subsystem borrows from the cell-mutation
* layer. `createCell` drops an entry in the first free window (used when there
* is no work to anchor a break to); `updateEntry`/`requireOrgId` are the shared
* API helpers. Keeping them injected avoids a circular dependency and makes the
* break flow unit-testable in isolation.
*/
export interface BreakPlacementDeps {
weekDays: Ref<string[]>;
timeEntries: Ref<TimeEntry[]>;
requireOrgId: () => string;
createCell: (
row: TimesheetRow,
dayIndex: number,
totalSeconds: number,
afterCursor?: string
) => Promise<void>;
updateEntry: (entry: TimeEntry) => Promise<void>;
}
/**
* Break-placement subsystem for the timesheet. Owns the placement-modal request
* state and everything that positions a break relative to work — auto-placing it
* into a valid gap when one exists, or deferring to the split/move modal when the
* day has to be rearranged.
*/
export function useBreakPlacement(deps: BreakPlacementDeps) {
const { weekDays, timeEntries, requireOrgId, createCell, updateEntry } = deps;
const dayjs = getDayJsInstance();
const queryClient = useQueryClient();
const notifications = useNotificationsStore();
// Set when a break needs manual placement; the page shows the modal for it.
const breakPlacementRequest = ref<BreakPlacementRequest | null>(null);
/**
* Movable work/breaks on the target local day plus the usable day window.
* Entries crossing a day boundary shrink the window instead of being
* movable (see buildDayPlacementContext) — the padded timesheet fetch
* makes them visible even at the week edges.
*/
function dayPlacementContext(
date: string,
tz: string,
excludeBreakId?: string
): DayPlacementContext {
const { dayStart, dayEnd } = localDayBounds(date, tz);
return buildDayPlacementContext(
timeEntries.value,
dayStart.format(),
dayEnd.format(),
excludeBreakId ?? null
);
}
async function createBreakEntry(start: string, end: string, memberId?: string): Promise<void> {
const orgId = requireOrgId();
const member = memberId ?? getCurrentMembershipId();
if (!member) throw new Error('No member context');
await api.createTimeEntry(
{
member_id: member,
project_id: null,
task_id: null,
start,
end,
billable: false,
type: 'break',
description: null,
tags: [],
},
{ params: { organization: orgId } }
);
}
async function saveBreakEntry(
start: string,
end: string,
replaceBreakId?: string,
memberId?: string
): Promise<void> {
if (replaceBreakId) {
const existing = timeEntries.value.find((entry) => entry.id === replaceBreakId);
if (!existing) throw new Error('Break to update no longer exists');
await updateEntry({ ...existing, start, end });
return;
}
await createBreakEntry(start, end, memberId);
}
/**
* Place a break on the day (new, or re-placing an existing one when `replaceBreakId`
* is given). Prefers a gap that already satisfies the placement tolerance; otherwise
* raises BreakPlacementDeferred so the page opens the modal. With no work to anchor to,
* the break is just dropped in / resized in the first free window.
*/
async function placeBreak(
row: TimesheetRow,
dayIndex: number,
durationSeconds: number,
replaceBreakId?: string
): Promise<void> {
const date = weekDays.value[dayIndex]!;
const tz = getUserTimezone();
const { work, breaks, blocked, dayStart, dayEnd } = dayPlacementContext(
date,
tz,
replaceBreakId
);
// Existing breaks block auto-placement into a gap (obstacles), but move
// along with the surrounding work when a move plan shifts entries.
// Running entries block everything from their start (never movable).
const obstacles = [...breaks, ...blocked];
// On edit, keep the break where it is when its current gap still fits it; only
// fall back to the first-gap-centered placement when it can't stay put.
const anchorStart = replaceBreakId
? (timeEntries.value.find((e) => e.id === replaceBreakId)?.start ?? null)
: null;
const validGap =
(anchorStart !== null
? findValidBreakGapNear(work, durationSeconds, anchorStart, obstacles)
: null) ?? findValidBreakGap(work, durationSeconds, obstacles);
if (validGap) {
await saveBreakEntry(validGap.start, validGap.end, replaceBreakId);
return;
}
if (work.length === 0) {
// No work to sit between: for an edit, resize the break in place; for a new
// break, drop it in the first free window. Nothing to align to either way.
if (replaceBreakId) {
const existing = timeEntries.value.find((e) => e.id === replaceBreakId);
if (existing) {
const newEnd = dayjs
.utc(existing.start)
.add(durationSeconds, 'second')
.format();
await updateEntry({ ...existing, end: newEnd });
return;
}
}
await createCell(row, dayIndex, durationSeconds);
return;
}
const mode: 'split' | 'move' = work.length === 1 ? 'split' : 'move';
const defaultBreakStart =
mode === 'split'
? (planSplitEntry(work[0]!, durationSeconds)?.breakSlot.start ?? null)
: (suggestMovePlan(work, dayStart, dayEnd, durationSeconds, breaks)?.breakSlot
.start ?? null);
if (!defaultBreakStart) {
// Even splitting/moving can't open a slot on this day.
throw new NoFreeWindowError(date, durationSeconds);
}
breakPlacementRequest.value = {
date,
durationSeconds,
dayStart,
dayEnd,
workEntries: work,
otherEntries: breaks,
defaultBreakStart,
replaceBreakId: replaceBreakId ?? null,
};
throw new BreakPlacementDeferred();
}
function dismissBreakPlacement(): void {
breakPlacementRequest.value = null;
}
/**
* Commit a break at `breakStart` by executing the split or move plan. Shifts
* happen before the break is saved so its target slot is free first.
*/
async function applyBreakPlacement(breakStart: string, durationSeconds: number): Promise<void> {
const req = breakPlacementRequest.value;
if (!req) return;
// The timesheet is the current member's own, so all created/edited entries stay with them.
const memberId = getCurrentMembershipId();
if (!memberId) throw new Error('No member context');
let entriesAdjusted = true;
try {
if (placementMode(req) === 'split') {
const original = timeEntries.value.find((e) => e.id === req.workEntries[0]!.id);
const plan = planSplitEntry(req.workEntries[0]!, durationSeconds, breakStart);
if (!original || !plan) throw new NoFreeWindowError(req.date, durationSeconds);
// Shrink the original to the first half, then add the second half + break.
await updateEntry({
...original,
start: plan.firstHalf.start,
end: plan.firstHalf.end,
});
await api.createTimeEntry(
{
member_id: memberId,
project_id: original.project_id,
task_id: original.task_id,
start: plan.secondHalf.start,
end: plan.secondHalf.end,
billable: original.billable,
type: 'work',
description: original.description ?? null,
tags: original.tags ?? [],
},
{ params: { organization: requireOrgId() } }
);
await saveBreakEntry(
plan.breakSlot.start,
plan.breakSlot.end,
req.replaceBreakId ?? undefined,
memberId
);
} else {
const plan = planMoveInsert(
[...req.workEntries, ...req.otherEntries],
req.dayStart,
req.dayEnd,
breakStart,
durationSeconds
);
if (!plan) throw new NoFreeWindowError(req.date, durationSeconds);
entriesAdjusted = plan.shifted.length > 0;
// Order the shifts so no intermediate step overlaps (matters when the org
// prevents overlapping entries): entries moving earlier are updated left-to-right,
// entries moving later right-to-left, so each one vacates before its neighbour moves.
const shifts = plan.shifted
.map((shift) => ({
shift,
original: timeEntries.value.find((e) => e.id === shift.id),
}))
.filter(
(x): x is { shift: (typeof plan.shifted)[number]; original: TimeEntry } =>
!!x.original
);
const movingEarlier = shifts
.filter((x) => x.shift.start < x.original.start)
.sort((a, b) => a.original.start.localeCompare(b.original.start));
const movingLater = shifts
.filter((x) => x.shift.start >= x.original.start)
.sort((a, b) => b.original.start.localeCompare(a.original.start));
for (const { shift, original } of [...movingEarlier, ...movingLater]) {
await updateEntry({ ...original, start: shift.start, end: shift.end });
}
await saveBreakEntry(
plan.breakSlot.start,
plan.breakSlot.end,
req.replaceBreakId ?? undefined,
memberId
);
}
notifications.addNotification(
'success',
req.replaceBreakId ? 'Break updated' : 'Break added',
entriesAdjusted
? 'Your entries were adjusted to make room for the break.'
: 'The break was added at the selected time.'
);
} catch (err) {
if (err instanceof NoFreeWindowError) {
notifications.addNotification(
'error',
"This day can't fit the break",
'Try a shorter break or a different time.'
);
} else {
notifications.addNotification(
'error',
'Failed to add break',
'Please try again later.'
);
}
throw err;
} finally {
breakPlacementRequest.value = null;
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
}
}
return {
breakPlacementRequest,
placeBreak,
dismissBreakPlacement,
applyBreakPlacement,
};
}

View File

@@ -41,8 +41,10 @@ export function useCopyLastWeek(
projectId: string | null,
taskId: string | null,
billable: boolean,
tags: string[]
) => string
tags: string[],
type?: 'work' | 'break'
) => string,
breaksEnabled: Ref<boolean>
) {
const dayjs = getDayJsInstance();
const queryClient = useQueryClient();
@@ -50,6 +52,14 @@ export function useCopyLastWeek(
const isCopyingLastWeek = ref(false);
// The server rejects creating break entries while breaks are disabled,
// so leave last week's breaks out of the copy in that case
function copyableEntries(response: TimeEntryResponse): TimeEntry[] {
return breaksEnabled.value
? response.data
: response.data.filter((entry) => entry.type !== 'break');
}
async function fetchLastWeekEntries(): Promise<TimeEntryResponse | null> {
const prevStart = weekStart.value.subtract(7, 'day');
const prevEnd = weekStart.value;
@@ -73,16 +83,22 @@ export function useCopyLastWeek(
*/
function addMissingRowsFromPreviousWeek(prevEntries: TimeEntry[]): void {
const existingIdentities = new Set(
rows.value.map((r) => makeRowKey(r.projectId, r.taskId, r.billable, r.tags))
rows.value.map((r) => makeRowKey(r.projectId, r.taskId, r.billable, r.tags, r.type))
);
const addedIdentities = new Set<string>();
for (const entry of prevEntries) {
const tags = entry.tags ?? [];
const identity = makeRowKey(entry.project_id, entry.task_id, entry.billable, tags);
const identity = makeRowKey(
entry.project_id,
entry.task_id,
entry.billable,
tags,
entry.type
);
if (!existingIdentities.has(identity) && !addedIdentities.has(identity)) {
addedIdentities.add(identity);
addSlot(entry.project_id, entry.task_id, entry.billable, tags);
addSlot(entry.project_id, entry.task_id, entry.billable, tags, entry.type);
}
}
}
@@ -92,7 +108,7 @@ export function useCopyLastWeek(
try {
const prev = await fetchLastWeekEntries();
if (!prev) return;
addMissingRowsFromPreviousWeek(prev.data);
addMissingRowsFromPreviousWeek(copyableEntries(prev));
} finally {
isCopyingLastWeek.value = false;
}
@@ -110,7 +126,8 @@ export function useCopyLastWeek(
const tz = getUserTimezone();
addMissingRowsFromPreviousWeek(prev.data);
const prevEntries = copyableEntries(prev);
addMissingRowsFromPreviousWeek(prevEntries);
const prevWeekStart = weekStart.value.subtract(7, 'day');
@@ -125,7 +142,7 @@ export function useCopyLastWeek(
let overlapFailures = 0;
let otherFailures = 0;
for (const entry of prev.data) {
for (const entry of prevEntries) {
if (!entry.end || !entry.duration) continue;
// Map previous-week date → same day-of-week in current week.
@@ -174,6 +191,7 @@ export function useCopyLastWeek(
start: window.start,
end: window.end,
billable: entry.billable,
type: entry.type,
description: entry.description ?? null,
tags: entry.tags ?? [],
};

View File

@@ -79,6 +79,7 @@ function buildRow(
taskId: null,
billable: false,
tags: [],
type: 'work',
cells: new Map([[0, cell]]),
totalSeconds: cell.totalSeconds,
};
@@ -91,6 +92,7 @@ function buildEmptyRow(projectId: string | null, key = `${projectId}:null`): Tim
taskId: null,
billable: false,
tags: [],
type: 'work',
cells: new Map(),
totalSeconds: 0,
};
@@ -308,6 +310,144 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
});
});
describe('break placement', () => {
it('updates an existing break in place when moving it into a valid gap', async () => {
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', {
id: 'morning',
type: 'work',
});
const afternoon = entry('2026-04-10T13:00:00Z', '2026-04-10T17:00:00Z', {
id: 'afternoon',
type: 'work',
});
const existingBreak = entry('2026-04-10T08:00:00Z', '2026-04-10T08:30:00Z', {
id: 'break-1',
project_id: null,
type: 'break',
});
const row = buildRow(null, [existingBreak], 'break-row');
row.type = 'break';
const { cellMutations } = setup([morning, afternoon, existingBreak]);
await cellMutations.handleCellUpdate(row, 0, HOUR);
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
expect.objectContaining({
id: 'break-1',
start: '2026-04-10T12:00:00Z',
end: '2026-04-10T13:00:00Z',
})
);
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
});
it('keeps an edited break anchored to its position instead of recentering', async () => {
// 09-10 and 11:30-12:30 leave a 90-min gap; a resized 1h break has a valid
// window of 10:00-10:30. The break already starts at 10:00, so it must stay
// there (10:00-11:00) rather than jump to the centered 10:15-11:15.
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
id: 'morning',
type: 'work',
});
const afternoon = entry('2026-04-10T11:30:00Z', '2026-04-10T12:30:00Z', {
id: 'afternoon',
type: 'work',
});
const existingBreak = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
id: 'break-1',
project_id: null,
type: 'break',
});
const row = buildRow(null, [existingBreak], 'break-row');
row.type = 'break';
const { cellMutations } = setup([morning, afternoon, existingBreak]);
await cellMutations.handleCellUpdate(row, 0, HOUR);
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
expect.objectContaining({
id: 'break-1',
start: '2026-04-10T10:00:00Z',
end: '2026-04-10T11:00:00Z',
})
);
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
});
it('grows a multi-break cell by re-placing the latest break, not fragmenting', async () => {
// Two breaks share the break cell. Growing the cell total must extend the
// latest-ending break (break-b) in place — never create a third break entry.
const w1 = entry('2026-04-10T12:00:00Z', '2026-04-10T14:00:00Z', {
id: 'w1',
type: 'work',
});
const w2 = entry('2026-04-10T15:00:00Z', '2026-04-10T17:00:00Z', {
id: 'w2',
type: 'work',
});
const breakA = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
id: 'break-a',
project_id: null,
type: 'break',
});
const breakB = entry('2026-04-10T14:00:00Z', '2026-04-10T14:30:00Z', {
id: 'break-b',
project_id: null,
type: 'break',
});
const row = buildRow(null, [breakA, breakB], 'break-row');
row.type = 'break';
const { cellMutations } = setup([w1, w2, breakA, breakB]);
// Cell total 60m → 90m (the extra 30m lands on break-b, taking it to 60m,
// which fills the 14:00-15:00 gap).
await cellMutations.handleCellUpdate(row, 0, 90 * 60);
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
expect.objectContaining({
id: 'break-b',
start: '2026-04-10T14:00:00Z',
end: '2026-04-10T15:00:00Z',
})
);
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
});
it('shrinks a multi-break cell by trimming the tail break, not fragmenting', async () => {
const breakA = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
id: 'break-a',
project_id: null,
type: 'break',
});
const breakB = entry('2026-04-10T14:00:00Z', '2026-04-10T14:30:00Z', {
id: 'break-b',
project_id: null,
type: 'break',
});
const row = buildRow(null, [breakA, breakB], 'break-row');
row.type = 'break';
const { cellMutations } = setup([breakA, breakB]);
// Cell total 60m → 40m: trim 20m off the latest break (break-b → 14:00-14:10).
await cellMutations.handleCellUpdate(row, 0, 40 * 60);
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
expect.objectContaining({
id: 'break-b',
end: '2026-04-10T14:10:00Z',
})
);
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
expect(apiMocks.deleteTimeEntry).not.toHaveBeenCalled();
});
});
// ── Extend cell (Phase 2) ──────────────────────────────────────
describe('extendCell', () => {
@@ -426,6 +566,7 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
taskId: null,
billable: false,
tags: [],
type: 'work',
cells: new Map([[0, cell]]),
totalSeconds: HOUR,
};

View File

@@ -18,6 +18,7 @@ import {
workDayStartOn,
type FreeWindow,
} from './cellMath';
import { useBreakPlacement, BreakPlacementDeferred } from './useBreakPlacement';
export type CellSaveStatus = 'saving' | 'saved' | 'error';
@@ -65,6 +66,12 @@ export function useTimesheetCellMutations(
const cellPendingSeconds = ref<Record<string, number>>({});
const statusClearTimers: Record<string, ReturnType<typeof setTimeout>> = {};
// Break placement (positioning a break relative to work, plus the split/move
// modal flow) is its own subsystem — it borrows the generic entry primitives
// below (hoisted function declarations, so referenceable here).
const { breakPlacementRequest, placeBreak, dismissBreakPlacement, applyBreakPlacement } =
useBreakPlacement({ weekDays, timeEntries, requireOrgId, createCell, updateEntry });
function clearStatusTimer(key: string): void {
clearTimeout(statusClearTimers[key]);
delete statusClearTimers[key];
@@ -130,6 +137,14 @@ export function useTimesheetCellMutations(
}
markSaved(statusKey);
} catch (err) {
if (err instanceof BreakPlacementDeferred) {
// The break needs manual placement — revert the cell to idle (the
// modal drives the actual save) instead of showing an error.
clearStatusTimer(statusKey);
delete cellStatus.value[statusKey];
delete cellPendingSeconds.value[statusKey];
return;
}
markError(statusKey);
if (err instanceof NoFreeWindowError) {
const friendlyDuration = formatHumanReadableDuration(
@@ -155,11 +170,11 @@ export function useTimesheetCellMutations(
}
function hasDuplicateIdentitySlot(row: TimesheetRow): boolean {
const target = makeRowKey(row.projectId, row.taskId, row.billable, row.tags);
const target = makeRowKey(row.projectId, row.taskId, row.billable, row.tags, row.type);
return rows.value.some(
(r) =>
r.key !== row.key &&
makeRowKey(r.projectId, r.taskId, r.billable, r.tags) === target
makeRowKey(r.projectId, r.taskId, r.billable, r.tags, r.type) === target
);
}
@@ -178,10 +193,34 @@ export function useTimesheetCellMutations(
}
if (!cell || existingSeconds === 0) {
// Breaks are placed relative to work (within tolerance), not just in the
// first free slot, and may need the placement modal to resolve.
if (row.type === 'break' && newTotalSeconds > 0) {
await placeBreak(row, dayIndex, newTotalSeconds);
return;
}
await createCell(row, dayIndex, newTotalSeconds);
return;
}
// Re-place breaks rather than extend/shrink them, which would fragment a break into
// a second entry. A day's breaks share one cell: a single break re-places at the new
// total; growing a multi-break cell grows the latest-ending break in place (others
// become obstacles); shrinking just trims the tail, which can't fragment.
if (row.type === 'break') {
if (cell.entries.length === 1) {
await placeBreak(row, dayIndex, newTotalSeconds, cell.entries[0]!.id);
return;
}
const tail = pickLatestEndedEntry(cell);
if (diff > 0 && tail?.end) {
await placeBreak(row, dayIndex, (tail.duration ?? 0) + diff, tail.id);
return;
}
await shrinkFromEnd(cell, -diff);
return;
}
if (diff > 0) {
await extendCell(row, dayIndex, cell, diff);
return;
@@ -241,6 +280,7 @@ export function useTimesheetCellMutations(
start: window.start,
end: window.end,
billable: row.billable,
type: row.type,
description: null,
tags: row.tags,
};
@@ -371,5 +411,12 @@ export function useTimesheetCellMutations(
return best;
}
return { handleCellUpdate, cellStatus, cellPendingSeconds };
return {
handleCellUpdate,
cellStatus,
cellPendingSeconds,
breakPlacementRequest,
applyBreakPlacement,
dismissBreakPlacement,
};
}

View File

@@ -54,6 +54,7 @@ function buildRow(key: string, projectId: string | null, entries: TimeEntry[]):
taskId: null,
billable: false,
tags: [],
type: 'work',
cells,
totalSeconds,
};
@@ -177,6 +178,7 @@ describe('useTimesheetRowMutations', () => {
taskId: null,
billable: false,
tags: [],
type: 'work',
});
expect(removeSlot).not.toHaveBeenCalled();
});
@@ -207,6 +209,7 @@ describe('useTimesheetRowMutations', () => {
taskId: null,
billable: false,
tags: [],
type: 'work',
});
});
@@ -233,6 +236,7 @@ describe('useTimesheetRowMutations', () => {
taskId: null,
billable: true,
tags: [],
type: 'work',
});
});

View File

@@ -38,7 +38,8 @@ export function useTimesheetRowMutations(
projectId: string | null,
taskId: string | null,
billable: boolean,
tags: string[]
tags: string[],
type?: 'work' | 'break'
) => TimesheetRowKey,
updateSlot: (key: TimesheetRowKey, identity: TimesheetRowIdentity) => void,
removeSlot: (key: TimesheetRowKey) => void
@@ -61,7 +62,8 @@ export function useTimesheetRowMutations(
identity.projectId,
identity.taskId,
identity.billable,
identity.tags
identity.tags,
identity.type
);
return rows.value.some(
@@ -71,7 +73,8 @@ export function useTimesheetRowMutations(
candidate.projectId,
candidate.taskId,
candidate.billable,
candidate.tags
candidate.tags,
candidate.type
) === target
);
}
@@ -80,13 +83,24 @@ export function useTimesheetRowMutations(
row: TimesheetRow,
partial: Partial<TimesheetRowIdentity>
): Promise<void> {
// Break rows have a fixed identity (no project/task/billable)
if (row.type === 'break' && ('projectId' in partial || 'billable' in partial)) {
return;
}
const entryIds = collectEntryIds(row);
const currentIdentity = makeRowKey(row.projectId, row.taskId, row.billable, row.tags);
const currentIdentity = makeRowKey(
row.projectId,
row.taskId,
row.billable,
row.tags,
row.type
);
let merged: TimesheetRowIdentity = {
projectId: row.projectId,
taskId: row.taskId,
billable: row.billable,
tags: row.tags,
type: row.type,
...partial,
};
@@ -111,7 +125,8 @@ export function useTimesheetRowMutations(
merged.projectId,
merged.taskId,
merged.billable,
merged.tags
merged.tags,
merged.type
);
const shouldMergeIntoExistingRow =
entryIds.length > 0 &&

View File

@@ -0,0 +1,39 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { describe, expect, it } from 'vitest';
import type { TimeEntry } from '@/packages/api/src';
import { getLastWorkTimeEntry } from './useCurrentTimeEntry';
dayjs.extend(utc);
function timeEntry(id: string, start: string, type: 'work' | 'break'): TimeEntry {
return {
id,
start,
end: null,
duration: null,
description: '',
project_id: null,
task_id: null,
organization_id: 'organization-1',
user_id: 'user-1',
tags: [],
billable: false,
type,
} as TimeEntry;
}
describe('getLastWorkTimeEntry', () => {
it('returns the newest work entry that is not in the future', () => {
const entries = [
timeEntry('future-work', '2026-07-14T14:00:00Z', 'work'),
timeEntry('break', '2026-07-14T12:00:00Z', 'break'),
timeEntry('last-work', '2026-07-14T11:00:00Z', 'work'),
timeEntry('older-work', '2026-07-14T10:00:00Z', 'work'),
];
expect(getLastWorkTimeEntry(entries, dayjs.utc('2026-07-14T13:00:00Z'))?.id).toBe(
'last-work'
);
});
});

View File

@@ -26,9 +26,33 @@ const emptyTimeEntry = {
project_id: null,
tags: [],
billable: false,
type: 'work',
organization_id: '',
} as TimeEntry;
export type ResumeTimeEntryContext = {
description: string | null;
project_id: string | null;
task_id: string | null;
tags: string[];
billable: boolean;
};
/**
* Time entries are loaded newest-first. Ignore scheduled entries so resuming after a break
* always uses the latest work entry that has actually started.
*/
export function getLastWorkTimeEntry(
timeEntries: TimeEntry[],
currentTime: Dayjs = dayjs().utc()
): TimeEntry | null {
return (
timeEntries.find(
(entry) => entry.type === 'work' && !dayjs(entry.start).utc().isAfter(currentTime)
) ?? null
);
}
export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
const currentTimeEntry = ref<TimeEntry>({ ...emptyTimeEntry });
const { handleApiRequestNotifications } = useNotificationsStore();
@@ -117,6 +141,7 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
project_id: currentTimeEntry.value?.project_id,
task_id: currentTimeEntry.value?.task_id,
billable: currentTimeEntry.value.billable,
type: currentTimeEntry.value?.type ?? 'work',
tags: currentTimeEntry.value?.tags,
},
{ params: { organization: organization } }
@@ -133,11 +158,11 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
}
}
async function stopTimer() {
async function stopTimer(endTime?: string) {
const user = getCurrentUserId();
const organization = getCurrentOrganizationId();
if (organization) {
const currentDateTime = dayjs().utc().format();
const currentDateTime = endTime ?? dayjs().utc().format();
await handleApiRequestNotifications(
() =>
api.updateTimeEntry(
@@ -161,6 +186,58 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
}
}
async function startBreak() {
const organization = getCurrentOrganizationId();
const membership = getCurrentMembershipId();
if (!organization || !membership) {
throw new Error('Failed to start break because organization ID is missing.');
}
// One timestamp for both the work end and the break start, so the entries touch exactly
const switchTime = dayjs().utc().format();
if (isActive.value && currentTimeEntry.value.type !== 'break') {
await stopTimer(switchTime);
}
startLiveTimer();
const response = await handleApiRequestNotifications(
() =>
api.createTimeEntry(
{
member_id: membership,
start: switchTime,
billable: false,
type: 'break',
},
{ params: { organization: organization } }
),
'Break started!',
'Your timer was stopped, but the break could not be started.'
);
if (response?.data) {
currentTimeEntry.value = response.data;
} else {
stopLiveTimer();
}
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
}
async function resumeWorkAfterBreak(context: ResumeTimeEntryContext) {
if (isActive.value && currentTimeEntry.value.type === 'break') {
stopLiveTimer();
await stopTimer();
}
currentTimeEntry.value = {
...emptyTimeEntry,
description: context.description ?? '',
project_id: context.project_id,
task_id: context.task_id,
tags: context.tags ?? [],
billable: context.billable,
};
startLiveTimer();
await startTimer();
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
}
async function updateTimer() {
const user = getCurrentUserId();
const organization = getCurrentOrganizationId();
@@ -213,6 +290,10 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
return false;
});
const isOnBreak = computed(() => {
return isActive.value && currentTimeEntry.value.type === 'break';
});
async function setActiveState(newState: boolean) {
if (newState) {
startLiveTimer();
@@ -229,6 +310,9 @@ export const useCurrentTimeEntryStore = defineStore('currentTimeEntry', () => {
fetchCurrentTimeEntry,
updateTimer,
isActive,
isOnBreak,
startBreak,
resumeWorkAfterBreak,
startLiveTimer,
stopLiveTimer,
now,

View File

@@ -8,6 +8,7 @@ import { useClientsQuery } from '@/utils/useClientsQuery';
import { useTagsQuery } from '@/utils/useTagsQuery';
import { CheckCircleIcon, UserCircleIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
import { DocumentTextIcon, FolderIcon } from '@heroicons/vue/16/solid';
import { Coffee } from '@lucide/vue';
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
export type GroupingOption =
@@ -17,7 +18,8 @@ export type GroupingOption =
| 'billable'
| 'client'
| 'description'
| 'tag';
| 'tag'
| 'type';
export const useReportingStore = defineStore('reporting', () => {
// Cache query composables to avoid creating new subscriptions on every call
@@ -35,6 +37,7 @@ export const useReportingStore = defineStore('reporting', () => {
client: 'No Client',
description: 'No Description',
tag: 'No Tag',
type: 'Work time',
} as Record<string, string>;
function getNameForReportingRowEntry(key: string | null, type: string | null) {
@@ -70,6 +73,9 @@ export const useReportingStore = defineStore('reporting', () => {
return 'Billable';
}
}
if (type === 'type') {
return key === 'break' ? 'Break' : 'Work time';
}
return key;
}
@@ -103,6 +109,11 @@ export const useReportingStore = defineStore('reporting', () => {
value: 'billable',
icon: BillableIcon,
},
{
label: 'Type',
value: 'type',
icon: Coffee,
},
{
label: 'Description',
value: 'description',

View File

@@ -10,7 +10,7 @@ import { useNotificationsStore } from '@/utils/notification';
export function useTimeEntriesMutations() {
const queryClient = useQueryClient();
const { handleApiRequestNotifications } = useNotificationsStore();
const { handleApiRequestNotifications, addNotification } = useNotificationsStore();
const { mutateAsync: createTimeEntry } = useMutation({
mutationFn: async (timeEntry: Omit<CreateTimeEntryBody, 'member_id'>) => {
@@ -71,7 +71,7 @@ export function useTimeEntriesMutations() {
}) => {
const organizationId = getCurrentOrganizationId();
if (organizationId) {
return await handleApiRequestNotifications(
const response = await handleApiRequestNotifications(
() =>
api.updateMultipleTimeEntries(
{
@@ -84,9 +84,23 @@ export function useTimeEntriesMutations() {
},
}
),
'Time entries updated successfully',
undefined,
'Failed to update time entries'
);
// The endpoint applies the changeset per entry and skips entries it can't
// apply it to (e.g. breaks with a project/tags/billable change) — a 200
// with their ids in `error`. Surface that instead of claiming success.
const skippedCount = response?.error.length ?? 0;
if (skippedCount > 0) {
addNotification(
'error',
`${skippedCount} of ${ids.length} time entries ${skippedCount === 1 ? 'was' : 'were'} skipped`,
'No changes were applied to the skipped entries — break entries can not have a project or tags, or be billable.'
);
} else {
addNotification('success', 'Time entries updated successfully');
}
return response;
}
},
onSuccess: () => {

View File

@@ -274,4 +274,108 @@ describe('useTimesheetGrid', () => {
expect(dayTotals.value[4]).toBe(9000);
expect(grandTotal.value).toBe(9000);
});
it('always seeds a break row pinned below all other rows when breaks are enabled', async () => {
const timeEntries = ref([
entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
id: 'work-1',
project_id: 'p-1',
type: 'work',
}),
]);
const projects = ref([project('p-1', 'Alpha')]);
const { rows, addSlot } = useTimesheetGrid(
timeEntries,
ref(WEEK_DAYS),
projects,
ref<Task[]>([]),
ref<Dayjs | null>(null),
ref(true)
);
expect(rows.value).toHaveLength(2);
expect(rows.value[1]?.type).toBe('break');
expect(rows.value[1]?.totalSeconds).toBe(0);
// User-added work rows stay above the break row
addSlot('p-1', null, true, []);
timeEntries.value = [...timeEntries.value];
await nextTick();
expect(rows.value).toHaveLength(3);
expect(rows.value[2]?.type).toBe('break');
});
it('claims break entries for the seeded break row and does not duplicate it', () => {
const breakEntry = entry('2026-04-10T12:00:00Z', '2026-04-10T12:30:00Z', {
id: 'break-1',
project_id: null,
type: 'break',
} as Partial<TimeEntry>);
const { rows } = useTimesheetGrid(
ref([breakEntry]),
ref(WEEK_DAYS),
ref<Project[]>([]),
ref<Task[]>([]),
ref<Dayjs | null>(null),
ref(true)
);
expect(rows.value).toHaveLength(1);
expect(rows.value[0]?.type).toBe('break');
expect(rows.value[0]?.totalSeconds).toBe(1800);
});
it('sums break time into break totals and keeps it out of the worked totals', () => {
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
id: 'work-1',
project_id: 'p-1',
type: 'work',
});
const brk = entry('2026-04-10T12:00:00Z', '2026-04-10T12:30:00Z', {
id: 'break-1',
project_id: null,
type: 'break',
} as Partial<TimeEntry>);
const { dayTotals, grandTotal, breakDayTotals, breakGrandTotal } = useTimesheetGrid(
ref([work, brk]),
ref(WEEK_DAYS),
ref([project('p-1', 'Alpha')]),
ref<Task[]>([]),
ref<Dayjs | null>(null),
ref(true)
);
// 2026-04-10 is dayIndex 4. Worked totals see only the 1h work entry.
expect(dayTotals.value[4]).toBe(3600);
expect(grandTotal.value).toBe(3600);
// Break time is tallied separately, per day and for the week.
expect(breakDayTotals.value[4]).toBe(1800);
expect(breakGrandTotal.value).toBe(1800);
// Days without a break contribute nothing.
expect(breakDayTotals.value[0]).toBe(0);
});
it('does not seed a break row when breaks are disabled', () => {
const { rows } = useTimesheetGrid(
ref([
entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
id: 'work-1',
project_id: 'p-1',
type: 'work',
}),
]),
ref(WEEK_DAYS),
ref([project('p-1', 'Alpha')]),
ref<Task[]>([]),
ref<Dayjs | null>(null),
ref(false)
);
expect(rows.value).toHaveLength(1);
expect(rows.value[0]?.type).toBe('work');
});
});

View File

@@ -1,4 +1,4 @@
import type { TimeEntry, Project, Task } from '@/packages/api/src';
import type { TimeEntry, TimeEntryType, Project, Task } from '@/packages/api/src';
import { getDayJsInstance, getLocalizedDateFromTimestamp } from '@/packages/ui/src/utils/time';
import type { Dayjs } from 'dayjs';
import { computed, ref, watch, type Ref } from 'vue';
@@ -18,6 +18,7 @@ export interface TimesheetRow {
taskId: string | null;
billable: boolean;
tags: string[];
type: TimeEntryType;
cells: Map<number, TimesheetCell>;
totalSeconds: number;
}
@@ -27,9 +28,11 @@ export interface TimesheetRowIdentity {
taskId: string | null;
billable: boolean;
tags: string[];
type?: TimeEntryType;
}
interface Slot extends TimesheetRowIdentity {
type: TimeEntryType;
id: string;
// 'seeded' slots are derived from the entries query and re-sort
// alphabetically whenever project/task lists change. 'user' slots
@@ -46,13 +49,14 @@ export function makeRowKey(
projectId: string | null,
taskId: string | null,
billable: boolean,
tags: string[]
tags: string[],
type: TimeEntryType = 'work'
): TimesheetRowKey {
return JSON.stringify([projectId, taskId, billable, sortTags(tags)]);
return JSON.stringify([projectId, taskId, billable, sortTags(tags), type]);
}
function slotIdentityKey(slot: Slot): TimesheetRowKey {
return makeRowKey(slot.projectId, slot.taskId, slot.billable, slot.tags);
return makeRowKey(slot.projectId, slot.taskId, slot.billable, slot.tags, slot.type);
}
let slotCounter = 0;
@@ -79,7 +83,9 @@ function newSlotId(): string {
* identity that doesn't already have one. Initial loads come in as a
* batch and are sorted by project name so the first render is stable;
* slots added later (via `addSlot` or post-mutation refetches) append
* at the end.
* at the end. With breaks enabled a break slot is always seeded, so
* the grid shows a permanent break row (pinned to the bottom) even
* when the week has no break entries.
*
* Mutations:
* - `addSlot` push a blank or pre-populated slot at the end
@@ -94,7 +100,8 @@ export function useTimesheetGrid(
weekDays: Ref<string[]>,
projects: Ref<Project[]>,
tasks: Ref<Task[]>,
currentTime: Ref<Dayjs | null>
currentTime: Ref<Dayjs | null>,
breaksEnabled?: Ref<boolean>
) {
const dayjs = getDayJsInstance();
const slots = ref<Slot[]>([]);
@@ -105,7 +112,12 @@ export function useTimesheetGrid(
// deterministic. User-added slots keep their insertion order and
// stay after the seeded block.
watch(
[() => timeEntries.value, () => projects.value, () => tasks.value],
[
() => timeEntries.value,
() => projects.value,
() => tasks.value,
() => breaksEnabled?.value,
],
([entries, projectList, taskList]) => {
const present = new Set(slots.value.map(slotIdentityKey));
for (const entry of entries) {
@@ -113,7 +125,8 @@ export function useTimesheetGrid(
entry.project_id,
entry.task_id,
entry.billable,
sortTags(entry.tags)
sortTags(entry.tags),
entry.type
);
if (present.has(key)) continue;
present.add(key);
@@ -124,6 +137,23 @@ export function useTimesheetGrid(
taskId: entry.task_id,
billable: entry.billable,
tags: sortTags(entry.tags),
type: entry.type,
});
}
// With breaks enabled the grid always shows a break row, even when
// the week has no break entries yet. Break entries can only have
// one identity (no project/task/tags, non-billable), so one break
// slot covers every break entry of the week.
if (breaksEnabled?.value && !present.has(makeRowKey(null, null, false, [], 'break'))) {
slots.value.push({
id: newSlotId(),
origin: 'seeded',
projectId: null,
taskId: null,
billable: false,
tags: [],
type: 'break',
});
}
@@ -138,10 +168,12 @@ export function useTimesheetGrid(
return `${projectName}\x00${taskName}\x00${s.billable ? '1' : '0'}\x00${s.tags.join(',')}`;
};
const seeded = slots.value.filter((s) => s.origin === 'seeded');
const userAdded = slots.value.filter((s) => s.origin === 'user');
const seeded = slots.value.filter((s) => s.origin === 'seeded' && s.type !== 'break');
const userAdded = slots.value.filter((s) => s.origin === 'user' && s.type !== 'break');
// The break row is pinned below all work rows, including user-added ones
const breakSlots = slots.value.filter((s) => s.type === 'break');
seeded.sort((a, b) => sortKey(a).localeCompare(sortKey(b)));
slots.value = [...seeded, ...userAdded];
slots.value = [...seeded, ...userAdded, ...breakSlots];
},
{ immediate: true }
);
@@ -159,7 +191,8 @@ export function useTimesheetGrid(
entry.project_id,
entry.task_id,
entry.billable,
sortTags(entry.tags)
sortTags(entry.tags),
entry.type
);
if (!entriesByIdentity.has(identityKey)) entriesByIdentity.set(identityKey, []);
entriesByIdentity.get(identityKey)!.push(entry);
@@ -222,25 +255,43 @@ export function useTimesheetGrid(
taskId: slot.taskId,
billable: slot.billable,
tags: slot.tags,
type: slot.type,
cells,
totalSeconds,
};
});
});
// Breaks are not working time: the totals sum work rows only, the break row itself shows the break time
const dayTotals = computed<number[]>(() =>
weekDays.value.map((_, dayIndex) =>
rows.value.reduce((sum, row) => sum + (row.cells.get(dayIndex)?.totalSeconds ?? 0), 0)
rows.value
.filter((row) => row.type !== 'break')
.reduce((sum, row) => sum + (row.cells.get(dayIndex)?.totalSeconds ?? 0), 0)
)
);
const grandTotal = computed(() => dayTotals.value.reduce((a, b) => a + b, 0));
// Break time is surfaced separately from worked time (dayTotals excludes it). These
// sum only the break rows, per day and for the week; consumers render them only when
// non-zero so break-free timesheets look unchanged.
const breakDayTotals = computed<number[]>(() =>
weekDays.value.map((_, dayIndex) =>
rows.value
.filter((row) => row.type === 'break')
.reduce((sum, row) => sum + (row.cells.get(dayIndex)?.totalSeconds ?? 0), 0)
)
);
const breakGrandTotal = computed(() => breakDayTotals.value.reduce((a, b) => a + b, 0));
function addSlot(
projectId: string | null,
taskId: string | null,
billable: boolean,
tags: string[]
tags: string[],
type: TimeEntryType = 'work'
): TimesheetRowKey {
const id = newSlotId();
slots.value.push({
@@ -250,6 +301,7 @@ export function useTimesheetGrid(
taskId,
billable,
tags: sortTags(tags),
type,
});
return id;
}
@@ -265,6 +317,7 @@ export function useTimesheetGrid(
slot.taskId = identity.taskId;
slot.billable = identity.billable;
slot.tags = sortTags(identity.tags);
slot.type = identity.type ?? slot.type;
}
function clearSlots() {
@@ -275,6 +328,8 @@ export function useTimesheetGrid(
rows,
dayTotals,
grandTotal,
breakDayTotals,
breakGrandTotal,
slots,
addSlot,
removeSlot,

View File

@@ -55,8 +55,11 @@ export function useTimesheetQuery(
const dateRange = computed(() => {
if (!weekStart.value || !weekEnd.value) return { start: null, end: null };
return {
start: localDateToUtc(weekStart.value),
end: localDateToUtc(weekEnd.value),
// One padding day on each side so entries crossing midnight at the
// week edges are loaded — break placement treats them as walls that
// shrink the usable day window. The grid filters back to the week.
start: localDateToUtc(weekStart.value.subtract(1, 'day')),
end: localDateToUtc(weekEnd.value.add(1, 'day')),
};
});
@@ -83,8 +86,9 @@ export function useTimesheetQuery(
}
export function prefetchTimesheetWeek(queryClient: QueryClient, weekStart: Dayjs, weekEnd: Dayjs) {
const start = localDateToUtc(weekStart);
const end = localDateToUtc(weekEnd);
// Same one-day padding as useTimesheetQuery so the prefetched key matches.
const start = localDateToUtc(weekStart.subtract(1, 'day'));
const end = localDateToUtc(weekEnd.add(1, 'day'));
const organizationId = getCurrentOrganizationId();
const memberId = getCurrentMembershipId();

View File

@@ -0,0 +1,3 @@
id,name,organization_id,archived_at,created_at,updated_at
b4187a44-41f4-46d7-8460-f15a25b3aad6,"Big Company",ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72,"Other Company (Archived)",ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name organization_id archived_at created_at updated_at
2 b4187a44-41f4-46d7-8460-f15a25b3aad6 Big Company ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72 Other Company (Archived) ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,2 @@
id,user_id,name,email,organization_id,billable_rate,role,created_at,updated_at
06e6e605-86bd-417b-b75d-02f671e5d520,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,"Peter Tester",peter.test@email.test,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,admin,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id user_id name email organization_id billable_rate role created_at updated_at
2 06e6e605-86bd-417b-b75d-02f671e5d520 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c Peter Tester peter.test@email.test ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 admin 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1 @@
{"id":"d6a324ee-58d5-4096-8069-c63bd55608f7","version":"1.0","organizations":["ee5a8cd6-312f-4ae6-b044-e2014f09ecc2"],"exported_at":"2024-08-26T18:21:59Z"}

View File

@@ -0,0 +1 @@
id,email,organization_id,role,created_at,updated_at
1 id email organization_id role created_at updated_at

View File

@@ -0,0 +1,2 @@
id,name,billable_rate,currency,created_at,updated_at
ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,"ACME Corp",,EUR,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name billable_rate currency created_at updated_at
2 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 ACME Corp EUR 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,2 @@
id,billable_rate,project_id,user_id,member_id,created_at,updated_at
180a1a98-2f1c-4596-86e4-63a6be0d7b1d,10002,06e79ec4-33f8-4730-804c-d03c014991d1,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,06e6e605-86bd-417b-b75d-02f671e5d520,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id billable_rate project_id user_id member_id created_at updated_at
2 180a1a98-2f1c-4596-86e4-63a6be0d7b1d 10002 06e79ec4-33f8-4730-804c-d03c014991d1 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c 06e6e605-86bd-417b-b75d-02f671e5d520 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,4 @@
id,name,color,billable_rate,is_public,client_id,organization_id,is_billable,archived_at,created_at,updated_at
06e79ec4-33f8-4730-804c-d03c014991d1,"Project for Big Company",#ec407a,10001,false,b4187a44-41f4-46d7-8460-f15a25b3aad6,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,true,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
622c74a9-7e64-44c2-9426-2a37ac738206,"Project without Client",#ef5350,,false,,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,false,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
aa831162-dbb2-4cfe-bfe0-5e3a252c66f0,"Project (Archived)",#6a407f,,true,e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,true,2024-08-25T10:00:00Z,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name color billable_rate is_public client_id organization_id is_billable archived_at created_at updated_at
2 06e79ec4-33f8-4730-804c-d03c014991d1 Project for Big Company #ec407a 10001 false b4187a44-41f4-46d7-8460-f15a25b3aad6 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 true 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 622c74a9-7e64-44c2-9426-2a37ac738206 Project without Client #ef5350 false ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 false 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
4 aa831162-dbb2-4cfe-bfe0-5e3a252c66f0 Project (Archived) #6a407f true e5a4d8f5-81ae-4606-8e84-6ab1ffa58b72 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 true 2024-08-25T10:00:00Z 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,3 @@
id,name,organization_id,created_at,updated_at
2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7,Development,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
bf6c0ac5-2587-474b-8983-40bb3ea8002f,Backend,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name organization_id created_at updated_at
2 2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7 Development ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 bf6c0ac5-2587-474b-8983-40bb3ea8002f Backend ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,3 @@
id,name,project_id,organization_id,done_at,created_at,updated_at
b49688a0-94f3-4cb3-9ca1-5003de955fb0,"Task 1",06e79ec4-33f8-4730-804c-d03c014991d1,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
b49688a0-94f3-4cb3-9ca1-5003de955fb0,"Task 2",06e79ec4-33f8-4730-804c-d03c014991d1,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,2024-08-24T10:00:00Z,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id name project_id organization_id done_at created_at updated_at
2 b49688a0-94f3-4cb3-9ca1-5003de955fb0 Task 1 06e79ec4-33f8-4730-804c-d03c014991d1 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 b49688a0-94f3-4cb3-9ca1-5003de955fb0 Task 2 06e79ec4-33f8-4730-804c-d03c014991d1 ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 2024-08-24T10:00:00Z 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -0,0 +1,4 @@
id,description,start,end,billable_rate,billable,type,member_id,user_id,organization_id,client_id,project_id,task_id,tags,is_imported,still_active_email_sent_at,created_at,updated_at
00aae3be-18fc-462d-bee4-350fb605b2f3,,2024-03-04T09:23:52Z,2024-03-04T09:23:52Z,,false,,06e6e605-86bd-417b-b75d-02f671e5d520,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,,,"[""2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7"",""bf6c0ac5-2587-474b-8983-40bb3ea8002f""]",false,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1c7a905d-aa12-4d08-bc41-7e92577e7cdf,"Working hard",2024-03-04T09:23:00Z,2024-03-04T10:23:01Z,,true,work,06e6e605-86bd-417b-b75d-02f671e5d520,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,b4187a44-41f4-46d7-8460-f15a25b3aad6,06e79ec4-33f8-4730-804c-d03c014991d1,b49688a0-94f3-4cb3-9ca1-5003de955fb0,[],false,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
9f2f5b83-3a6b-4a9c-8d21-4f1e5cf1b7aa,"Lunch break",2024-03-04T12:00:00Z,2024-03-04T12:30:00Z,,false,break,06e6e605-86bd-417b-b75d-02f671e5d520,0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c,ee5a8cd6-312f-4ae6-b044-e2014f09ecc2,,,,[],false,,2024-08-22T10:36:48Z,2024-08-22T10:36:48Z
1 id description start end billable_rate billable type member_id user_id organization_id client_id project_id task_id tags is_imported still_active_email_sent_at created_at updated_at
2 00aae3be-18fc-462d-bee4-350fb605b2f3 2024-03-04T09:23:52Z 2024-03-04T09:23:52Z false 06e6e605-86bd-417b-b75d-02f671e5d520 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 ["2c5c2da7-9ef8-4410-bb8f-6e0a90f9d2c7","bf6c0ac5-2587-474b-8983-40bb3ea8002f"] false 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
3 1c7a905d-aa12-4d08-bc41-7e92577e7cdf Working hard 2024-03-04T09:23:00Z 2024-03-04T10:23:01Z true work 06e6e605-86bd-417b-b75d-02f671e5d520 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 b4187a44-41f4-46d7-8460-f15a25b3aad6 06e79ec4-33f8-4730-804c-d03c014991d1 b49688a0-94f3-4cb3-9ca1-5003de955fb0 [] false 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z
4 9f2f5b83-3a6b-4a9c-8d21-4f1e5cf1b7aa Lunch break 2024-03-04T12:00:00Z 2024-03-04T12:30:00Z false break 06e6e605-86bd-417b-b75d-02f671e5d520 0446cdd8-3ad1-43d6-9231-9e0dc4eeb71c ee5a8cd6-312f-4ae6-b044-e2014f09ecc2 [] false 2024-08-22T10:36:48Z 2024-08-22T10:36:48Z

View File

@@ -158,6 +158,7 @@
<th style="text-align: center;">Time</th>
<th>Duration</th>
<th>Billable</th>
<th>Break</th>
<th>Tags</th>
</tr>
</thead>
@@ -192,6 +193,7 @@
{{ $localization->formatIntervalForReporting($timeEntry->getDuration()) }}
</td>
<td style="overflow-wrap: break-word;">{{ $timeEntry->billable ? 'Yes' : 'No' }}</td>
<td style="overflow-wrap: break-word;">{{ $timeEntry->type === \App\Enums\TimeEntryType::Break ? 'Yes' : 'No' }}</td>
<td style="overflow-wrap: break-word; min-width: 75px;">{{ count($timeEntry->tagsRelation) === 0 ? '-' : $timeEntry->tagsRelation->implode('name', ', ') }}</td>
</tr>
@endforeach