TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.
TypeScript graphviewkanban-boardnodejsproductivityproject-managementself-hostedtasktask-managementtask-managertodoapp
wip: time tracking page and tests
Nikolai Gimanec50b31642f7
diff --git a/api/src/core/GoalPermissionsFetcher.ts b/api/src/core/GoalPermissionsFetcher.tsindex 1868c8d..b7fe5fc 100644--- a/api/src/core/GoalPermissionsFetcher.ts+++ b/api/src/core/GoalPermissionsFetcher.ts@@ -67,4 +67,32 @@ export class GoalPermissionsFetcher {async getCheckerForGoal(goalId: number): Promise<GoalPermissionsChecker> {return await this.getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL);}++ async getAccessibleGoalIds(organizationId: number, permissions: string[]): Promise<number[]> {+ if (permissions.length === 0) return [];++ const tokenPerms = this.user.getTokenPermissions();+ const effectivePermissions = tokenPerms && tokenPerms.length > 0+ ? permissions.filter((p) => tokenPerms.includes(p))+ : permissions;++ if (effectivePermissions.length === 0) return [];++ const userData = this.user.getUserData();+ if (!userData) return [];++ let goalIds = await this.goalPermissionsRepository.fetchGoalIdsWithAnyPermission({+ userId: userData.id,+ email: userData.email,+ organizationId,+ permissionNames: effectivePermissions,+ });++ const allowedGoalIds = this.user.getAllowedGoalIds();+ if (allowedGoalIds && allowedGoalIds.length > 0) {+ goalIds = goalIds.filter((id) => allowedGoalIds.includes(id));+ }++ return goalIds;+ }}diff --git a/api/src/core/GoalPermissionsRepository.ts b/api/src/core/GoalPermissionsRepository.tsindex 9512963..3f6e084 100644--- a/api/src/core/GoalPermissionsRepository.ts+++ b/api/src/core/GoalPermissionsRepository.ts@@ -1,5 +1,15 @@+import { and, eq, exists, inArray, or } from 'drizzle-orm';+import {+ CollaborationPermissionsToRoleSchema,+ CollaborationRolesSchema,+ CollaborationUsersSchema,+ CollaborationUsersToGoalsSchema,+ CollaborationUsersToRolesSchema,+ GoalsSchema,+ PermissionsSchema,+} from 'taskview-db-schemas';import { Database } from '../modules/db';-import type { GoalPermissionItemsFromDb } from '../types/auth.types';+import type { FetchGoalIdsWithAnyPermissionParams, GoalPermissionItemsFromDb } from '../types/auth.types';import type { GoalItemInDb } from '../types/goal.type';import type { ListItemInDb } from '../types/lists.types';import type { TaskItemInDb } from '../types/tasks.types';@@ -59,4 +69,57 @@ export class GoalPermissionsRepository {}return null;}++ async fetchGoalIdsWithAnyPermission(params: FetchGoalIdsWithAnyPermissionParams): Promise<number[]> {+ if (params.permissionNames.length === 0) return [];++ const permissionSubquery = this.db.dbDrizzle+ .select({ one: CollaborationUsersSchema.id })+ .from(CollaborationUsersSchema)+ .innerJoin(+ CollaborationUsersToGoalsSchema,+ and(+ eq(CollaborationUsersToGoalsSchema.userId, CollaborationUsersSchema.id),+ eq(CollaborationUsersToGoalsSchema.goalId, GoalsSchema.id),+ ),+ )+ .innerJoin(+ CollaborationUsersToRolesSchema,+ eq(CollaborationUsersToRolesSchema.userId, CollaborationUsersSchema.id),+ )+ .innerJoin(+ CollaborationRolesSchema,+ and(+ eq(CollaborationRolesSchema.id, CollaborationUsersToRolesSchema.roleId),+ eq(CollaborationRolesSchema.goalId, GoalsSchema.id),+ ),+ )+ .innerJoin(+ CollaborationPermissionsToRoleSchema,+ eq(CollaborationPermissionsToRoleSchema.roleId, CollaborationRolesSchema.id),+ )+ .innerJoin(+ PermissionsSchema,+ eq(PermissionsSchema.id, CollaborationPermissionsToRoleSchema.permissionId),+ )+ .where(+ and(+ eq(CollaborationUsersSchema.email, params.email),+ inArray(PermissionsSchema.name, params.permissionNames),+ ),+ );++ const result = await this.db.dbDrizzle+ .select({ id: GoalsSchema.id })+ .from(GoalsSchema)+ .where(+ and(+ eq(GoalsSchema.organizationId, params.organizationId),+ eq(GoalsSchema.archive, 0),+ or(eq(GoalsSchema.owner, params.userId), exists(permissionSubquery)),+ ),+ );++ return result.map((r) => r.id).filter((id): id is number => Number.isInteger(id));+ }}diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex 2ba3624..15d59ff 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -526,5 +526,17 @@"Added timetracking_can_log and timetracking_can_manage_all goal-level permissions (granted to new projects only, matching the 1.46.0 analytics convention)","all-triggers.sql: updated add_roles_and_permissions function with new permissions; added log_changes_time_entries trigger (BEFORE UPDATE writes JSONB snapshot to history.time_entries)"]+ },+ "42": {+ "version": "1.49.0",+ "name": "Release 1.49.0",+ "releaseDate": "20260512",+ "scripts": [+ "/1.49.0/0.time_entries_report_indexes.sql"+ ],+ "description": [+ "Added compound indexes on tasks.time_entries (goal_id, started_at, user_id) and (goal_id, started_at, task_id) for time-tracking report aggregations",+ "Added partial index on tasks.time_entries(goal_id, started_at) WHERE billable = TRUE for billable-only reports"+ ]}}\ No newline at end of filediff --git a/api/src/migrations/taskview/sql/1.49.0/0.time_entries_report_indexes.sql b/api/src/migrations/taskview/sql/1.49.0/0.time_entries_report_indexes.sqlnew file mode 100644index 0000000..bebb560--- /dev/null+++ b/api/src/migrations/taskview/sql/1.49.0/0.time_entries_report_indexes.sql@@ -0,0 +1,9 @@+CREATE INDEX IF NOT EXISTS idx_time_entries_goal_started_user+ ON tasks.time_entries(goal_id, started_at DESC, user_id);++CREATE INDEX IF NOT EXISTS idx_time_entries_goal_started_task+ ON tasks.time_entries(goal_id, started_at DESC, task_id);++CREATE INDEX IF NOT EXISTS idx_time_entries_billable_goal_started+ ON tasks.time_entries(goal_id, started_at DESC)+ WHERE billable = TRUE;diff --git a/api/src/tv-modules/time-tracking/TimeTrackingController.ts b/api/src/tv-modules/time-tracking/TimeTrackingController.tsindex f334d75..33348b9 100644--- a/api/src/tv-modules/time-tracking/TimeTrackingController.ts+++ b/api/src/tv-modules/time-tracking/TimeTrackingController.ts@@ -1,6 +1,7 @@import type { Request, Response } from 'express'import { ArkErrors } from 'arktype'import { logError } from '../../utils/api'+import { parsePositiveInt } from '../../utils/helpers'import {TimeEntryArkTypeCreate,TimeEntryArkTypeDelete,@@ -11,6 +12,7 @@ import {TimeEntryArkTypeSummaryByGoal,TimeEntryArkTypeSummaryByTask,TimeEntryArkTypeUpdate,+ TimeReportArkTypeFilters,} from './types'export class TimeTrackingController {@@ -98,4 +100,62 @@ export class TimeTrackingController {if (!history) return res.status(403).end()return res.tvJson(history)}++ private parseReportQuery(req: Request) {+ const organizationId = parsePositiveInt(req.query?.organizationId)+ if (organizationId === null) return { error: 'orgId' as const }+ const filters = TimeReportArkTypeFilters(req.query)+ if (filters instanceof ArkErrors) return { error: 'filters' as const, summary: filters.summary }+ return { request: { organizationId, filters } }+ }++ reportByDay = async (req: Request, res: Response) => {+ const parsed = this.parseReportQuery(req)+ if ('error' in parsed) {+ if (parsed.error === 'orgId') return res.status(400).end()+ return res.status(400).send(parsed.summary)+ }+ const rows = await req.appUser.timeTrackingManager.reportByDay(parsed.request).catch(logError)+ return res.tvJson(rows ?? [])+ }++ reportByUser = async (req: Request, res: Response) => {+ const parsed = this.parseReportQuery(req)+ if ('error' in parsed) {+ if (parsed.error === 'orgId') return res.status(400).end()+ return res.status(400).send(parsed.summary)+ }+ const rows = await req.appUser.timeTrackingManager.reportByUser(parsed.request).catch(logError)+ return res.tvJson(rows ?? [])+ }++ reportByTask = async (req: Request, res: Response) => {+ const parsed = this.parseReportQuery(req)+ if ('error' in parsed) {+ if (parsed.error === 'orgId') return res.status(400).end()+ return res.status(400).send(parsed.summary)+ }+ const rows = await req.appUser.timeTrackingManager.reportByTask(parsed.request).catch(logError)+ return res.tvJson(rows ?? [])+ }++ reportSummary = async (req: Request, res: Response) => {+ const parsed = this.parseReportQuery(req)+ if ('error' in parsed) {+ if (parsed.error === 'orgId') return res.status(400).end()+ return res.status(400).send(parsed.summary)+ }+ const summary = await req.appUser.timeTrackingManager.reportSummary(parsed.request).catch(logError)+ return res.tvJson(summary ?? { totalSeconds: 0, totalBillableSeconds: 0, entriesCount: 0 })+ }++ reportContributors = async (req: Request, res: Response) => {+ const parsed = this.parseReportQuery(req)+ if ('error' in parsed) {+ if (parsed.error === 'orgId') return res.status(400).end()+ return res.status(400).send(parsed.summary)+ }+ const rows = await req.appUser.timeTrackingManager.reportContributors(parsed.request).catch(logError)+ return res.tvJson(rows ?? [])+ }}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingManager.ts b/api/src/tv-modules/time-tracking/TimeTrackingManager.tsindex eef1988..7c460f6 100644--- a/api/src/tv-modules/time-tracking/TimeTrackingManager.ts+++ b/api/src/tv-modules/time-tracking/TimeTrackingManager.ts@@ -1,5 +1,6 @@import type { AppUser } from '../../core/AppUser'import { eventBus } from '../../core/EventBus'+import { GoalPermissions } from '../../types/auth.types'import { TimeTrackingRepository } from './TimeTrackingRepository'import {TIME_ENTRY_SOURCE,@@ -11,8 +12,17 @@ import {type TimeEntryStartResult,type TimeEntryUpdateParams,type TimeEntryWithUser,+ type TimeReportByDayRow,+ type TimeReportByTaskRow,+ type TimeReportByUserRow,+ type TimeReportContributor,+ type TimeReportRepoFilters,+ type TimeReportRequest,+ type TimeReportSummary,} from './types'+type ResolvedReportFilters = TimeReportRepoFilters+export class TimeTrackingManager {public readonly repository: TimeTrackingRepositoryprivate readonly user: AppUser@@ -72,14 +82,7 @@ export class TimeTrackingManager {}private async closeActiveTimer(userId: number): Promise<TimeEntryWithUser | null> {- const active = await this.repository.findActiveForUser(userId)- if (!active) return null-- const endedAt = new Date()- const stopped = await this.repository.updateById(active.id, {- endedAt,- durationSeconds: this.computeDuration(active.startedAt, endedAt),- })+ const stopped = await this.repository.closeActiveAtomicForUser(userId, new Date())if (!stopped) return nulleventBus.emit('time-entry.stopped', {@@ -221,13 +224,31 @@ export class TimeTrackingManager {goalId = task.goalId}- const hasProjectScope = filters.goalId !== undefined || filters.taskId !== undefined- const effectiveUserId = hasProjectScope ? filters.userId : (filters.userId ?? userId)+ const hasSingleScope = goalId !== undefined++ let goalIds: number[]+ if (hasSingleScope) {+ goalIds = [goalId!]+ } else {+ if (filters.organizationId === undefined) return []+ const accessibleGoalIds = await this.user.permissionsFetcher.getAccessibleGoalIds(+ filters.organizationId,+ [GoalPermissions.TIMETRACKING_CAN_VIEW, GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL],+ )+ if (accessibleGoalIds.length === 0) return []++ const requested = filters.goalIds && filters.goalIds.length > 0 ? filters.goalIds : null+ goalIds = requested+ ? requested.filter((id) => accessibleGoalIds.includes(id))+ : accessibleGoalIds+ if (goalIds.length === 0) return []+ }return this.repository.fetchEntries({- goalId,+ goalIds,taskId: filters.taskId,- userId: effectiveUserId,+ userId: filters.userId,+ billable: filters.billable,from: filters.from,to: filters.to,limit: filters.limit,@@ -261,4 +282,67 @@ export class TimeTrackingManager {return this.repository.fetchHistory(entryId)}++ async getViewableGoalIds(organizationId: number): Promise<number[]> {+ return this.user.permissionsFetcher.getAccessibleGoalIds(organizationId, [+ GoalPermissions.TIMETRACKING_CAN_VIEW,+ GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,+ ])+ }++ private async resolveReportFilters(req: TimeReportRequest): Promise<ResolvedReportFilters | null> {+ const data = this.user.getUserData()+ if (!data) return null++ const allowedIds = await this.getViewableGoalIds(req.organizationId)+ if (allowedIds.length === 0) return null++ const requestedIds = req.filters.goalIds && req.filters.goalIds.length > 0 ? req.filters.goalIds : null+ const goalIds = requestedIds+ ? requestedIds.filter((id) => allowedIds.includes(id))+ : allowedIds++ if (goalIds.length === 0) return null++ return {+ goalIds,+ userId: req.filters.userId,+ from: req.filters.from,+ to: req.filters.to,+ billable: req.filters.billable,+ timezone: req.filters.timezone,+ }+ }++ async reportByDay(req: TimeReportRequest): Promise<TimeReportByDayRow[]> {+ const resolved = await this.resolveReportFilters(req)+ if (!resolved) return []+ return this.repository.aggregateByDay(resolved)+ }++ async reportByUser(req: TimeReportRequest): Promise<TimeReportByUserRow[]> {+ const resolved = await this.resolveReportFilters(req)+ if (!resolved) return []+ return this.repository.aggregateByUser(resolved)+ }++ async reportByTask(req: TimeReportRequest): Promise<TimeReportByTaskRow[]> {+ const resolved = await this.resolveReportFilters(req)+ if (!resolved) return []+ return this.repository.aggregateByTask(resolved)+ }++ async reportSummary(req: TimeReportRequest): Promise<TimeReportSummary> {+ const resolved = await this.resolveReportFilters(req)+ if (!resolved) {+ return { totalSeconds: 0, totalBillableSeconds: 0, entriesCount: 0 }+ }+ return this.repository.getReportSummary(resolved)+ }++ async reportContributors(req: TimeReportRequest): Promise<TimeReportContributor[]> {+ const resolved = await this.resolveReportFilters(req)+ if (!resolved) return []+ return this.repository.fetchContributors({ ...resolved, userId: undefined })+ }}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingRepository.ts b/api/src/tv-modules/time-tracking/TimeTrackingRepository.tsindex c5460e5..b2724ca 100644--- a/api/src/tv-modules/time-tracking/TimeTrackingRepository.ts+++ b/api/src/tv-modules/time-tracking/TimeTrackingRepository.ts@@ -17,6 +17,12 @@ import type {TimeEntryTaskSummary,TimeEntryUpdateParams,TimeEntryWithUser,+ TimeReportByDayRow,+ TimeReportByTaskRow,+ TimeReportByUserRow,+ TimeReportContributor,+ TimeReportRepoFilters,+ TimeReportSummary,} from './types'const PG_UNIQUE_VIOLATION = '23505'@@ -66,6 +72,21 @@ export class TimeTrackingRepository {return result?.[0] ?? null}+ async closeActiveAtomicForUser(userId: number, endedAt: Date): Promise<TimeEntryWithUser | null> {+ const updated = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TimeEntriesSchema)+ .set({+ endedAt,+ durationSeconds: sql<number>`greatest(0, round(extract(epoch from ${endedAt}::timestamp - ${TimeEntriesSchema.startedAt}))::int)`,+ })+ .where(and(eq(TimeEntriesSchema.userId, userId), isNull(TimeEntriesSchema.endedAt)))+ .returning({ id: TimeEntriesSchema.id }),+ )+ if (!updated || updated.length === 0) return null+ return this.findById(updated[0].id)+ }+async findById(id: number): Promise<TimeEntryWithUser | null> {const result = await callWithCatch(() =>this.db.dbDrizzle@@ -162,10 +183,13 @@ export class TimeTrackingRepository {}async fetchEntries(filters: TimeEntryFilters): Promise<TimeEntryWithUser[]> {+ if (filters.goalIds !== undefined && filters.goalIds.length === 0) return []+const conditions: SQL[] = []- if (filters.goalId !== undefined) conditions.push(eq(TimeEntriesSchema.goalId, filters.goalId))+ if (filters.goalIds !== undefined) conditions.push(inArray(TimeEntriesSchema.goalId, filters.goalIds))if (filters.taskId !== undefined) conditions.push(eq(TimeEntriesSchema.taskId, filters.taskId))if (filters.userId !== undefined) conditions.push(eq(TimeEntriesSchema.userId, filters.userId))+ if (filters.billable !== undefined) conditions.push(eq(TimeEntriesSchema.billable, filters.billable))if (filters.from !== undefined) conditions.push(gte(TimeEntriesSchema.startedAt, filters.from))if (filters.to !== undefined) conditions.push(lte(TimeEntriesSchema.startedAt, filters.to))@@ -286,4 +310,110 @@ export class TimeTrackingRepository {const ids = (updated ?? []).map((r) => r.id)return this.findByIds(ids)}++ private reportConditions(filters: TimeReportRepoFilters): SQL[] {+ const conditions: SQL[] = [+ inArray(TimeEntriesSchema.goalId, filters.goalIds),+ gte(TimeEntriesSchema.startedAt, filters.from),+ lte(TimeEntriesSchema.startedAt, filters.to),+ ]+ if (filters.userId !== undefined) conditions.push(eq(TimeEntriesSchema.userId, filters.userId))+ if (filters.billable !== undefined) conditions.push(eq(TimeEntriesSchema.billable, filters.billable))+ return conditions+ }++ async aggregateByDay(filters: TimeReportRepoFilters): Promise<TimeReportByDayRow[]> {+ if (filters.goalIds.length === 0) return []+ const tzLiteral = filters.timezone ? `'${filters.timezone.replace(/'/g, "''")}'` : null+ const dayExpr = tzLiteral+ ? sql<string>`to_char((${TimeEntriesSchema.startedAt} AT TIME ZONE 'UTC' AT TIME ZONE ${sql.raw(tzLiteral)})::date, 'YYYY-MM-DD')`+ : sql<string>`to_char(${TimeEntriesSchema.startedAt}::date, 'YYYY-MM-DD')`+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ day: dayExpr,+ totalSeconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ entriesCount: sql<number>`count(*)::int`,+ })+ .from(TimeEntriesSchema)+ .where(and(...this.reportConditions(filters)))+ .groupBy(dayExpr)+ .orderBy(dayExpr),+ )+ return result ?? []+ }++ async aggregateByUser(filters: TimeReportRepoFilters): Promise<TimeReportByUserRow[]> {+ if (filters.goalIds.length === 0) return []+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ userId: TimeEntriesSchema.userId,+ userEmail: UsersSchema.email,+ totalSeconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ entriesCount: sql<number>`count(*)::int`,+ })+ .from(TimeEntriesSchema)+ .leftJoin(UsersSchema, eq(UsersSchema.id, TimeEntriesSchema.userId))+ .where(and(...this.reportConditions(filters)))+ .groupBy(TimeEntriesSchema.userId, UsersSchema.email)+ .orderBy(sql`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0) desc`),+ )+ return result ?? []+ }++ async aggregateByTask(filters: TimeReportRepoFilters): Promise<TimeReportByTaskRow[]> {+ if (filters.goalIds.length === 0) return []+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ taskId: TimeEntriesSchema.taskId,+ taskDescription: TasksSchema.description,+ goalId: TimeEntriesSchema.goalId,+ totalSeconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ entriesCount: sql<number>`count(*)::int`,+ })+ .from(TimeEntriesSchema)+ .leftJoin(TasksSchema, eq(TasksSchema.id, TimeEntriesSchema.taskId))+ .where(and(...this.reportConditions(filters)))+ .groupBy(TimeEntriesSchema.taskId, TasksSchema.description, TimeEntriesSchema.goalId)+ .orderBy(sql`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0) desc`),+ )+ return result ?? []+ }++ async getReportSummary(filters: TimeReportRepoFilters): Promise<TimeReportSummary> {+ const empty: TimeReportSummary = { totalSeconds: 0, totalBillableSeconds: 0, entriesCount: 0 }+ if (filters.goalIds.length === 0) return empty+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ totalSeconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ totalBillableSeconds: sql<number>`coalesce(sum(case when ${TimeEntriesSchema.billable} then ${TimeEntriesSchema.durationSeconds} else 0 end), 0)::int`,+ entriesCount: sql<number>`count(*)::int`,+ })+ .from(TimeEntriesSchema)+ .where(and(...this.reportConditions(filters))),+ )+ return result?.[0] ?? empty+ }++ async fetchContributors(filters: TimeReportRepoFilters): Promise<TimeReportContributor[]> {+ if (filters.goalIds.length === 0) return []+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ userId: TimeEntriesSchema.userId,+ userEmail: UsersSchema.email,+ totalSeconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ entriesCount: sql<number>`count(*)::int`,+ })+ .from(TimeEntriesSchema)+ .leftJoin(UsersSchema, eq(UsersSchema.id, TimeEntriesSchema.userId))+ .where(and(...this.reportConditions(filters)))+ .groupBy(TimeEntriesSchema.userId, UsersSchema.email)+ .orderBy(sql`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0) desc`),+ )+ return result ?? []+ }}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingRoutes.ts b/api/src/tv-modules/time-tracking/TimeTrackingRoutes.tsindex 8ca59f4..21eeac9 100644--- a/api/src/tv-modules/time-tracking/TimeTrackingRoutes.ts+++ b/api/src/tv-modules/time-tracking/TimeTrackingRoutes.ts@@ -6,7 +6,9 @@ import { canLogTimeOnTask } from './middlewares/can-log-time-on-task'import { canStopTimer } from './middlewares/can-stop-timer'import { canAccessTimeEntry } from './middlewares/can-access-time-entry'import { canFetchTimeEntries } from './middlewares/can-fetch-time-entries'+import { canViewActiveTimer } from './middlewares/can-view-active-timer'import { canViewTimeStats } from './middlewares/can-view-time-stats'+import { isOrgMemberForReports } from './middlewares/is-org-member-for-reports'export default class TimeTrackingRoutes implements Routable {private readonly router: ReturnType<typeof Router>@@ -25,7 +27,7 @@ export default class TimeTrackingRoutes implements Routable {private initRoutes() {this.router.post('/start', [IsLoggedIn, canLogTimeOnTask], this.controller.start)this.router.post('/stop', [IsLoggedIn, canStopTimer], this.controller.stop)- this.router.get('/active', [IsLoggedIn], this.controller.active)+ this.router.get('/active', [IsLoggedIn, canViewActiveTimer], this.controller.active)this.router.post('/entries', [IsLoggedIn, canLogTimeOnTask], this.controller.createManual)this.router.patch('/entries/:id', [IsLoggedIn, canAccessTimeEntry('edit')], this.controller.update)@@ -35,5 +37,11 @@ export default class TimeTrackingRoutes implements Routable {this.router.get('/summary/task/:taskId', [IsLoggedIn, canViewTimeStats({ kind: 'task', param: 'taskId' })], this.controller.summaryByTask)this.router.get('/summary/goal/:goalId', [IsLoggedIn, canViewTimeStats({ kind: 'goal', param: 'goalId' })], this.controller.summaryByGoal)++ this.router.get('/reports/summary', [IsLoggedIn, isOrgMemberForReports], this.controller.reportSummary)+ this.router.get('/reports/by-day', [IsLoggedIn, isOrgMemberForReports], this.controller.reportByDay)+ this.router.get('/reports/by-user', [IsLoggedIn, isOrgMemberForReports], this.controller.reportByUser)+ this.router.get('/reports/by-task', [IsLoggedIn, isOrgMemberForReports], this.controller.reportByTask)+ this.router.get('/reports/contributors', [IsLoggedIn, isOrgMemberForReports], this.controller.reportContributors)}}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.tsindex 4397d72..f112849 100644--- a/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts+++ b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts@@ -4,10 +4,21 @@ import { $logger } from '../../../modules/logget'import { GoalPermissions } from '../../../types/auth.types'import { logError } from '../../../utils/api'+const TT_PERMS: string[] = [+ GoalPermissions.TIMETRACKING_CAN_VIEW,+ GoalPermissions.TIMETRACKING_CAN_LOG,+ GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,+]+export const canFetchTimeEntries = async (req: Request, res: Response, next: NextFunction) => {const goalIdRaw = req.query.goalIdconst taskIdRaw = req.query.taskId+ const tokenPerms = req.appUser.getTokenPermissions()+ if (tokenPerms && tokenPerms.length > 0 && !TT_PERMS.some((p) => tokenPerms.includes(p))) {+ return res.status(403).end()+ }+if (!goalIdRaw && !taskIdRaw) return next()const checker = goalIdRawdiff --git a/api/src/tv-modules/time-tracking/middlewares/can-view-active-timer.ts b/api/src/tv-modules/time-tracking/middlewares/can-view-active-timer.tsnew file mode 100644index 0000000..3e815c2--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-view-active-timer.ts@@ -0,0 +1,29 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++const TT_PERMS: string[] = [+ GoalPermissions.TIMETRACKING_CAN_VIEW,+ GoalPermissions.TIMETRACKING_CAN_LOG,+ GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,+]++export const canViewActiveTimer = async (req: Request, res: Response, next: NextFunction) => {+ const userId = req.appUser.getUserData()?.id+ if (!userId) return res.status(401).end()++ const tokenPerms = req.appUser.getTokenPermissions()+ if (tokenPerms && tokenPerms.length > 0 && !TT_PERMS.some((p) => tokenPerms.includes(p))) {+ return res.status(403).end()+ }++ const allowedGoalIds = req.appUser.getAllowedGoalIds()+ if (allowedGoalIds && allowedGoalIds.length > 0) {+ const active = await req.appUser.timeTrackingManager.repository+ .findActiveForUser(userId)+ .catch(logError)+ if (active && !allowedGoalIds.includes(active.goalId)) return res.status(403).end()+ }++ return next()+}diff --git a/api/src/tv-modules/time-tracking/middlewares/is-org-member-for-reports.ts b/api/src/tv-modules/time-tracking/middlewares/is-org-member-for-reports.tsnew file mode 100644index 0000000..5501d45--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/is-org-member-for-reports.ts@@ -0,0 +1,24 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissions } from '../../../types/auth.types'+import { parsePositiveInt } from '../../../utils/helpers'++const TT_PERMS: string[] = [+ GoalPermissions.TIMETRACKING_CAN_VIEW,+ GoalPermissions.TIMETRACKING_CAN_LOG,+ GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,+]++export const isOrgMemberForReports = async (req: Request, res: Response, next: NextFunction) => {+ const orgId = parsePositiveInt(req.query?.organizationId)+ if (orgId === null) return res.status(400).end()++ const tokenPerms = req.appUser.getTokenPermissions()+ if (tokenPerms && tokenPerms.length > 0 && !TT_PERMS.some((p) => tokenPerms.includes(p))) {+ return res.status(403).end()+ }++ const member = await req.appUser.organizationManager.getCurrentUserMember(orgId)+ if (!member) return res.status(403).end()++ return next()+}diff --git a/api/src/tv-modules/time-tracking/types.ts b/api/src/tv-modules/time-tracking/types.tsindex 2f98cfd..9eca29f 100644--- a/api/src/tv-modules/time-tracking/types.ts+++ b/api/src/tv-modules/time-tracking/types.ts@@ -10,6 +10,19 @@ const OptionalNumberFromString = type('string|number|undefined').pipe((v) => v =const DateFromString = type('string|Date').pipe((v) => v instanceof Date ? v : new Date(v))const OptionalDateFromString = type('string|Date|undefined').pipe((v) => v === undefined ? undefined : v instanceof Date ? v : new Date(v))+const NumberListFromString = type('string|number|number[]|undefined').pipe((v) => {+ if (v === undefined) return undefined+ if (typeof v === 'number') return [v]+ if (Array.isArray(v)) return v.map((n) => Number(n)).filter((n) => Number.isFinite(n))+ return v.split(',').map((s) => Number(s.trim())).filter((n) => Number.isFinite(n))+})++const BooleanFromString = type('string|boolean|undefined').pipe((v) => {+ if (v === undefined) return undefined+ if (typeof v === 'boolean') return v+ return v === 'true' || v === '1'+})+const DESCRIPTION_MAX = 500const Description = type('string').narrow((v, ctx) => {const codepoints = [...v].length@@ -51,9 +64,12 @@ export const TimeEntryArkTypeDelete = type({export type TimeEntryArgDelete = typeof TimeEntryArkTypeDelete.inferexport const TimeEntryArkTypeFetchEntries = type({+ 'organizationId?': OptionalNumberFromString,'goalId?': OptionalNumberFromString,+ 'goalIds?': NumberListFromString,'taskId?': OptionalNumberFromString,'userId?': OptionalNumberFromString,+ 'billable?': BooleanFromString,'from?': OptionalDateFromString,'to?': OptionalDateFromString,'limit?': OptionalNumberFromString,@@ -81,6 +97,74 @@ export const TIME_ENTRY_SOURCE = {MANUAL: 1,} as const+const Timezone = type('string').narrow((v, ctx) => {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: v })+ return true+ }+ catch {+ return ctx.mustBe('a valid IANA timezone name')+ }+})++export const TimeReportArkTypeFilters = type({+ 'goalIds?': NumberListFromString,+ 'userId?': OptionalNumberFromString,+ from: DateFromString,+ to: DateFromString,+ 'billable?': BooleanFromString,+ 'timezone?': Timezone,+})+export type TimeReportFilters = typeof TimeReportArkTypeFilters.infer++export type TimeReportRequest = {+ organizationId: number+ filters: TimeReportFilters+}++export type TimeReportRepoFilters = {+ goalIds: number[]+ userId?: number+ from: Date+ to: Date+ billable?: boolean+ timezone?: string+}++export type TimeReportByDayRow = {+ day: string+ totalSeconds: number+ entriesCount: number+}++export type TimeReportByUserRow = {+ userId: number+ userEmail: string | null+ totalSeconds: number+ entriesCount: number+}++export type TimeReportByTaskRow = {+ taskId: number+ taskDescription: string | null+ goalId: number+ totalSeconds: number+ entriesCount: number+}++export type TimeReportSummary = {+ totalSeconds: number+ totalBillableSeconds: number+ entriesCount: number+}++export type TimeReportContributor = {+ userId: number+ userEmail: string | null+ totalSeconds: number+ entriesCount: number+}+export type TimeEntrySource = typeof TIME_ENTRY_SOURCE[keyof typeof TIME_ENTRY_SOURCE]export type TimeEntryInsertParams = {@@ -105,9 +189,10 @@ export type TimeEntryUpdateParams = Partial<{}>export type TimeEntryFilters = {- goalId?: number+ goalIds?: number[]taskId?: numberuserId?: number+ billable?: booleanfrom?: Dateto?: Datelimit?: numberdiff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.tsindex 18d48c4..225f852 100644--- a/api/src/types/auth.types.ts+++ b/api/src/types/auth.types.ts@@ -138,3 +138,10 @@ export type PermissionsEntityType =| typeof GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL| typeof GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASKLIST| typeof GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK;++export type FetchGoalIdsWithAnyPermissionParams = {+ userId: number;+ email: string;+ organizationId: number;+ permissionNames: string[];+};diff --git a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.ymlindex 5201343..5a28fe2 100644--- a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml+++ b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml@@ -2,6 +2,7 @@ services:db:image: postgres:17restart: "no"+ command: postgres -c max_connections=300env_file:- .env.postgresqlports:diff --git a/taskview-packages/taskview-api/src/api/__tests__/setup-db.ts b/taskview-packages/taskview-api/src/api/__tests__/setup-db.tsindex 4b0fa60..8cd7b5c 100644--- a/taskview-packages/taskview-api/src/api/__tests__/setup-db.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/setup-db.ts@@ -47,6 +47,7 @@ async function cleanDatabase() {const tables = ['tv_auth.api_tokens',+ 'tv_auth.user_tokens','history.tasks_tasks','collaboration.users','tasks.goals',diff --git a/taskview-packages/taskview-api/src/api/__tests__/teardown-db.ts b/taskview-packages/taskview-api/src/api/__tests__/teardown-db.tsindex 0963bc3..419da04 100644--- a/taskview-packages/taskview-api/src/api/__tests__/teardown-db.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/teardown-db.ts@@ -23,6 +23,7 @@ async function cleanDatabase() {const tables = ['tv_auth.api_tokens',+ 'tv_auth.user_tokens','history.tasks_tasks','collaboration.users','tasks.goals',diff --git a/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.ts b/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.tsnew file mode 100644index 0000000..ffa92d2--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.ts@@ -0,0 +1,1347 @@+// cspell:ignore TIMETRACKING+import { TvApi } from '@/tv';+import {+ describe,+ it,+ expect,+ beforeAll,+ beforeEach,+} from 'vitest';+import axios from 'axios';+import { initApi, API_URL } from './init-api';+import { TvPermissions } from '../permissions';+import type { CollaborationPermission } from '../collaboration.types';+import type { TimeEntryItem } from '../time-tracking.types';++const isoMinutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();+const isoMinutesFromNow = (minutes: number) => new Date(Date.now() + minutes * 60_000).toISOString();++describe('TvApi time-tracking tests', () => {+ let $mainUser: TvApi;+ let $invitedUser: TvApi;+ let mainUserEmail: string;+ let invitedUserEmail: string;++ let organizationId: number;+ let goalId: number;+ let secondaryGoalId: number;+ let foreignGoalId: number;+ let taskId: number;+ let secondaryTaskId: number;+ let foreignTaskId: number;+ let foreignOrgId: number;++ let timestamp: number;+ let permissions: CollaborationPermission[] = [];++ const findPermissionId = async (api: TvApi, permission: typeof TvPermissions[keyof typeof TvPermissions]) => {+ if (!permissions.length) {+ permissions = await api.collaboration.fetchAllPermissions();+ }+ const id = permissions.find((p) => p.name === permission)?.id;+ if (!id) throw new Error(`Permission ${permission} not found`);+ return id;+ };++ const togglePermissionForRole = async (roleId: number, permission: typeof TvPermissions[keyof typeof TvPermissions]) => {+ const permissionId = await findPermissionId($mainUser, permission);+ const response = await $mainUser.collaboration.toggleRolePermission({+ roleId,+ permissionId,+ }).catch(console.error);+ if (!response) throw new Error(`Failed to toggle permission ${permission}`);+ return response.add;+ };++ const inviteUserToGoalWithRole = async (+ targetGoalId: number,+ targetRoleName: string,+ targetPermissions: (typeof TvPermissions[keyof typeof TvPermissions])[],+ ) => {+ const role = await $mainUser.collaboration.createRoleForGoal({+ goalId: targetGoalId,+ roleName: targetRoleName,+ }).catch(console.error);+ if (!role) throw new Error('Failed to create role');++ const added = await $mainUser.collaboration.inviteUserToGoal({+ goalId: targetGoalId,+ email: invitedUserEmail,+ }).catch(console.error);+ if (!added) throw new Error('Failed to invite user');++ await $mainUser.collaboration.toggleUserRoles({+ goalId: targetGoalId,+ userId: added.id,+ roles: [role.id],+ }).catch(console.error);++ for (const perm of targetPermissions) {+ await togglePermissionForRole(role.id, perm);+ }++ return { roleId: role.id, invitedRecordId: added.id };+ };++ const stopActiveIfAny = async (api: TvApi) => {+ const active = await api.timeTracking.getActive().catch(() => null);+ if (active) {+ await api.timeTracking.stop({ entryId: active.id }).catch(() => null);+ }+ };++ beforeAll(async () => {+ const init = await initApi();+ $mainUser = init.$tvApi;+ $invitedUser = init.$tvApiForSecondUser;+ mainUserEmail = init.user1Email;+ invitedUserEmail = init.user2Email;+ });++ beforeEach(async () => {+ timestamp = Date.now();+ permissions = [];++ await stopActiveIfAny($mainUser);+ await stopActiveIfAny($invitedUser);++ const org = await $mainUser.organizations.create({+ name: `TT Org-${timestamp}`,+ }).catch(console.error);+ if (!org) throw new Error('Failed to create organization');+ organizationId = org.id;++ const goal = await $mainUser.goals.createGoal({+ name: `TT Goal-${timestamp}`,+ organizationId,+ }).catch(console.error);+ if (!goal) throw new Error('Failed to create primary goal');+ goalId = goal.id;++ const secondaryGoal = await $mainUser.goals.createGoal({+ name: `TT Goal2-${timestamp}`,+ organizationId,+ }).catch(console.error);+ if (!secondaryGoal) throw new Error('Failed to create secondary goal');+ secondaryGoalId = secondaryGoal.id;++ const foreignOrg = await $invitedUser.organizations.create({+ name: `TT Foreign Org-${timestamp}`,+ }).catch(console.error);+ if (!foreignOrg) throw new Error('Failed to create foreign organization');+ foreignOrgId = foreignOrg.id;++ const foreignGoal = await $invitedUser.goals.createGoal({+ name: `TT Foreign Goal-${timestamp}`,+ organizationId: foreignOrgId,+ }).catch(console.error);+ if (!foreignGoal) throw new Error('Failed to create foreign goal');+ foreignGoalId = foreignGoal.id;++ const task = await $mainUser.tasks.createTask({+ goalId,+ description: `TT task-${timestamp}`,+ }).catch(console.error);+ if (!task) throw new Error('Failed to create task');+ taskId = task.id;++ const secondaryTask = await $mainUser.tasks.createTask({+ goalId,+ description: `TT secondary task-${timestamp}`,+ }).catch(console.error);+ if (!secondaryTask) throw new Error('Failed to create secondary task');+ secondaryTaskId = secondaryTask.id;++ const foreignTask = await $invitedUser.tasks.createTask({+ goalId: foreignGoalId,+ description: `TT foreign task-${timestamp}`,+ }).catch(console.error);+ if (!foreignTask) throw new Error('Failed to create foreign task');+ foreignTaskId = foreignTask.id;++ });++ describe('1. Owner basic CRUD', () => {+ it('starts and stops a timer; getActive reflects state', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started).toBeDefined();+ expect(started?.entry).toBeDefined();+ expect(started?.entry.taskId).toBe(taskId);+ expect(started?.entry.endedAt).toBeNull();+ expect(started?.autoStoppedEntry).toBeNull();++ const active = await $mainUser.timeTracking.getActive().catch(console.error);+ expect(active?.id).toBe(started?.entry.id);++ const stopped = await $mainUser.timeTracking.stop({ entryId: started?.entry.id }).catch(console.error);+ expect(stopped?.endedAt).not.toBeNull();+ expect(stopped?.durationSeconds).toBeGreaterThanOrEqual(0);++ const activeAfter = await $mainUser.timeTracking.getActive().catch(console.error);+ expect(activeAfter).toBeNull();+ });++ it('auto-stops previous active timer on start of a new one', async () => {+ const first = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(first?.entry).toBeDefined();++ const second = await $mainUser.timeTracking.start({ taskId: secondaryTaskId }).catch(console.error);+ expect(second?.entry).toBeDefined();+ expect(second?.autoStoppedEntry).not.toBeNull();+ expect(second?.autoStoppedEntry?.id).toBe(first?.entry.id);+ expect(second?.autoStoppedEntry?.endedAt).not.toBeNull();++ await $mainUser.timeTracking.stop({ entryId: second?.entry.id }).catch(() => null);+ });++ it('starting a new timer on the same task auto-stops the previous one', async () => {+ const first = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(first?.entry).toBeDefined();++ const second = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(second?.entry).toBeDefined();+ expect(second?.entry.id).not.toBe(first?.entry.id);+ expect(second?.autoStoppedEntry).not.toBeNull();+ expect(second?.autoStoppedEntry?.id).toBe(first?.entry.id);++ await $mainUser.timeTracking.stop({ entryId: second?.entry.id }).catch(() => null);+ });++ it('stop without entryId stops the user own active timer', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const stopped = await $mainUser.timeTracking.stop().catch(console.error);+ expect(stopped?.id).toBe(started?.entry.id);+ expect(stopped?.endedAt).not.toBeNull();+ });++ it('createManual creates a manual entry that is visible in fetchEntries by goalId', async () => {+ const startedAt = isoMinutesAgo(60);+ const endedAt = isoMinutesAgo(30);++ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt,+ endedAt,+ description: 'manual entry',+ billable: true,+ }).catch(console.error);+ expect(entry?.taskId).toBe(taskId);+ expect(entry?.source).toBe(1);+ expect(entry?.durationSeconds).toBe(30 * 60);++ const entries = await $mainUser.timeTracking.fetchEntries({ goalId }).catch(console.error);+ expect(entries?.some((e) => e.id === entry?.id)).toBe(true);+ });++ it('createManual with endedAt <= startedAt is rejected', async () => {+ const startedAt = isoMinutesAgo(30);+ const endedAt = isoMinutesAgo(60);++ const status = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt,+ endedAt,+ }).catch((err) => err.status);+ expect(status).toBe(400);+ });++ it('update of active timer allows description only; other fields rejected', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const descUpdated = await $mainUser.timeTracking.update({+ id: started!.entry.id,+ description: 'updated description',+ }).catch(console.error);+ expect(descUpdated?.description).toBe('updated description');+ expect(descUpdated?.endedAt).toBeNull();++ const startedAtStatus = await $mainUser.timeTracking.update({+ id: started!.entry.id,+ startedAt: isoMinutesAgo(120),+ }).catch((err) => err.status);+ expect(startedAtStatus).toBe(403);++ const endedAtStatus = await $mainUser.timeTracking.update({+ id: started!.entry.id,+ endedAt: isoMinutesFromNow(1),+ }).catch((err) => err.status);+ expect(endedAtStatus).toBe(403);++ const billableStatus = await $mainUser.timeTracking.update({+ id: started!.entry.id,+ billable: false,+ }).catch((err) => err.status);+ expect(billableStatus).toBe(403);++ await $mainUser.timeTracking.stop({ entryId: started?.entry.id }).catch(() => null);+ });++ it('update of completed entry adjusts startedAt/endedAt and recalculates durationSeconds', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(entry).toBeDefined();++ const newStart = isoMinutesAgo(90);+ const newEnd = isoMinutesAgo(30);+ const updated = await $mainUser.timeTracking.update({+ id: entry!.id,+ startedAt: newStart,+ endedAt: newEnd,+ }).catch(console.error);+ expect(updated).toBeDefined();+ expect(updated?.durationSeconds).toBe(60 * 60);+ });++ it('update of completed entry with endedAt <= startedAt is rejected', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(entry).toBeDefined();++ const status = await $mainUser.timeTracking.update({+ id: entry!.id,+ startedAt: isoMinutesAgo(10),+ endedAt: isoMinutesAgo(20),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('delete removes own entry', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(entry).toBeDefined();++ const result = await $mainUser.timeTracking.delete(entry!.id).catch(console.error);+ expect(result?.deleted).toBe(true);++ const entries = await $mainUser.timeTracking.fetchEntries({ goalId }).catch(console.error);+ expect(entries?.some((e) => e.id === entry!.id)).toBe(false);+ });++ it('fetchHistory returns history items after edits', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ description: 'first',+ }).catch(console.error);++ await $mainUser.timeTracking.update({+ id: entry!.id,+ description: 'second',+ }).catch(console.error);++ await $mainUser.timeTracking.update({+ id: entry!.id,+ description: 'third',+ }).catch(console.error);++ const history = await $mainUser.timeTracking.fetchHistory(entry!.id).catch(console.error);+ expect(Array.isArray(history)).toBe(true);+ expect(history!.length).toBeGreaterThan(0);+ });+ });++ describe('2. Foreign goal access (no invitation)', () => {+ it('start on foreign task is forbidden', async () => {+ const status = await $invitedUser.timeTracking.start({ taskId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('createManual on foreign task is forbidden', async () => {+ const status = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchEntries with foreign goalId is forbidden', async () => {+ const status = await $invitedUser.timeTracking.fetchEntries({ goalId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchEntries with foreign taskId is forbidden', async () => {+ const status = await $invitedUser.timeTracking.fetchEntries({ taskId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('summaryByTask/summaryByGoal on foreign resources are forbidden', async () => {+ const taskStatus = await $invitedUser.timeTracking.summaryByTask(taskId).catch((err) => err.status);+ expect(taskStatus).toBe(403);++ const goalStatus = await $invitedUser.timeTracking.summaryByGoal(goalId).catch((err) => err.status);+ expect(goalStatus).toBe(403);+ });++ it('stop by foreign entryId returns 403/404 to non-collaborator', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const status = await $invitedUser.timeTracking.stop({ entryId: started!.entry.id }).catch((err) => err.status);+ expect([403, 404]).toContain(status);++ await $mainUser.timeTracking.stop({ entryId: started?.entry.id }).catch(() => null);+ });++ it('update/delete of foreign entry returns 403/404', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(entry).toBeDefined();++ const updateStatus = await $invitedUser.timeTracking.update({+ id: entry!.id,+ description: 'hacked',+ }).catch((err) => err.status);+ expect([403, 404]).toContain(updateStatus);++ const deleteStatus = await $invitedUser.timeTracking.delete(entry!.id).catch((err) => err.status);+ expect([403, 404]).toContain(deleteStatus);+ });+ });++ describe('3. Invited user without time-tracking permissions', () => {+ beforeEach(async () => {+ await inviteUserToGoalWithRole(goalId, `tt-no-perms-${timestamp}`, []);+ });++ it('start is forbidden without TIMETRACKING_CAN_LOG', async () => {+ const status = await $invitedUser.timeTracking.start({ taskId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('createManual is forbidden without TIMETRACKING_CAN_LOG', async () => {+ const status = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchEntries by goalId is forbidden without TIMETRACKING_CAN_VIEW', async () => {+ const status = await $invitedUser.timeTracking.fetchEntries({ goalId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('summaryByTask/summaryByGoal are forbidden without VIEW/MANAGE_ALL', async () => {+ const taskStatus = await $invitedUser.timeTracking.summaryByTask(taskId).catch((err) => err.status);+ expect(taskStatus).toBe(403);+ const goalStatus = await $invitedUser.timeTracking.summaryByGoal(goalId).catch((err) => err.status);+ expect(goalStatus).toBe(403);+ });++ it('update/delete of owner entry is forbidden', async () => {+ const entry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(entry).toBeDefined();++ const updateStatus = await $invitedUser.timeTracking.update({+ id: entry!.id,+ description: 'hacked',+ }).catch((err) => err.status);+ expect(updateStatus).toBe(403);++ const deleteStatus = await $invitedUser.timeTracking.delete(entry!.id).catch((err) => err.status);+ expect(deleteStatus).toBe(403);+ });+ });++ describe('4. Invited user with TIMETRACKING_CAN_LOG only', () => {+ let invitedRoleId: number;++ beforeEach(async () => {+ const { roleId } = await inviteUserToGoalWithRole(goalId, `tt-log-only-${timestamp}`, [+ TvPermissions.TIMETRACKING_CAN_LOG,+ ]);+ invitedRoleId = roleId;+ });++ it('can start, stop, createManual, update and delete OWN entries', async () => {+ const started = await $invitedUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const stopped = await $invitedUser.timeTracking.stop({ entryId: started!.entry.id }).catch(console.error);+ expect(stopped?.endedAt).not.toBeNull();++ const manual = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(manual?.taskId).toBe(taskId);++ const updated = await $invitedUser.timeTracking.update({+ id: manual!.id,+ description: 'updated own',+ }).catch(console.error);+ expect(updated?.description).toBe('updated own');++ const del = await $invitedUser.timeTracking.delete(manual!.id).catch(console.error);+ expect(del?.deleted).toBe(true);+ });++ it('cannot view or edit other users entries (no VIEW/MANAGE_ALL)', async () => {+ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();++ const updateStatus = await $invitedUser.timeTracking.update({+ id: ownerEntry!.id,+ description: 'hacked',+ }).catch((err) => err.status);+ expect(updateStatus).toBe(403);++ const deleteStatus = await $invitedUser.timeTracking.delete(ownerEntry!.id).catch((err) => err.status);+ expect(deleteStatus).toBe(403);++ const historyStatus = await $invitedUser.timeTracking.fetchHistory(ownerEntry!.id).catch((err) => err.status);+ expect(historyStatus).toBe(403);+ });++ it('cannot fetchEntries by goalId without VIEW (middleware rejects)', async () => {+ const status = await $invitedUser.timeTracking.fetchEntries({ goalId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('cannot fetchHistory of OWN entry without VIEW or MANAGE_ALL', async () => {+ const ownEntry = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownEntry).toBeDefined();++ const status = await $invitedUser.timeTracking.fetchHistory(ownEntry!.id).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('cannot update or delete OWN entry after TIMETRACKING_CAN_LOG is revoked', async () => {+ const ownEntry = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ description: 'original',+ }).catch(console.error);+ expect(ownEntry).toBeDefined();++ await togglePermissionForRole(invitedRoleId, TvPermissions.TIMETRACKING_CAN_LOG);++ const updateStatus = await $invitedUser.timeTracking.update({+ id: ownEntry!.id,+ description: 'should not pass',+ }).catch((err) => err.status);+ expect(updateStatus).toBe(403);++ const deleteStatus = await $invitedUser.timeTracking.delete(ownEntry!.id).catch((err) => err.status);+ expect(deleteStatus).toBe(403);++ const startStatus = await $invitedUser.timeTracking.start({ taskId }).catch((err) => err.status);+ expect(startStatus).toBe(403);++ const createStatus = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(20),+ endedAt: isoMinutesAgo(10),+ }).catch((err) => err.status);+ expect(createStatus).toBe(403);+ });+ });++ describe('5. Invited user with TIMETRACKING_CAN_MANAGE_ALL', () => {+ beforeEach(async () => {+ await inviteUserToGoalWithRole(goalId, `tt-manage-all-${timestamp}`, [+ TvPermissions.TIMETRACKING_CAN_MANAGE_ALL,+ ]);+ });++ it('can update and delete owner entry', async () => {+ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();++ const updated = await $invitedUser.timeTracking.update({+ id: ownerEntry!.id,+ description: 'edited by manager',+ }).catch(console.error);+ expect(updated?.description).toBe('edited by manager');++ const del = await $invitedUser.timeTracking.delete(ownerEntry!.id).catch(console.error);+ expect(del?.deleted).toBe(true);+ });++ it('sees all goal entries (own and owner) via fetchEntries with goalId', async () => {+ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ const invitedEntry = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(45),+ endedAt: isoMinutesAgo(20),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();+ expect(invitedEntry).toBeDefined();++ const entries = await $invitedUser.timeTracking.fetchEntries({ goalId }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(ownerEntry!.id);+ expect(ids).toContain(invitedEntry!.id);+ });++ it('fetchHistory of owner entry is allowed', async () => {+ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);++ await $mainUser.timeTracking.update({+ id: ownerEntry!.id,+ description: 'edit 1',+ }).catch(console.error);++ const history = await $invitedUser.timeTracking.fetchHistory(ownerEntry!.id).catch(console.error);+ expect(Array.isArray(history)).toBe(true);+ });+ });++ describe('6. Cross-goal/task substitution attempts', () => {+ it('createManual with foreign taskId is forbidden (canLogTimeOnTask)', async () => {+ const status = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchEntries with goalIds including foreign goal filters out foreign entries', async () => {+ const ownEntry = await $invitedUser.timeTracking.createManual({+ taskId: foreignTaskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownEntry).toBeDefined();++ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();++ const entries = await $invitedUser.timeTracking.fetchEntries({+ organizationId: foreignOrgId,+ goalIds: [foreignGoalId, goalId],+ }).catch(console.error);++ const fetched = entries ?? [];+ expect(fetched.some((e) => e.id === ownEntry!.id)).toBe(true);+ expect(fetched.some((e) => e.id === ownerEntry!.id)).toBe(false);+ });++ it('summaryByGoal with foreign goalId is forbidden', async () => {+ const status = await $invitedUser.timeTracking.summaryByGoal(goalId).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('reports request with foreign organizationId is forbidden', async () => {+ const status = await $invitedUser.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });+ });++ describe('7. fetchEntries filters', () => {+ let entryA: TimeEntryItem;+ let entryB: TimeEntryItem;+ let entryC: TimeEntryItem;++ beforeEach(async () => {+ const a = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(120),+ endedAt: isoMinutesAgo(90),+ billable: true,+ }).catch(console.error);+ const b = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ billable: false,+ }).catch(console.error);+ const c = await $mainUser.timeTracking.createManual({+ taskId: secondaryTaskId,+ startedAt: isoMinutesAgo(45),+ endedAt: isoMinutesAgo(15),+ billable: true,+ }).catch(console.error);++ if (!a || !b || !c) throw new Error('Failed to seed entries');+ entryA = a;+ entryB = b;+ entryC = c;+ });++ it('returns own accessible entries when organizationId is provided without goal/task scope', async () => {+ const entries = await $mainUser.timeTracking.fetchEntries({ organizationId }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(entryA.id);+ expect(ids).toContain(entryB.id);+ expect(ids).toContain(entryC.id);+ });++ it('returns empty array when no organizationId and no goal/task is given', async () => {+ const entries = await $mainUser.timeTracking.fetchEntries({}).catch(console.error);+ expect(entries).toEqual([]);+ });++ it('filters by taskId', async () => {+ const entries = await $mainUser.timeTracking.fetchEntries({ taskId: secondaryTaskId }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(entryC.id);+ expect(ids).not.toContain(entryA.id);+ expect(ids).not.toContain(entryB.id);+ });++ it('filters by billable=false', async () => {+ const entries = await $mainUser.timeTracking.fetchEntries({ goalId, billable: false }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(entryB.id);+ expect(ids).not.toContain(entryA.id);+ expect(ids).not.toContain(entryC.id);+ });++ it('filters by userId', async () => {+ const userData = (await $mainUser.timeTracking.fetchEntries({ goalId })) ?? [];+ const ownerUserId = userData[0]?.userId;+ expect(ownerUserId).toBeDefined();++ const entries = await $mainUser.timeTracking.fetchEntries({+ goalId,+ userId: ownerUserId,+ }).catch(console.error);+ expect(entries?.every((e) => e.userId === ownerUserId)).toBe(true);+ });++ it('filters by from/to', async () => {+ const from = isoMinutesAgo(75);+ const to = isoMinutesFromNow(1);+ const entries = await $mainUser.timeTracking.fetchEntries({ goalId, from, to }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(entryB.id);+ expect(ids).not.toContain(entryA.id);+ });++ it('respects limit and offset', async () => {+ const first = await $mainUser.timeTracking.fetchEntries({ goalId, limit: 1, offset: 0 }).catch(console.error);+ expect(first?.length).toBe(1);++ const second = await $mainUser.timeTracking.fetchEntries({ goalId, limit: 1, offset: 1 }).catch(console.error);+ expect(second?.length).toBe(1);+ expect(second?.[0].id).not.toBe(first?.[0].id);+ });++ it('fetchEntries with goalIds containing only inaccessible goals returns empty', async () => {+ const entries = await $invitedUser.timeTracking.fetchEntries({+ organizationId: foreignOrgId,+ goalIds: [goalId],+ }).catch(console.error);+ expect(entries).toEqual([]);+ });++ it('fetchEntries with both goalId and taskId narrows to the task within the goal', async () => {+ const entries = await $mainUser.timeTracking.fetchEntries({+ goalId,+ taskId: secondaryTaskId,+ }).catch(console.error);+ const ids = entries?.map((e) => e.id) ?? [];+ expect(ids).toContain(entryC.id);+ expect(ids).not.toContain(entryA.id);+ expect(ids).not.toContain(entryB.id);+ });+ });++ describe('8. Reports', () => {+ beforeEach(async () => {+ await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ billable: true,+ }).catch(console.error);+ await $mainUser.timeTracking.createManual({+ taskId: secondaryTaskId,+ startedAt: isoMinutesAgo(45),+ endedAt: isoMinutesAgo(15),+ billable: false,+ }).catch(console.error);+ });++ it('rejects request without organizationId (400)', async () => {+ const status = await $mainUser.timeTracking.reportSummary({+ organizationId: undefined as unknown as number,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch((err) => err.status);+ expect(status).toBe(400);+ });++ it('non-member of organization receives 403', async () => {+ const status = await $invitedUser.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('reportSummary returns aggregated totals for accessible goals', async () => {+ const summary = await $mainUser.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(summary).toBeDefined();+ expect(summary?.entriesCount).toBeGreaterThanOrEqual(2);+ expect(summary?.totalSeconds).toBeGreaterThanOrEqual(60 * 60);+ expect(summary?.totalBillableSeconds).toBeGreaterThanOrEqual(30 * 60);+ });++ it('reportByDay returns at least one row', async () => {+ const rows = await $mainUser.timeTracking.reportByDay({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(Array.isArray(rows)).toBe(true);+ expect(rows!.length).toBeGreaterThan(0);+ });++ it('reportByUser returns at least one row with userId', async () => {+ const rows = await $mainUser.timeTracking.reportByUser({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(Array.isArray(rows)).toBe(true);+ expect(rows!.length).toBeGreaterThan(0);+ expect(rows![0].userId).toBeDefined();+ });++ it('reportByTask returns rows grouped by task', async () => {+ const rows = await $mainUser.timeTracking.reportByTask({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(Array.isArray(rows)).toBe(true);+ const taskIds = rows!.map((r) => r.taskId);+ expect(taskIds).toContain(taskId);+ expect(taskIds).toContain(secondaryTaskId);+ });++ it('reportContributors returns at least the current user', async () => {+ const rows = await $mainUser.timeTracking.reportContributors({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(Array.isArray(rows)).toBe(true);+ expect(rows!.length).toBeGreaterThan(0);+ expect(rows!.some((r) => r.userEmail === mainUserEmail)).toBe(true);+ });++ it('reports respect goalIds intersection with accessible goals', async () => {+ const summary = await $mainUser.timeTracking.reportSummary({+ organizationId,+ goalIds: [secondaryGoalId],+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ }).catch(console.error);+ expect(summary).toBeDefined();+ expect(summary?.entriesCount).toBe(0);+ });+ });++ describe('9. Edge cases', () => {+ it('stop without an active timer returns 404', async () => {+ await stopActiveIfAny($mainUser);+ const status = await $mainUser.timeTracking.stop().catch((err) => err.status);+ expect(status).toBe(404);+ });++ it('stop with non-existent entryId returns 404', async () => {+ const status = await $mainUser.timeTracking.stop({ entryId: 999999999 }).catch((err) => err.status);+ expect(status).toBe(404);+ });++ it('update of non-existent entry returns 404', async () => {+ const status = await $mainUser.timeTracking.update({+ id: 999999999,+ description: 'nope',+ }).catch((err) => err.status);+ expect(status).toBe(404);+ });++ it('delete of non-existent entry returns 404', async () => {+ const status = await $mainUser.timeTracking.delete(999999999).catch((err) => err.status);+ expect(status).toBe(404);+ });++ it('start with non-existent taskId returns 403', async () => {+ const status = await $mainUser.timeTracking.start({ taskId: 999999999 }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchHistory of non-existent entry returns 404', async () => {+ const status = await $mainUser.timeTracking.fetchHistory(999999999).catch((err) => err.status);+ expect(status).toBe(404);+ });++ it('createManual on non-existent task returns 403 (middleware blocks)', async () => {+ const status = await $mainUser.timeTracking.createManual({+ taskId: 999999999,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('createManual with description longer than 500 characters is rejected', async () => {+ const tooLong = 'a'.repeat(501);+ const status = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ description: tooLong,+ }).catch((err) => err.status);+ expect(status).toBe(400);+ });++ it('start without taskId is rejected by middleware (400)', async () => {+ const status = await $mainUser.timeTracking.start({ taskId: undefined as unknown as number }).catch((err) => err.status);+ expect(status).toBe(400);+ });++ it('reportSummary with invalid timezone is rejected (400)', async () => {+ const status = await $mainUser.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60 * 24),+ timezone: 'Not/A_Real_Zone',+ }).catch((err) => err.status);+ expect(status).toBe(400);+ });++ it('deleting an active timer removes it and clears active state', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const result = await $mainUser.timeTracking.delete(started!.entry.id).catch(console.error);+ expect(result?.deleted).toBe(true);++ const active = await $mainUser.timeTracking.getActive().catch(console.error);+ expect(active).toBeNull();+ });+ });++ describe('10. Default goal roles include time-tracking permissions', () => {+ it('assigning default executor role grants log and view permissions', async () => {+ const roles = await $mainUser.collaboration.fetchRolesForGoal(goalId).catch(console.error);+ const executor = roles?.find((r) => r.name === 'executor');+ expect(executor).toBeDefined();++ const invited = await $mainUser.collaboration.inviteUserToGoal({+ goalId,+ email: invitedUserEmail,+ }).catch(console.error);+ expect(invited).toBeDefined();++ await $mainUser.collaboration.toggleUserRoles({+ goalId,+ userId: invited!.id,+ roles: [executor!.id],+ }).catch(console.error);++ const started = await $invitedUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();+ await $invitedUser.timeTracking.stop({ entryId: started?.entry.id }).catch(() => null);++ const entries = await $invitedUser.timeTracking.fetchEntries({ goalId }).catch((err) => err.status);+ expect(Array.isArray(entries)).toBe(true);+ });++ it('assigning default editor role grants MANAGE_ALL on time entries', async () => {+ const roles = await $mainUser.collaboration.fetchRolesForGoal(goalId).catch(console.error);+ const editor = roles?.find((r) => r.name === 'editor');+ expect(editor).toBeDefined();++ const invited = await $mainUser.collaboration.inviteUserToGoal({+ goalId,+ email: invitedUserEmail,+ }).catch(console.error);+ expect(invited).toBeDefined();++ await $mainUser.collaboration.toggleUserRoles({+ goalId,+ userId: invited!.id,+ roles: [editor!.id],+ }).catch(console.error);++ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();++ const updated = await $invitedUser.timeTracking.update({+ id: ownerEntry!.id,+ description: 'edited by editor',+ }).catch(console.error);+ expect(updated?.description).toBe('edited by editor');+ });+ });++ describe('11. canViewActiveTimer with API tokens', () => {+ const createdTokenIds: number[] = [];++ const createTokenApi = async (data: {+ name: string;+ allowedPermissions?: string[];+ allowedGoalIds?: number[];+ }) => {+ const created = await $mainUser.apiTokens.create(data);+ if (!created) throw new Error(`Failed to create token ${data.name}`);+ createdTokenIds.push(created.item.id);+ const tokenApi = new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${created.token}` },+ }));+ return { tokenApi, token: created.token, id: created.item.id };+ };++ beforeEach(async () => {+ while (createdTokenIds.length) {+ const id = createdTokenIds.pop()!;+ await $mainUser.apiTokens.delete(id).catch(() => null);+ }+ });++ it('token with TIMETRACKING_CAN_VIEW returns the active entry', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `tt-view-token-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_VIEW],+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ });++ it('token with TIMETRACKING_CAN_LOG returns the active entry', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `tt-log-token-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_LOG],+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ });++ it('token with TIMETRACKING_CAN_MANAGE_ALL returns the active entry', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `tt-manage-token-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_MANAGE_ALL],+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ });++ it('token with non-time-tracking permissions only returns 403', async () => {+ await $mainUser.timeTracking.start({ taskId }).catch(console.error);++ const { tokenApi } = await createTokenApi({+ name: `no-tt-token-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.getActive().catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('token with multiple non-time-tracking permissions still returns 403', async () => {+ await $mainUser.timeTracking.start({ taskId }).catch(console.error);++ const { tokenApi } = await createTokenApi({+ name: `mixed-no-tt-token-${timestamp}`,+ allowedPermissions: [+ TvPermissions.COMPONENT_CAN_WATCH_CONTENT,+ TvPermissions.COMPONENT_CAN_ADD_TASKS,+ TvPermissions.TASK_CAN_EDIT_DESCRIPTION,+ ],+ });++ const status = await tokenApi.timeTracking.getActive().catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('token with allowedGoalIds not containing the active timer goal returns 403', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `wrong-goal-scope-${timestamp}`,+ allowedGoalIds: [secondaryGoalId],+ });++ const status = await tokenApi.timeTracking.getActive().catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('token with allowedGoalIds containing the active timer goal returns the entry', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `right-goal-scope-${timestamp}`,+ allowedGoalIds: [goalId],+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ expect(active?.goalId).toBe(goalId);+ });++ it('token with allowedGoalIds and no active timer returns null without 403', async () => {+ await stopActiveIfAny($mainUser);++ const { tokenApi } = await createTokenApi({+ name: `no-active-${timestamp}`,+ allowedGoalIds: [secondaryGoalId],+ });++ const active = await tokenApi.timeTracking.getActive().catch((err) => err.status);+ expect(active).toBeNull();+ });++ it('token without allowedPermissions and without allowedGoalIds returns the active entry', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `unrestricted-token-${timestamp}`,+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ });++ it('token scoped both by goal and by TT permission allows reading active in scope', async () => {+ const started = await $mainUser.timeTracking.start({ taskId }).catch(console.error);+ expect(started?.entry).toBeDefined();++ const { tokenApi } = await createTokenApi({+ name: `combined-scope-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_VIEW],+ allowedGoalIds: [goalId],+ });++ const active = await tokenApi.timeTracking.getActive().catch(console.error);+ expect(active).not.toBeNull();+ expect(active?.id).toBe(started!.entry.id);+ });++ it('token with TT permission but wrong goal scope still returns 403', async () => {+ await $mainUser.timeTracking.start({ taskId }).catch(console.error);++ const { tokenApi } = await createTokenApi({+ name: `tt-perm-wrong-goal-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_VIEW],+ allowedGoalIds: [secondaryGoalId],+ });++ const status = await tokenApi.timeTracking.getActive().catch((err) => err.status);+ expect(status).toBe(403);+ });+ });++ describe('12. API token scopes on fetchEntries and reports', () => {+ const createdTokenIds: number[] = [];++ const createTokenApi = async (data: {+ name: string;+ allowedPermissions?: string[];+ allowedGoalIds?: number[];+ }) => {+ const created = await $mainUser.apiTokens.create(data);+ if (!created) throw new Error(`Failed to create token ${data.name}`);+ createdTokenIds.push(created.item.id);+ const tokenApi = new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${created.token}` },+ }));+ return { tokenApi };+ };++ beforeEach(async () => {+ while (createdTokenIds.length) {+ const id = createdTokenIds.pop()!;+ await $mainUser.apiTokens.delete(id).catch(() => null);+ }+ });++ it('fetchEntries without goal/task scope returns 403 for token with non-TT permissions only', async () => {+ const { tokenApi } = await createTokenApi({+ name: `no-tt-fetch-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.fetchEntries({ organizationId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('fetchEntries without goal/task scope succeeds for token with TT permission', async () => {+ await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);++ const { tokenApi } = await createTokenApi({+ name: `tt-view-fetch-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_VIEW],+ });++ const entries = await tokenApi.timeTracking.fetchEntries({ organizationId }).catch(console.error);+ expect(Array.isArray(entries)).toBe(true);+ expect(entries!.length).toBeGreaterThanOrEqual(1);+ });++ it('fetchEntries without scope succeeds for unrestricted token', async () => {+ const { tokenApi } = await createTokenApi({+ name: `unrestricted-fetch-${timestamp}`,+ });++ const entries = await tokenApi.timeTracking.fetchEntries({ organizationId }).catch(console.error);+ expect(Array.isArray(entries)).toBe(true);+ });++ it('fetchEntries by goalId returns 403 for token with non-TT permissions only', async () => {+ const { tokenApi } = await createTokenApi({+ name: `no-tt-fetch-goal-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.fetchEntries({ goalId }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('reportSummary returns 403 for token with non-TT permissions only', async () => {+ const { tokenApi } = await createTokenApi({+ name: `no-tt-report-summary-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('reportByDay returns 403 for token with non-TT permissions only', async () => {+ const { tokenApi } = await createTokenApi({+ name: `no-tt-report-day-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.reportByDay({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('reportSummary succeeds for token with TT permission', async () => {+ await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);++ const { tokenApi } = await createTokenApi({+ name: `tt-view-report-${timestamp}`,+ allowedPermissions: [TvPermissions.TIMETRACKING_CAN_VIEW],+ });++ const summary = await tokenApi.timeTracking.reportSummary({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60),+ }).catch(console.error);+ expect(summary).toBeDefined();+ expect(summary?.totalSeconds).toBeGreaterThanOrEqual(0);+ });++ it('reportContributors returns 403 for token with non-TT permissions only', async () => {+ const { tokenApi } = await createTokenApi({+ name: `no-tt-report-contrib-${timestamp}`,+ allowedPermissions: [TvPermissions.COMPONENT_CAN_WATCH_CONTENT],+ });++ const status = await tokenApi.timeTracking.reportContributors({+ organizationId,+ from: isoMinutesAgo(60 * 24),+ to: isoMinutesFromNow(60),+ }).catch((err) => err.status);+ expect(status).toBe(403);+ });+ });+});diff --git a/taskview-packages/taskview-api/src/api/time-tracking.ts b/taskview-packages/taskview-api/src/api/time-tracking.tsindex c886b42..0789d94 100644--- a/taskview-packages/taskview-api/src/api/time-tracking.ts+++ b/taskview-packages/taskview-api/src/api/time-tracking.ts@@ -11,11 +11,32 @@ import type {TimeEntrySummaryByGoal,TimeEntrySummaryByTask,TimeEntryUpdateArg,+ TimeReportByDayRow,+ TimeReportByTaskRow,+ TimeReportByUserRow,+ TimeReportContributor,+ TimeReportFilters,+ TimeReportSummary,} from './time-tracking.types'export default class TvTimeTrackingApi extends TvApiBase {protected moduleUrl = '/module/time-tracking'+ private static reportParams(filters: TimeReportFilters) {+ const params: Record<string, string | number | boolean> = {+ organizationId: filters.organizationId,+ from: filters.from instanceof Date ? filters.from.toISOString() : filters.from,+ to: filters.to instanceof Date ? filters.to.toISOString() : filters.to,+ }+ if (filters.goalIds && filters.goalIds.length > 0) {+ params.goalIds = filters.goalIds.join(',')+ }+ if (filters.userId !== undefined) params.userId = filters.userId+ if (filters.billable !== undefined) params.billable = filters.billable+ if (filters.timezone !== undefined) params.timezone = filters.timezone+ return params+ }+public async start(data: TimeEntryStartArg) {return this.request(this.$axios.post<AppResponse<TimeEntryStartResult>>(`${this.moduleUrl}/start`, data))}@@ -44,8 +65,11 @@ export default class TvTimeTrackingApi extends TvApiBase {}public async fetchEntries(filters: TimeEntryFetchFilters = {}) {+ const { goalIds, ...rest } = filters+ const params: Record<string, unknown> = { ...rest }+ if (goalIds && goalIds.length > 0) params.goalIds = goalIds.join(',')return this.request(- this.$axios.get<AppResponse<TimeEntryItem[]>>(`${this.moduleUrl}/entries`, { params: filters }),+ this.$axios.get<AppResponse<TimeEntryItem[]>>(`${this.moduleUrl}/entries`, { params }),)}@@ -66,4 +90,44 @@ export default class TvTimeTrackingApi extends TvApiBase {this.$axios.get<AppResponse<TimeEntryHistoryItem[]>>(`${this.moduleUrl}/entries/${entryId}/history`),)}++ public async reportSummary(filters: TimeReportFilters) {+ return this.request(+ this.$axios.get<AppResponse<TimeReportSummary>>(`${this.moduleUrl}/reports/summary`, {+ params: TvTimeTrackingApi.reportParams(filters),+ }),+ )+ }++ public async reportByDay(filters: TimeReportFilters) {+ return this.request(+ this.$axios.get<AppResponse<TimeReportByDayRow[]>>(`${this.moduleUrl}/reports/by-day`, {+ params: TvTimeTrackingApi.reportParams(filters),+ }),+ )+ }++ public async reportByUser(filters: TimeReportFilters) {+ return this.request(+ this.$axios.get<AppResponse<TimeReportByUserRow[]>>(`${this.moduleUrl}/reports/by-user`, {+ params: TvTimeTrackingApi.reportParams(filters),+ }),+ )+ }++ public async reportByTask(filters: TimeReportFilters) {+ return this.request(+ this.$axios.get<AppResponse<TimeReportByTaskRow[]>>(`${this.moduleUrl}/reports/by-task`, {+ params: TvTimeTrackingApi.reportParams(filters),+ }),+ )+ }++ public async reportContributors(filters: TimeReportFilters) {+ return this.request(+ this.$axios.get<AppResponse<TimeReportContributor[]>>(`${this.moduleUrl}/reports/contributors`, {+ params: TvTimeTrackingApi.reportParams(filters),+ }),+ )+ }}diff --git a/taskview-packages/taskview-api/src/api/time-tracking.types.ts b/taskview-packages/taskview-api/src/api/time-tracking.types.tsindex e52f8b3..a59a261 100644--- a/taskview-packages/taskview-api/src/api/time-tracking.types.ts+++ b/taskview-packages/taskview-api/src/api/time-tracking.types.ts@@ -46,9 +46,12 @@ export type TimeEntryUpdateArg = {}export type TimeEntryFetchFilters = {+ organizationId?: numbergoalId?: number+ goalIds?: number[]taskId?: numberuserId?: number+ billable?: booleanfrom?: string | Dateto?: string | Datelimit?: number@@ -77,3 +80,47 @@ export const TIME_ENTRY_SOURCE = {TIMER: 0,MANUAL: 1,} as const++export type TimeReportFilters = {+ organizationId: number+ goalIds?: number[]+ userId?: number+ from: string | Date+ to: string | Date+ billable?: boolean+ timezone?: string+}++export type TimeReportByDayRow = {+ day: string+ totalSeconds: number+ entriesCount: number+}++export type TimeReportByUserRow = {+ userId: number+ userEmail: string | null+ totalSeconds: number+ entriesCount: number+}++export type TimeReportByTaskRow = {+ taskId: number+ taskDescription: string | null+ goalId: number+ totalSeconds: number+ entriesCount: number+}++export type TimeReportSummary = {+ totalSeconds: number+ totalBillableSeconds: number+ entriesCount: number+}++export type TimeReportContributor = {+ userId: number+ userEmail: string | null+ totalSeconds: number+ entriesCount: number+}diff --git a/taskview-packages/taskview-mcp/src/tools/time-tracking.ts b/taskview-packages/taskview-mcp/src/tools/time-tracking.tsindex a090538..e0eceaa 100644--- a/taskview-packages/taskview-mcp/src/tools/time-tracking.ts+++ b/taskview-packages/taskview-mcp/src/tools/time-tracking.ts@@ -141,6 +141,70 @@ export function registerTimeTrackingTools(server: McpServer, api: TvApi) {},)+ server.registerTool(+ 'get_time_report',+ {+ description:+ 'Aggregated time report. Choose scope: by-day (daily totals), by-user (per member), by-task (per task), summary (totals + billable). Filter by org, optional projects, optional user, date range.',+ inputSchema: {+ scope: z.enum(['by-day', 'by-user', 'by-task', 'summary']).describe('Aggregation scope'),+ organizationId: z.coerce.number().describe('Organization ID'),+ from: z.string().describe('ISO 8601 start date (inclusive)'),+ to: z.string().describe('ISO 8601 end date (inclusive)'),+ goalIds: z.array(z.coerce.number()).optional().describe('Limit to specific projects; if omitted — all projects user has VIEW access to'),+ userId: z.coerce.number().optional().describe('Limit to a specific user; if omitted — all visible members'),+ billable: z.boolean().optional().describe('Filter by billable flag'),+ },+ },+ async (params) => {+ try {+ const filters = {+ organizationId: params.organizationId,+ goalIds: params.goalIds,+ userId: params.userId,+ from: params.from,+ to: params.to,+ billable: params.billable,+ }+ let result: unknown+ switch (params.scope) {+ case 'by-day': result = await api.timeTracking.reportByDay(filters); break+ case 'by-user': result = await api.timeTracking.reportByUser(filters); break+ case 'by-task': result = await api.timeTracking.reportByTask(filters); break+ case 'summary': result = await api.timeTracking.reportSummary(filters); break+ }+ return ok(result)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'get_time_contributors',+ {+ description:+ 'List users who logged time in the given projects and date range, with total seconds and entry counts. Useful for "who worked on this project last month".',+ inputSchema: {+ organizationId: z.coerce.number().describe('Organization ID'),+ from: z.string().describe('ISO 8601 start date (inclusive)'),+ to: z.string().describe('ISO 8601 end date (inclusive)'),+ goalIds: z.array(z.coerce.number()).optional().describe('Limit to specific projects'),+ billable: z.boolean().optional().describe('Filter by billable flag'),+ },+ },+ async (params) => {+ try {+ const result = await api.timeTracking.reportContributors({+ organizationId: params.organizationId,+ goalIds: params.goalIds,+ from: params.from,+ to: params.to,+ billable: params.billable,+ })+ return ok(result)+ } catch (e) { return err(e) }+ },+ )+server.registerTool('delete_time_entry',{diff --git a/web/src/components/UserMenu.vue b/web/src/components/UserMenu.vueindex be10128..bcecb41 100644--- a/web/src/components/UserMenu.vue+++ b/web/src/components/UserMenu.vue@@ -183,6 +183,13 @@ const items = computed<DropdownMenuItem[][]>(() => [router.push({ name: 'analytics' })},},+ {+ label: t('userMenu.timeReports'),+ icon: 'i-lucide-clock-4',+ onSelect() {+ router.push({ name: 'time-reports' })+ },+ },],[{diff --git a/web/src/components/features/tasks/parts/TaskTimeTracking.vue b/web/src/components/features/tasks/parts/TaskTimeTracking.vueindex 71ce0ff..72f01c9 100644--- a/web/src/components/features/tasks/parts/TaskTimeTracking.vue+++ b/web/src/components/features/tasks/parts/TaskTimeTracking.vue@@ -175,6 +175,7 @@ const onUpdate = (payload: TimeEntryFormPayload & { id: number }) =>startedAt: payload.startedAt,endedAt: payload.endedAt,description: payload.description || undefined,+ billable: payload.billable,})const onSubmitManual = async (payload: TimeEntryFormPayload) => {@@ -183,6 +184,7 @@ const onSubmitManual = async (payload: TimeEntryFormPayload) => {startedAt: payload.startedAt,endedAt: payload.endedAt,description: payload.description || undefined,+ billable: payload.billable,})if (created) manualOpen.value = false}diff --git a/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vue b/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vueindex 040a17e..b327c07 100644--- a/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vue+++ b/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vue@@ -50,6 +50,7 @@:initial-started-at="entry.startedAt":initial-ended-at="entry.endedAt ?? undefined":initial-description="entry.description ?? ''"+ :initial-billable="entry.billable"class="border-t border-default"@submit="onSubmit"@cancel="editing = false"diff --git a/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vue b/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vueindex bef24fc..5a1abec 100644--- a/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vue+++ b/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vue@@ -56,6 +56,11 @@/></UFormField>+ <UCheckbox+ v-model="billable"+ :label="t('timeTracking.billable')"+ />+<div class="flex justify-end gap-2"><UButton:label="t('timeTracking.cancel')"@@ -85,12 +90,14 @@ export type TimeEntryFormPayload = {startedAt: stringendedAt: stringdescription: string+ billable: boolean}const props = defineProps<{initialStartedAt?: stringinitialEndedAt?: stringinitialDescription?: string+ initialBillable?: booleansubmitLabel?: string}>()@@ -118,6 +125,7 @@ const endDate = shallowRef<CalendarDate | undefined>(initialEnd.date)const startTime = shallowRef<Time | undefined>(initialStart.time)const endTime = shallowRef<Time | undefined>(initialEnd.time)const description = ref(props.initialDescription ?? '')+const billable = ref(props.initialBillable ?? true)const startOpen = ref(false)const endOpen = ref(false)@@ -154,6 +162,7 @@ const onSubmit = () => {startedAt: startJs.value.toISOString(),endedAt: endJs.value.toISOString(),description: description.value,+ billable: billable.value,})}</script>diff --git a/web/src/components/features/time-reports/TimeReportsByDayTable.vue b/web/src/components/features/time-reports/TimeReportsByDayTable.vuenew file mode 100644index 0000000..2c7bb26--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsByDayTable.vue@@ -0,0 +1,32 @@+<template>+ <UTable+ :data="byDay"+ :columns="columns"+ :loading="loading"+ :empty="t('timeTracking.reports.empty')"+ />+</template>++<script setup lang="ts">+import { h } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import type { TableColumn } from '@nuxt/ui'+import type { TimeReportByDayRow } from 'taskview-api'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import { formatDuration } from '@/helpers/formatDuration'++const { t } = useI18n()+const store = useTimeReportsStore()+const { byDay, loading } = storeToRefs(store)++const columns: TableColumn<TimeReportByDayRow>[] = [+ { accessorKey: 'day', header: t('timeTracking.reports.colDay') },+ {+ accessorKey: 'totalSeconds',+ header: t('timeTracking.reports.colHours'),+ cell: ({ row }) => h('span', { class: 'font-mono' }, formatDuration(row.original.totalSeconds)),+ },+ { accessorKey: 'entriesCount', header: t('timeTracking.reports.colEntries') },+]+</script>diff --git a/web/src/components/features/time-reports/TimeReportsByTaskTable.vue b/web/src/components/features/time-reports/TimeReportsByTaskTable.vuenew file mode 100644index 0000000..fb86d1b--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsByTaskTable.vue@@ -0,0 +1,61 @@+<template>+ <UTable+ :data="byTask"+ :columns="columns"+ :empty="t('timeTracking.reports.empty')"+ />+</template>++<script setup lang="ts">+import { h, resolveComponent } from 'vue'+import { useI18n } from 'vue-i18n'+import { useRouter } from 'vue-router'+import { storeToRefs } from 'pinia'+import type { TableColumn } from '@nuxt/ui'+import type { TimeReportByTaskRow } from 'taskview-api'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import { formatDuration } from '@/helpers/formatDuration'++const { t } = useI18n()+const router = useRouter()+const store = useTimeReportsStore()+const { byTask } = storeToRefs(store)++const UButton = resolveComponent('UButton')++const openTask = (row: TimeReportByTaskRow) => {+ router.push({+ name: 'user',+ params: { projectId: String(row.goalId), taskId: String(row.taskId) },+ })+}++const columns: TableColumn<TimeReportByTaskRow>[] = [+ {+ accessorKey: 'taskDescription',+ header: t('timeTracking.reports.colTask'),+ cell: ({ row }) => row.original.taskDescription ?? `#${row.original.taskId}`,+ },+ {+ accessorKey: 'totalSeconds',+ header: t('timeTracking.reports.colHours'),+ cell: ({ row }) => h('span', { class: 'font-mono' }, formatDuration(row.original.totalSeconds)),+ },+ {+ accessorKey: 'entriesCount',+ header: t('timeTracking.reports.colEntries'),+ },+ {+ id: 'actions',+ header: '',+ cell: ({ row }) => h(UButton, {+ icon: 'i-lucide-arrow-up-right',+ color: 'neutral',+ variant: 'ghost',+ size: 'xs',+ 'aria-label': t('timeTracking.reports.openTask'),+ onClick: () => openTask(row.original),+ }),+ },+]+</script>diff --git a/web/src/components/features/time-reports/TimeReportsByUserTable.vue b/web/src/components/features/time-reports/TimeReportsByUserTable.vuenew file mode 100644index 0000000..a207ec1--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsByUserTable.vue@@ -0,0 +1,38 @@+<template>+ <UTable+ :data="byUser"+ :columns="columns"+ :empty="t('timeTracking.reports.empty')"+ />+</template>++<script setup lang="ts">+import { h } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import type { TableColumn } from '@nuxt/ui'+import type { TimeReportByUserRow } from 'taskview-api'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import { formatDuration } from '@/helpers/formatDuration'++const { t } = useI18n()+const store = useTimeReportsStore()+const { byUser } = storeToRefs(store)++const columns: TableColumn<TimeReportByUserRow>[] = [+ {+ accessorKey: 'userEmail',+ header: t('timeTracking.reports.colUser'),+ cell: ({ row }) => row.original.userEmail ?? `User #${row.original.userId}`,+ },+ {+ accessorKey: 'totalSeconds',+ header: t('timeTracking.reports.colHours'),+ cell: ({ row }) => h('span', { class: 'font-mono' }, formatDuration(row.original.totalSeconds)),+ },+ {+ accessorKey: 'entriesCount',+ header: t('timeTracking.reports.colEntries'),+ },+]+</script>diff --git a/web/src/components/features/time-reports/TimeReportsEntriesList.vue b/web/src/components/features/time-reports/TimeReportsEntriesList.vuenew file mode 100644index 0000000..e961149--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsEntriesList.vue@@ -0,0 +1,53 @@+<template>+ <div class="flex flex-col gap-1">+ <h3 class="text-sm font-medium">+ {{ t('timeTracking.reports.recentEntries') }}+ </h3>+ <div+ v-if="entries.length === 0"+ class="text-xs text-muted py-3 text-center"+ >+ {{ t('timeTracking.reports.empty') }}+ </div>+ <div+ v-else+ class="flex flex-col gap-1 max-h-80 overflow-y-auto pr-1"+ >+ <div+ v-for="entry in entries"+ :key="entry.id"+ class="flex items-center justify-between gap-2 px-2 py-1.5 rounded bg-elevated/50 text-sm"+ >+ <div class="flex flex-col min-w-0 flex-1">+ <div class="flex items-center gap-2 text-xs text-muted">+ <span class="font-mono">{{ formatDate(entry.startedAt) }}</span>+ <span class="truncate">· {{ entry.userEmail ?? `#${entry.userId}` }}</span>+ </div>+ <span+ v-if="entry.description"+ class="truncate"+ >{{ entry.description }}</span>+ </div>+ <UBadge+ :label="formatDuration(entry.durationSeconds ?? 0)"+ color="neutral"+ variant="subtle"+ size="xs"+ />+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import { formatDuration } from '@/helpers/formatDuration'++const { t } = useI18n()+const store = useTimeReportsStore()+const { entries } = storeToRefs(store)++const formatDate = (iso: string) => new Date(iso).toLocaleString()+</script>diff --git a/web/src/components/features/time-reports/TimeReportsFilters.vue b/web/src/components/features/time-reports/TimeReportsFilters.vuenew file mode 100644index 0000000..d9c5422--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsFilters.vue@@ -0,0 +1,170 @@+<template>+ <div class="flex flex-wrap items-center gap-2">+ <UPopover v-model:open="fromOpen">+ <UButton+ :label="formattedFrom"+ icon="i-lucide-calendar"+ color="neutral"+ variant="outline"+ size="lg"+ :ui="activatorStyle"+ />+ <template #content>+ <div class="p-2">+ <UCalendar+ v-model="fromDate"+ :max-value="toDate"+ />+ </div>+ </template>+ </UPopover>++ <span class="text-muted text-sm">—</span>++ <UPopover v-model:open="toOpen">+ <UButton+ :label="formattedTo"+ icon="i-lucide-calendar-check"+ color="neutral"+ variant="outline"+ size="lg"+ :ui="activatorStyle"+ />+ <template #content>+ <div class="p-2">+ <UCalendar+ v-model="toDate"+ :min-value="fromDate"+ />+ </div>+ </template>+ </UPopover>++ <USelectMenu+ v-if="availableProjects.length > 0"+ v-model="selectedGoalIds"+ :items="projectOptions"+ multiple+ :placeholder="t('timeTracking.reports.allProjects')"+ class="min-w-56"+ size="lg"+ />++ <USelectMenu+ v-if="canFilterByUser && contributorOptions.length > 0"+ v-model="selectedUser"+ :items="contributorOptions"+ :placeholder="t('timeTracking.reports.allUsers')"+ class="min-w-56"+ size="lg"+ />++ <UCheckbox+ v-model="billableOnly"+ :label="t('timeTracking.reports.billableOnly')"+ :ui="{root: 'items-center'}"+ />++ <UButton+ v-if="selectedUser"+ icon="i-lucide-x"+ color="neutral"+ variant="ghost"+ size="sm"+ :aria-label="t('timeTracking.reports.clearUser')"+ @click="store.setUserId(null)"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useDateFormat } from '@vueuse/core'+import { CalendarDate } from '@internationalized/date'+import type { GoalItem } from 'taskview-api'+import { useTimeReportsStore } from '@/stores/time-reports.store'++const props = defineProps<{+ availableProjects: GoalItem[]+ canFilterByUser: boolean+}>()++const { t } = useI18n()+const store = useTimeReportsStore()+const { filters, contributors } = storeToRefs(store)++const fromOpen = ref(false)+const toOpen = ref(false)++const activatorStyle = {+ leadingIcon: 'size-4.5',+}++const isoToCalendarDate = (iso: string): CalendarDate => {+ const d = new Date(iso)+ return new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate())+}++const calendarDateToStartOfDayIso = (d: CalendarDate): string =>+ new Date(d.year, d.month - 1, d.day, 0, 0, 0, 0).toISOString()++const calendarDateToEndOfDayIso = (d: CalendarDate): string =>+ new Date(d.year, d.month - 1, d.day, 23, 59, 59, 999).toISOString()++const fromDate = computed<CalendarDate>({+ get: () => isoToCalendarDate(filters.value.from),+ set: (v) => store.setPeriod(calendarDateToStartOfDayIso(v), filters.value.to),+})++const toDate = computed<CalendarDate>({+ get: () => isoToCalendarDate(filters.value.to),+ set: (v) => store.setPeriod(filters.value.from, calendarDateToEndOfDayIso(v)),+})++const formattedFrom = computed(() => useDateFormat(new Date(filters.value.from), 'DD MMM YYYY').value)+const formattedTo = computed(() => useDateFormat(new Date(filters.value.to), 'DD MMM YYYY').value)++const projectOptions = computed(() =>+ props.availableProjects.map((p) => ({ label: p.name, value: p.id })),+)++const selectedGoalIds = computed({+ get: () => projectOptions.value.filter((o) => filters.value.goalIds.includes(o.value)),+ set: (v) => store.setGoalIds(v.map((o) => o.value)),+})++const contributorOptions = computed(() =>+ contributors.value.map((c) => ({+ label: c.userEmail ?? `User #${c.userId}`,+ value: c.userId,+ })),+)++const selectedUser = computed({+ get: () => contributorOptions.value.find((o) => o.value === filters.value.userId),+ set: (v) => store.setUserId(v?.value ?? null),+})++const billableOnly = computed({+ get: () => filters.value.billable === true,+ set: (v) => store.setBillable(v ? true : null),+})++watch(+ () => [+ filters.value.organizationId,+ filters.value.from,+ filters.value.to,+ filters.value.goalIds,+ filters.value.userId,+ filters.value.billable,+ ],+ () => {+ if (!store.initialized) return+ store.refreshAll()+ },+ { deep: true },+)+</script>diff --git a/web/src/components/features/time-reports/TimeReportsKpis.vue b/web/src/components/features/time-reports/TimeReportsKpis.vuenew file mode 100644index 0000000..6ad3c3f--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsKpis.vue@@ -0,0 +1,43 @@+<template>+ <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">+ <UCard>+ <div class="text-xs text-muted">+ {{ t('timeTracking.reports.kpiTotal') }}+ </div>+ <div class="text-2xl font-mono font-semibold mt-1">+ {{ totalLabel }}+ </div>+ </UCard>+ <UCard>+ <div class="text-xs text-muted">+ {{ t('timeTracking.reports.kpiBillable') }}+ </div>+ <div class="text-2xl font-mono font-semibold mt-1">+ {{ billableLabel }}+ </div>+ </UCard>+ <UCard>+ <div class="text-xs text-muted">+ {{ t('timeTracking.reports.kpiEntries') }}+ </div>+ <div class="text-2xl font-mono font-semibold mt-1">+ {{ summary?.entriesCount ?? 0 }}+ </div>+ </UCard>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import { formatDuration } from '@/helpers/formatDuration'++const { t } = useI18n()+const store = useTimeReportsStore()+const { summary } = storeToRefs(store)++const totalLabel = computed(() => formatDuration(summary.value?.totalSeconds ?? 0))+const billableLabel = computed(() => formatDuration(summary.value?.totalBillableSeconds ?? 0))+</script>diff --git a/web/src/components/features/time-reports/TimeReportsLayout.vue b/web/src/components/features/time-reports/TimeReportsLayout.vuenew file mode 100644index 0000000..248b8ac--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsLayout.vue@@ -0,0 +1,51 @@+<template>+ <div class="flex flex-col gap-4 p-4">+ <TimeReportsFilters+ :available-projects="availableProjects"+ :can-filter-by-user="canFilterByUser"+ />++ <TimeReportsKpis />++ <TimeReportsViewTabs />++ <TimeReportsEntriesList />+ </div>+</template>++<script setup lang="ts">+import { onMounted, watch } from 'vue'+import type { GoalItem } from 'taskview-api'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import TimeReportsFilters from './TimeReportsFilters.vue'+import TimeReportsKpis from './TimeReportsKpis.vue'+import TimeReportsViewTabs from './TimeReportsViewTabs.vue'+import TimeReportsEntriesList from './TimeReportsEntriesList.vue'++const props = defineProps<{+ organizationId: number+ availableProjects: GoalItem[]+ defaultGoalIds?: number[]+ canFilterByUser: boolean+}>()++const store = useTimeReportsStore()++onMounted(() => {+ store.init({ organizationId: props.organizationId, goalIds: props.defaultGoalIds ?? [] })+})++watch(+ () => props.organizationId,+ (id) => {+ store.setOrganization(id)+ },+)++watch(+ () => props.defaultGoalIds,+ (ids) => {+ store.setGoalIds(ids ?? [])+ },+)+</script>diff --git a/web/src/components/features/time-reports/TimeReportsViewTabs.vue b/web/src/components/features/time-reports/TimeReportsViewTabs.vuenew file mode 100644index 0000000..93612c9--- /dev/null+++ b/web/src/components/features/time-reports/TimeReportsViewTabs.vue@@ -0,0 +1,42 @@+<template>+ <UTabs+ v-model="active"+ :items="items"+ class="w-full"+ >+ <template #by-task>+ <TimeReportsByTaskTable />+ </template>+ <template #by-user>+ <TimeReportsByUserTable />+ </template>+ <template #by-day>+ <TimeReportsByDayTable />+ </template>+ </UTabs>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useTimeReportsStore } from '@/stores/time-reports.store'+import TimeReportsByTaskTable from './TimeReportsByTaskTable.vue'+import TimeReportsByUserTable from './TimeReportsByUserTable.vue'+import TimeReportsByDayTable from './TimeReportsByDayTable.vue'++const { t } = useI18n()+const store = useTimeReportsStore()+const { view } = storeToRefs(store)++const items = computed(() => [+ { label: t('timeTracking.reports.byTask'), slot: 'by-task' as const, value: 'by-task' },+ { label: t('timeTracking.reports.byUser'), slot: 'by-user' as const, value: 'by-user' },+ { label: t('timeTracking.reports.byDay'), slot: 'by-day' as const, value: 'by-day' },+])++const active = computed({+ get: () => view.value,+ set: (v) => store.setView(v as 'by-task' | 'by-user' | 'by-day'),+})+</script>diff --git a/web/src/helpers/timeReports.ts b/web/src/helpers/timeReports.tsnew file mode 100644index 0000000..edab4e9--- /dev/null+++ b/web/src/helpers/timeReports.ts@@ -0,0 +1,48 @@+import axios from 'axios'+import type { TimeReportFilters } from 'taskview-api'+import type { TimeReportsFiltersState } from '@/stores/time-reports.types'++export function resolveTimeReportsErrorKey(err: unknown): string {+ if (axios.isAxiosError(err)) {+ const status = err.response?.status+ if (status === 403) return 'timeTracking.errors.forbidden'+ if (status === 400) return 'timeTracking.errors.validation'+ if (status === undefined) return 'timeTracking.errors.network'+ }+ return 'timeTracking.errors.generic'+}++export function todayEndOfDayIso(): string {+ const d = new Date()+ d.setHours(23, 59, 59, 999)+ return d.toISOString()+}++export function weekAgoStartOfDayIso(): string {+ const d = new Date()+ d.setDate(d.getDate() - 7)+ d.setHours(0, 0, 0, 0)+ return d.toISOString()+}++export function detectTimezone(): string | undefined {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone+ }+ catch {+ return undefined+ }+}++export function toTimeReportFilters(state: TimeReportsFiltersState): TimeReportFilters | null {+ if (state.organizationId === null) return null+ return {+ organizationId: state.organizationId,+ goalIds: state.goalIds.length > 0 ? state.goalIds : undefined,+ userId: state.userId ?? undefined,+ from: state.from,+ to: state.to,+ billable: state.billable ?? undefined,+ timezone: detectTimezone(),+ }+}diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex ad9c9af..d401651 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -437,6 +437,7 @@ export default {accountSettings: 'Account settings',organizations: 'Organizations',analytics: 'Analytics',+ timeReports: 'Time reports',switchOrganization: 'Switch organization',logout: 'Log out',logoutFailed: 'Logout failed',@@ -689,6 +690,7 @@ export default {startedAt: 'Started at',endedAt: 'Ended at',description: 'Description',+ billable: 'Billable',save: 'Save',cancel: 'Cancel',willStopOther: 'Starting will stop your current timer on another task',@@ -707,5 +709,26 @@ export default {validation: 'Invalid input data',network: 'Network error. Check your connection.',},+ reports: {+ title: 'Time reports',+ allProjects: 'All projects',+ allUsers: 'All users',+ clearUser: 'Clear user filter',+ billableOnly: 'Billable only',+ openTask: 'Open task',+ kpiTotal: 'Total time',+ kpiBillable: 'Billable',+ kpiEntries: 'Entries',+ byTask: 'By task',+ byUser: 'By user',+ byDay: 'By day',+ colTask: 'Task',+ colUser: 'User',+ colDay: 'Day',+ colHours: 'Time',+ colEntries: 'Entries',+ empty: 'No data for the selected filters',+ recentEntries: 'Recent entries',+ },},}diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 026fc48..edb0c7f 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -409,6 +409,7 @@ export default {accountSettings: 'Настройки аккаунта',organizations: 'Организации',analytics: 'Аналитика',+ timeReports: 'Отчёты по времени',switchOrganization: 'Переключить организацию',logout: 'Выйти',logoutFailed: 'Не удалось выйти',@@ -621,6 +622,7 @@ export default {startedAt: 'Начало',endedAt: 'Окончание',description: 'Описание',+ billable: 'Оплачиваемое',save: 'Сохранить',cancel: 'Отмена',willStopOther: 'Запуск остановит ваш текущий таймер на другой задаче',@@ -639,5 +641,26 @@ export default {validation: 'Некорректные данные',network: 'Ошибка сети. Проверьте подключение.',},+ reports: {+ title: 'Отчёты по времени',+ allProjects: 'Все проекты',+ allUsers: 'Все пользователи',+ clearUser: 'Сбросить фильтр по пользователю',+ billableOnly: 'Только оплачиваемое',+ openTask: 'Открыть задачу',+ kpiTotal: 'Всего',+ kpiBillable: 'Оплачиваемое',+ kpiEntries: 'Записей',+ byTask: 'По задачам',+ byUser: 'По пользователям',+ byDay: 'По дням',+ colTask: 'Задача',+ colUser: 'Пользователь',+ colDay: 'День',+ colHours: 'Время',+ colEntries: 'Записей',+ empty: 'Нет данных по выбранным фильтрам',+ recentEntries: 'Последние записи',+ },},}diff --git a/web/src/main.ts b/web/src/main.tsindex bedc115..962e344 100644--- a/web/src/main.ts+++ b/web/src/main.ts@@ -84,6 +84,16 @@ const router = createRouter({name: 'analytics',component: () => import('./pages/user/analytics.vue'),},+ {+ path: 'time-reports',+ name: 'time-reports',+ component: () => import('./pages/user/time-reports.vue'),+ },+ {+ path: ':projectId/time-reports',+ name: 'project-time-reports',+ component: () => import('./pages/user/project-time-reports.vue'),+ },{path: ':projectId?/:listId?/:taskId?',name: 'user',diff --git a/web/src/pages/user/project-time-reports.vue b/web/src/pages/user/project-time-reports.vuenew file mode 100644index 0000000..d90da29--- /dev/null+++ b/web/src/pages/user/project-time-reports.vue@@ -0,0 +1,51 @@+<template>+ <UDashboardPanel id="project-time-reports">+ <template #header>+ <UDashboardNavbar :title="t('timeTracking.reports.title')" />+ </template>+ <template #body>+ <TimeReportsLayout+ v-if="orgId !== null && projectId !== null"+ :organization-id="orgId"+ :available-projects="visibleProjects"+ :default-goal-ids="defaultGoalIds"+ :can-filter-by-user="canManageAll"+ />+ </template>+ </UDashboardPanel>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useRoute } from 'vue-router'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { TvPermissions } from 'taskview-api'+import { useOrganizationStore } from '@/stores/organization.store'+import { useGoalsStore } from '@/stores/goals.store'+import TimeReportsLayout from '@/components/features/time-reports/TimeReportsLayout.vue'++const { t } = useI18n()+const route = useRoute()+const orgStore = useOrganizationStore()+const goalsStore = useGoalsStore()+const { currentOrg } = storeToRefs(orgStore)+const { goals } = storeToRefs(goalsStore)++const orgId = computed(() => currentOrg.value?.id ?? null)+const projectId = computed(() => {+ const raw = route.params.projectId+ const n = Number(Array.isArray(raw) ? raw[0] : raw)+ return Number.isFinite(n) && n > 0 ? n : null+})++const currentGoal = computed(() => goals.value.find((g) => g.id === projectId.value))++const visibleProjects = computed(() => (currentGoal.value ? [currentGoal.value] : []))++const defaultGoalIds = computed(() => (projectId.value !== null ? [projectId.value] : undefined))++const canManageAll = computed(+ () => currentGoal.value?.permissions[TvPermissions.TIMETRACKING_CAN_MANAGE_ALL] === true,+)+</script>diff --git a/web/src/pages/user/time-reports.vue b/web/src/pages/user/time-reports.vuenew file mode 100644index 0000000..ba01ff4--- /dev/null+++ b/web/src/pages/user/time-reports.vue@@ -0,0 +1,46 @@+<template>+ <UDashboardPanel id="time-reports">+ <template #header>+ <UDashboardNavbar :title="t('timeTracking.reports.title')" />+ </template>+ <template #body>+ <TimeReportsLayout+ v-if="orgId !== null"+ :organization-id="orgId"+ :available-projects="visibleProjects"+ :can-filter-by-user="hasAnyManageAll"+ />+ </template>+ </UDashboardPanel>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { TvPermissions } from 'taskview-api'+import { useOrganizationStore } from '@/stores/organization.store'+import { useGoalsStore } from '@/stores/goals.store'+import TimeReportsLayout from '@/components/features/time-reports/TimeReportsLayout.vue'++const { t } = useI18n()+const orgStore = useOrganizationStore()+const goalsStore = useGoalsStore()+const { currentOrg } = storeToRefs(orgStore)+const { goals } = storeToRefs(goalsStore)++const orgId = computed(() => currentOrg.value?.id ?? null)++const visibleProjects = computed(() =>+ goals.value.filter(+ (g) =>+ g.organizationId === orgId.value &&+ (g.permissions[TvPermissions.TIMETRACKING_CAN_VIEW] ||+ g.permissions[TvPermissions.TIMETRACKING_CAN_MANAGE_ALL]),+ ),+)++const hasAnyManageAll = computed(() =>+ visibleProjects.value.some((g) => g.permissions[TvPermissions.TIMETRACKING_CAN_MANAGE_ALL]),+)+</script>diff --git a/web/src/stores/time-reports.store.ts b/web/src/stores/time-reports.store.tsnew file mode 100644index 0000000..bc6b016--- /dev/null+++ b/web/src/stores/time-reports.store.ts@@ -0,0 +1,151 @@+import { defineStore } from 'pinia'+import { nextTick } from 'vue'+import type {+ TimeReportByDayRow,+ TimeReportByTaskRow,+ TimeReportByUserRow,+ TimeReportFilters,+} from 'taskview-api'+import { $tvApi } from '@/plugins/axios'+import {+ resolveTimeReportsErrorKey,+ toTimeReportFilters,+ todayEndOfDayIso,+ weekAgoStartOfDayIso,+} from '@/helpers/timeReports'+import type {+ ReportView,+ TimeReportsInitParams,+ TimeReportsState,+ TimeReportViewData,+} from './time-reports.types'++export const useTimeReportsStore = defineStore('timeReports', {+ state: (): TimeReportsState => ({+ filters: {+ organizationId: null,+ goalIds: [],+ userId: null,+ from: weekAgoStartOfDayIso(),+ to: todayEndOfDayIso(),+ billable: true,+ },+ view: 'by-task',+ summary: null,+ byDay: [],+ byUser: [],+ byTask: [],+ contributors: [],+ entries: [],+ loading: false,+ initialized: false,+ requestId: 0,+ lastError: null,+ }),+ actions: {+ setError(err: unknown): void {+ this.lastError = { key: resolveTimeReportsErrorKey(err), ts: Date.now() }+ },++ async init(params: TimeReportsInitParams): Promise<void> {+ this.initialized = false+ this.filters.organizationId = params.organizationId+ this.filters.goalIds = params.goalIds+ await nextTick()+ this.initialized = true+ await this.refreshAll()+ },++ setOrganization(orgId: number): void {+ this.filters.organizationId = orgId+ },++ async setView(view: ReportView): Promise<void> {+ if (this.view === view) return+ this.view = view+ await this.fetchCurrentView()+ },++ setPeriod(from: string, to: string): void {+ this.filters.from = from+ this.filters.to = to+ },++ setGoalIds(ids: number[]): void {+ this.filters.goalIds = ids+ },++ setUserId(id: number | null): void {+ this.filters.userId = id+ },++ setBillable(value: boolean | null): void {+ this.filters.billable = value+ },++ async refreshAll(): Promise<void> {+ const filters = toTimeReportFilters(this.filters)+ if (!filters) return+ const contributorsFilters = { ...filters, userId: undefined, billable: undefined }+ const view = this.view+ const myId = ++this.requestId+ this.loading = true+ try {+ const [summary, contributors, entries, viewData] = await Promise.all([+ $tvApi.timeTracking.reportSummary(filters),+ $tvApi.timeTracking.reportContributors(contributorsFilters),+ $tvApi.timeTracking.fetchEntries({+ organizationId: this.filters.organizationId ?? undefined,+ goalIds: this.filters.goalIds.length > 0 ? this.filters.goalIds : undefined,+ userId: this.filters.userId ?? undefined,+ billable: this.filters.billable ?? undefined,+ from: this.filters.from,+ to: this.filters.to,+ limit: 50,+ }),+ this.fetchViewData(view, filters),+ ])+ if (myId !== this.requestId) return+ this.summary = summary ?? null+ this.contributors = contributors ?? []+ this.entries = entries ?? []+ this.assignViewData(view, viewData)+ } catch (err) {+ if (myId !== this.requestId) return+ this.setError(err)+ } finally {+ if (myId === this.requestId) this.loading = false+ }+ },++ async fetchCurrentView(): Promise<void> {+ const filters = toTimeReportFilters(this.filters)+ if (!filters) return+ const view = this.view+ const myId = ++this.requestId+ this.loading = true+ try {+ const data = await this.fetchViewData(view, filters)+ if (myId !== this.requestId) return+ this.assignViewData(view, data)+ } catch (err) {+ if (myId !== this.requestId) return+ this.setError(err)+ } finally {+ if (myId === this.requestId) this.loading = false+ }+ },++ fetchViewData(view: ReportView, filters: TimeReportFilters): Promise<TimeReportViewData> {+ if (view === 'by-task') return $tvApi.timeTracking.reportByTask(filters)+ if (view === 'by-user') return $tvApi.timeTracking.reportByUser(filters)+ return $tvApi.timeTracking.reportByDay(filters)+ },++ assignViewData(view: ReportView, data: TimeReportViewData): void {+ if (view === 'by-task') this.byTask = (data as TimeReportByTaskRow[]) ?? []+ else if (view === 'by-user') this.byUser = (data as TimeReportByUserRow[]) ?? []+ else this.byDay = (data as TimeReportByDayRow[]) ?? []+ },+ },+})diff --git a/web/src/stores/time-reports.types.ts b/web/src/stores/time-reports.types.tsnew file mode 100644index 0000000..5dee771--- /dev/null+++ b/web/src/stores/time-reports.types.ts@@ -0,0 +1,45 @@+import type {+ TimeEntryItem,+ TimeReportByDayRow,+ TimeReportByTaskRow,+ TimeReportByUserRow,+ TimeReportContributor,+ TimeReportSummary,+} from 'taskview-api'++export type ReportView = 'by-task' | 'by-user' | 'by-day'++export type TimeReportViewData =+ | TimeReportByTaskRow[]+ | TimeReportByUserRow[]+ | TimeReportByDayRow[]+ | undefined++export type TimeReportsInitParams = {+ organizationId: number+ goalIds: number[]+}++export type TimeReportsFiltersState = {+ organizationId: number | null+ goalIds: number[]+ userId: number | null+ from: string+ to: string+ billable: boolean | null+}++export interface TimeReportsState {+ filters: TimeReportsFiltersState+ view: ReportView+ summary: TimeReportSummary | null+ byDay: TimeReportByDayRow[]+ byUser: TimeReportByUserRow[]+ byTask: TimeReportByTaskRow[]+ contributors: TimeReportContributor[]+ entries: TimeEntryItem[]+ loading: boolean+ initialized: boolean+ requestId: number+ lastError: { key: string; ts: number } | null+}