diff --git a/package-lock.json b/package-lock.json index f16a392a..276d0238 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,8 @@ "name": "solidtime", "workspaces": [ "resources/js/packages/ui", - "resources/js/packages/api" + "resources/js/packages/api", + "resources/js/packages/composables" ], "dependencies": { "@floating-ui/core": "^1.7.5", @@ -2103,6 +2104,10 @@ "resolved": "resources/js/packages/api", "link": true }, + "node_modules/@solidtime/composables": { + "resolved": "resources/js/packages/composables", + "link": true + }, "node_modules/@solidtime/ui": { "resolved": "resources/js/packages/ui", "link": true @@ -8549,7 +8554,7 @@ }, "resources/js/packages/api": { "name": "@solidtime/api", - "version": "0.0.7", + "version": "0.0.8", "license": "AGPL-3.0", "devDependencies": { "vite-plugin-dts": "^4.5.4" @@ -8562,6 +8567,25 @@ "zod": "^3.23.8" } }, + "resources/js/packages/composables": { + "name": "@solidtime/composables", + "version": "0.0.1", + "license": "AGPL-3.0", + "devDependencies": { + "vite-plugin-dts": "^4.5.4" + }, + "peerDependencies": { + "@solidtime/api": "^0.0.8", + "@tanstack/vue-query": "^5.0.0", + "@vueuse/core": "^12.5.0 || ^14.0.0", + "axios": "^1.6.4", + "dayjs": "^1.11.13", + "typescript": "^5.5.4", + "vite": "^5.4.1 || ^6.0.0 || ^7.0.0", + "vue": "^3.5.0", + "vue-tsc": "^2.2.0 || ^3.0.0" + } + }, "resources/js/packages/ui": { "name": "@solidtime/ui", "version": "0.0.23", diff --git a/package.json b/package.json index 7755d99c..e44d35ef 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,8 @@ "type": "module", "workspaces": [ "resources/js/packages/ui", - "resources/js/packages/api" + "resources/js/packages/api", + "resources/js/packages/composables" ], "scripts": { "dev": "vite", diff --git a/resources/js/packages/api/package.json b/resources/js/packages/api/package.json index e6e80481..f1df60c6 100644 --- a/resources/js/packages/api/package.json +++ b/resources/js/packages/api/package.json @@ -1,6 +1,6 @@ { "name": "@solidtime/api", - "version": "0.0.7", + "version": "0.0.8", "description": "Package containing the solidtime api client and type declarations", "main": "./dist/solidtime-api.umd.cjs", "module": "./dist/solidtime-api.js", diff --git a/resources/js/packages/api/src/index.ts b/resources/js/packages/api/src/index.ts index 50b82db1..bbf9a2d6 100644 --- a/resources/js/packages/api/src/index.ts +++ b/resources/js/packages/api/src/index.ts @@ -148,6 +148,6 @@ export type UpdateUserBody = ZodiosBodyByAlias; export type DeleteUserBody = ZodiosBodyByAlias; export type DeleteOrganizationBody = ZodiosBodyByAlias; -const api = createApiClient('/api', { validate: 'none' }); +const api: ReturnType = createApiClient('/api', { validate: 'none' }); export { createApiClient, api }; diff --git a/resources/js/packages/composables/README.md b/resources/js/packages/composables/README.md new file mode 100644 index 00000000..14422a77 --- /dev/null +++ b/resources/js/packages/composables/README.md @@ -0,0 +1,29 @@ +# @solidtime/composables + +Vue composables shared by the solidtime web app, the desktop app and the browser extension: time entry mutations, the timer, organization lists and the authenticated API client. + +Each app keeps its own login flow and decides where the API client and the selected organization come from, by installing the plugin: + +```ts +import { SolidtimeComposables, withAuthentication } from '@solidtime/composables'; +import { createApiClient } from '@solidtime/api'; + +const client = withAuthentication(createApiClient(endpoint + '/api', { validate: 'none' }), { + getAccessToken: () => accessToken.value, + canRefresh: () => !!refreshToken.value, + refreshAccessToken, +}); + +app.use(SolidtimeComposables, { + apiClient: () => client, + currentOrganizationId, + currentMembershipId, + selectOrganization: (organizationId) => { /* switch the membership */ }, +}); +``` + +Requires `@tanstack/vue-query` to be installed in the app. + +## What belongs here + +Logic that more than one app needs and that does not render anything. Components belong in `@solidtime/ui`, the generated API client and types in `@solidtime/api`. diff --git a/resources/js/packages/composables/package.json b/resources/js/packages/composables/package.json new file mode 100644 index 00000000..8f046184 --- /dev/null +++ b/resources/js/packages/composables/package.json @@ -0,0 +1,57 @@ +{ + "name": "@solidtime/composables", + "version": "0.0.1", + "description": "Vue composables shared by the solidtime web app, desktop app and browser extension", + "main": "./dist/solidtime-composables.umd.cjs", + "module": "./dist/solidtime-composables.js", + "repository": { + "type": "git", + "url": "git+https://github.com/solidtime-io/solidtime.git", + "directory": "resources/js/packages/composables" + }, + "types": "./dist/packages/composables/src/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/packages/composables/src/index.d.ts", + "default": "./dist/solidtime-composables.js" + }, + "require": { + "types": "./dist/packages/composables/src/index.d.ts", + "default": "./dist/solidtime-composables.umd.cjs" + } + } + }, + "scripts": { + "build": "vite build && vue-tsc --emitDeclarationOnly", + "watch": "vite build --watch", + "types": "vue-tsc --noEmit" + }, + "files": [ + "dist" + ], + "keywords": [ + "solidtime", + "timetracker", + "timetracking", + "vue", + "composables" + ], + "type": "module", + "author": "solidtime", + "license": "AGPL-3.0", + "devDependencies": { + "vite-plugin-dts": "^4.5.4" + }, + "peerDependencies": { + "@solidtime/api": "^0.0.8", + "@tanstack/vue-query": "^5.0.0", + "@vueuse/core": "^12.5.0 || ^14.0.0", + "axios": "^1.6.4", + "dayjs": "^1.11.13", + "typescript": "^5.5.4", + "vite": "^5.4.1 || ^6.0.0 || ^7.0.0", + "vue": "^3.5.0", + "vue-tsc": "^2.2.0 || ^3.0.0" + } +} diff --git a/resources/js/packages/composables/src/apiClient.test.ts b/resources/js/packages/composables/src/apiClient.test.ts new file mode 100644 index 00000000..2d0adb43 --- /dev/null +++ b/resources/js/packages/composables/src/apiClient.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios'; +import { createApiClient } from '@/packages/api/src/openapi.json.client'; +import { withAuthentication } from './apiClient'; + +function respond(config: InternalAxiosRequestConfig, status: number, data: unknown = {}) { + const response = { data, status, statusText: '', headers: {}, config }; + if (status >= 400) { + return Promise.reject( + Object.assign(new Error(`Request failed with status code ${status}`), { + isAxiosError: true, + config, + response, + }) + ); + } + return Promise.resolve(response); +} + +function setup(options: { canRefresh?: boolean; statuses?: number[] } = {}) { + let token = 'old-token'; + const statuses = [...(options.statuses ?? [200])]; + // Header values as sent, axios reuses the config object for the retry + const requests: unknown[] = []; + const client = createApiClient('https://example.test/api', { validate: 'none' }); + client.axios.defaults.adapter = ((config) => { + requests.push(config.headers.Authorization); + return respond(config, statuses.shift() ?? 200, { data: { id: 'me' } }); + }) as AxiosAdapter; + const refreshAccessToken = vi.fn(async () => { + token = 'new-token'; + }); + withAuthentication(client, { + getAccessToken: () => token, + canRefresh: () => options.canRefresh ?? true, + refreshAccessToken, + }); + return { + client, + requests, + refreshAccessToken, + setToken: (value: string) => (token = value), + }; +} + +describe('withAuthentication', () => { + it('reads the token on every request', async () => { + const { client, requests, setToken } = setup(); + await client.getMe(); + setToken('changed-token'); + await client.getMe(); + expect(requests).toEqual(['Bearer old-token', 'Bearer changed-token']); + }); + + it('sets a default timeout', () => { + expect(setup().client.axios.defaults.timeout).toBe(30000); + }); + + it('refreshes once on a 401 and retries with the new token', async () => { + const { client, requests, refreshAccessToken } = setup({ statuses: [401, 200] }); + await expect(client.getMe()).resolves.toEqual({ data: { id: 'me' } }); + expect(refreshAccessToken).toHaveBeenCalledOnce(); + expect(requests).toEqual(['Bearer old-token', 'Bearer new-token']); + }); + + it('does not refresh when the app cannot refresh, e.g. with an API token', async () => { + const { client, refreshAccessToken } = setup({ canRefresh: false, statuses: [401] }); + await expect(client.getMe()).rejects.toMatchObject({ response: { status: 401 } }); + expect(refreshAccessToken).not.toHaveBeenCalled(); + }); + + it('does not refresh twice when the retried request fails again', async () => { + const { client, refreshAccessToken } = setup({ statuses: [401, 401] }); + await expect(client.getMe()).rejects.toMatchObject({ response: { status: 401 } }); + expect(refreshAccessToken).toHaveBeenCalledOnce(); + }); +}); diff --git a/resources/js/packages/composables/src/apiClient.ts b/resources/js/packages/composables/src/apiClient.ts new file mode 100644 index 00000000..06dfd501 --- /dev/null +++ b/resources/js/packages/composables/src/apiClient.ts @@ -0,0 +1,62 @@ +import type { AxiosError, InternalAxiosRequestConfig } from 'axios'; +import type { SolidtimeApiClient } from './context'; + +export interface AuthenticationOptions { + /** The current access token, read on every request */ + getAccessToken: () => string | null | undefined; + /** Whether a refresh is possible, e.g. false for personal API tokens */ + canRefresh: () => boolean; + /** Refreshes the tokens; must reject when the refresh failed */ + refreshAccessToken: () => Promise; + /** Request timeout in milliseconds, defaults to 30 seconds */ + timeout?: number; +} + +type RetriableRequestConfig = InternalAxiosRequestConfig & { _retry?: boolean }; + +/** + * Adds bearer authentication to an API client: the token is read on every + * request, and a 401 triggers one token refresh and retry when the app can + * refresh. + */ +export function withAuthentication( + client: T, + options: AuthenticationOptions +): T { + const axiosInstance = client.axios; + + // A request that never settles would jam the serialized time entry + // mutation queue forever + axiosInstance.defaults.timeout = options.timeout ?? 30000; + + axiosInstance.interceptors.request.use((config) => { + const token = options.getAccessToken(); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; + }); + + axiosInstance.interceptors.response.use( + (response) => response, + async (error: AxiosError) => { + const originalRequest = error.config as RetriableRequestConfig | undefined; + + if ( + error.response?.status === 401 && + originalRequest && + !originalRequest._retry && + options.canRefresh() + ) { + originalRequest._retry = true; + await options.refreshAccessToken(); + originalRequest.headers.Authorization = `Bearer ${options.getAccessToken()}`; + return axiosInstance.request(originalRequest); + } + + return Promise.reject(error); + } + ); + + return client; +} diff --git a/resources/js/packages/composables/src/context.ts b/resources/js/packages/composables/src/context.ts new file mode 100644 index 00000000..c39f7060 --- /dev/null +++ b/resources/js/packages/composables/src/context.ts @@ -0,0 +1,53 @@ +import { inject, type App, type InjectionKey, type MaybeRefOrGetter } from 'vue'; +import type { createApiClient } from '@/packages/api/src'; + +export type SolidtimeApiClient = ReturnType; + +/** + * App specific wiring the composables depend on. Each app decides where the + * API client, the selected organization and the membership come from (the web + * app from the session, desktop and the browser extension from the stored + * membership). + */ +export interface SolidtimeComposablesOptions { + /** Returns the API client to use, read on every request */ + apiClient: () => SolidtimeApiClient; + /** The id of the organization the user is currently working in */ + currentOrganizationId: MaybeRefOrGetter; + /** The id of the current user's membership in that organization */ + currentMembershipId: MaybeRefOrGetter; + /** + * Switches to the given organization. Called when the user stops a timer + * that runs in another organization than the current one. + */ + selectOrganization?: (organizationId: string) => void; +} + +export const solidtimeComposablesKey: InjectionKey = + Symbol('solidtime-composables'); + +/** + * Vue plugin that provides the app wiring to all composables of this package. + * + * @example + * app.use(SolidtimeComposables, { + * apiClient: () => client, + * currentOrganizationId, + * currentMembershipId, + * }); + */ +export const SolidtimeComposables = { + install(app: App, options: SolidtimeComposablesOptions) { + app.provide(solidtimeComposablesKey, options); + }, +}; + +export function useSolidtimeContext(): SolidtimeComposablesOptions { + const context = inject(solidtimeComposablesKey, null); + if (!context) { + throw new Error( + 'useSolidtimeContext: install the SolidtimeComposables plugin before using solidtime composables' + ); + } + return context; +} diff --git a/resources/js/packages/composables/src/fetchAllPages.ts b/resources/js/packages/composables/src/fetchAllPages.ts new file mode 100644 index 00000000..34bb3fe1 --- /dev/null +++ b/resources/js/packages/composables/src/fetchAllPages.ts @@ -0,0 +1,22 @@ +/** + * Fetches all pages from a paginated Laravel API endpoint. + * Uses `meta.last_page` to determine the total number of pages, + * so only a single request is made when all data fits on one page. + */ +export async function fetchAllPages( + fetchPage: (page: number) => Promise<{ + data: T[]; + meta: { per_page: number; last_page: number }; + }> +): Promise { + const firstResponse = await fetchPage(1); + const allItems: T[] = [...firstResponse.data]; + const { last_page } = firstResponse.meta; + + for (let page = 2; page <= last_page; page++) { + const response = await fetchPage(page); + allItems.push(...response.data); + } + + return allItems; +} diff --git a/resources/js/packages/composables/src/helpers.test.ts b/resources/js/packages/composables/src/helpers.test.ts new file mode 100644 index 00000000..9e0348eb --- /dev/null +++ b/resources/js/packages/composables/src/helpers.test.ts @@ -0,0 +1,81 @@ +import dayjs from 'dayjs'; +import utc from 'dayjs/plugin/utc'; +import { describe, expect, it, vi } from 'vitest'; +import { fetchAllPages } from './fetchAllPages'; +import { getLastWorkTimeEntry } from './timeEntries/timeEntry'; +import { mapTimeEntryList } from './timeEntries/cache'; +import { timeEntry } from './testUtils'; + +dayjs.extend(utc); + +describe('fetchAllPages', () => { + it('makes one request when everything fits on one page', async () => { + const fetchPage = vi.fn().mockResolvedValue({ + data: [1, 2], + meta: { per_page: 15, last_page: 1 }, + }); + expect(await fetchAllPages(fetchPage)).toEqual([1, 2]); + expect(fetchPage).toHaveBeenCalledOnce(); + }); + + it('loads every page in order', async () => { + const fetchPage = vi.fn((page: number) => + Promise.resolve({ data: [page], meta: { per_page: 1, last_page: 3 } }) + ); + expect(await fetchAllPages(fetchPage)).toEqual([1, 2, 3]); + }); +}); + +describe('getLastWorkTimeEntry', () => { + const now = dayjs.utc('2026-07-14T13:00:00Z'); + + it('skips breaks and entries that start in the future', () => { + const entries = [ + timeEntry({ id: 'future', start: '2026-07-14T14:00:00Z' }), + timeEntry({ id: 'break', start: '2026-07-14T12:00:00Z', type: 'break' }), + timeEntry({ id: 'last-work', start: '2026-07-14T11:00:00Z' }), + ]; + expect(getLastWorkTimeEntry(entries, now)?.id).toBe('last-work'); + }); + + it('treats entries without a type as work for servers without breaks', () => { + const entry = { ...timeEntry({ id: 'untyped' }), type: undefined }; + expect(getLastWorkTimeEntry([entry as never], now)?.id).toBe('untyped'); + }); + + it('returns null when there is no work entry', () => { + expect(getLastWorkTimeEntry([], now)).toBeNull(); + }); +}); + +describe('mapTimeEntryList', () => { + const remove = (entries: { id: string }[]) => entries.filter((entry) => entry.id !== 'a'); + + it('updates a single page list', () => { + const cached = { data: [timeEntry({ id: 'a' }), timeEntry({ id: 'b' })], meta: {} }; + expect(mapTimeEntryList(cached, remove as never)).toEqual({ + data: [timeEntry({ id: 'b' })], + meta: {}, + }); + }); + + it('updates every page of an infinite list and passes the page index', () => { + const cached = { + pages: [{ data: [timeEntry({ id: 'a' })] }, { data: [timeEntry({ id: 'c' })] }], + pageParams: [], + }; + const pageIndexes: number[] = []; + const result = mapTimeEntryList(cached, (entries, index) => { + pageIndexes.push(index); + return remove(entries) as never; + }) as typeof cached; + expect(result.pages.map((page) => page.data.map((entry) => entry.id))).toEqual([[], ['c']]); + expect(pageIndexes).toEqual([0, 1]); + }); + + it('leaves unknown cache shapes untouched', () => { + const cached = { totals: 3 }; + expect(mapTimeEntryList(cached, remove as never)).toBe(cached); + expect(mapTimeEntryList(undefined, remove as never)).toBeUndefined(); + }); +}); diff --git a/resources/js/packages/composables/src/index.ts b/resources/js/packages/composables/src/index.ts new file mode 100644 index 00000000..84fcae41 --- /dev/null +++ b/resources/js/packages/composables/src/index.ts @@ -0,0 +1,24 @@ +export { + SolidtimeComposables, + useSolidtimeContext, + solidtimeComposablesKey, + type SolidtimeApiClient, + type SolidtimeComposablesOptions, +} from './context'; +export { withAuthentication, type AuthenticationOptions } from './apiClient'; +export { fetchAllPages } from './fetchAllPages'; +export { queryKeys } from './queryKeys'; +export { useProjectsQuery, useTasksQuery, useTagsQuery, useClientsQuery } from './queries'; +export { emptyTimeEntry, getLastWorkTimeEntry } from './timeEntries/timeEntry'; +export { mapTimeEntryList, updateTimeEntryLists, invalidateTimeEntries } from './timeEntries/cache'; +export { + resolveTimeEntryId, + useTimeEntryCreateMutation, + useTimeEntryStopMutation, + useTimeEntryUpdateMutation, + useCurrentTimeEntryUpdateMutation, + useTimeEntriesUpdateMutation, + useTimeEntriesDeleteMutation, + useTimeEntryDeleteMutation, +} from './timeEntries/mutations'; +export { useTimer, useTimerState, useCurrentTimeEntrySync } from './timeEntries/useTimer'; diff --git a/resources/js/packages/composables/src/queries.ts b/resources/js/packages/composables/src/queries.ts new file mode 100644 index 00000000..2a346ea2 --- /dev/null +++ b/resources/js/packages/composables/src/queries.ts @@ -0,0 +1,87 @@ +import { useQuery } from '@tanstack/vue-query'; +import { computed, toValue } from 'vue'; +import type { Client, Project, Tag, Task } from '@/packages/api/src'; +import { useSolidtimeContext } from './context'; +import { fetchAllPages } from './fetchAllPages'; +import { queryKeys } from './queryKeys'; + +/** + * Lists of an organization's projects, tasks, tags and clients. All pages are + * loaded, since the API returns only a page (15 items by default) at a time. + */ + +function useOrganizationListQuery( + key: (organizationId: string | null | undefined) => readonly unknown[], + fetchAll: (organizationId: string) => Promise +) { + const { currentOrganizationId } = useSolidtimeContext(); + const organizationId = computed(() => toValue(currentOrganizationId)); + + const query = useQuery({ + queryKey: computed(() => key(organizationId.value)), + queryFn: async () => { + if (!organizationId.value) { + throw new Error('No current organization'); + } + return { data: await fetchAll(organizationId.value) }; + }, + enabled: computed(() => !!organizationId.value), + staleTime: 1000 * 30, + }); + + const items = computed(() => query.data.value?.data ?? []); + + return { ...query, items }; +} + +export function useProjectsQuery() { + const { apiClient } = useSolidtimeContext(); + const query = useOrganizationListQuery(queryKeys.projects, (organization) => + fetchAllPages((page) => + apiClient().getProjects({ + params: { organization }, + queries: { archived: 'all', page }, + }) + ) + ); + return { ...query, projects: query.items }; +} + +export function useTasksQuery() { + const { apiClient } = useSolidtimeContext(); + const query = useOrganizationListQuery(queryKeys.tasks, (organization) => + fetchAllPages((page) => + apiClient().getTasks({ + params: { organization }, + queries: { done: 'all', page }, + }) + ) + ); + return { ...query, tasks: query.items }; +} + +export function useTagsQuery() { + const { apiClient } = useSolidtimeContext(); + const query = useOrganizationListQuery(queryKeys.tags, (organization) => + fetchAllPages((page) => + apiClient().getTags({ + params: { organization }, + queries: { page }, + }) + ) + ); + return { ...query, tags: query.items }; +} + +export function useClientsQuery() { + const { apiClient } = useSolidtimeContext(); + const query = useOrganizationListQuery(queryKeys.clients, (organization) => + fetchAllPages((page) => + apiClient().getClients({ + params: { organization }, + queries: { archived: 'all', page }, + }) + ) + ); + return { ...query, clients: query.items }; +} diff --git a/resources/js/packages/composables/src/queryKeys.ts b/resources/js/packages/composables/src/queryKeys.ts new file mode 100644 index 00000000..d131d675 --- /dev/null +++ b/resources/js/packages/composables/src/queryKeys.ts @@ -0,0 +1,13 @@ +/** + * Query keys shared by all apps, so that invalidations from shared composables + * reach the queries of every app. Lists are keyed by organization. + */ +export const queryKeys = { + projects: (organizationId?: string | null) => ['projects', organizationId] as const, + tasks: (organizationId?: string | null) => ['tasks', organizationId] as const, + tags: (organizationId?: string | null) => ['tags', organizationId] as const, + clients: (organizationId?: string | null) => ['clients', organizationId] as const, + /** Prefix of every time entry list (paginated, infinite or calendar) */ + timeEntries: ['timeEntries'] as const, + currentTimeEntry: ['currentTimeEntry'] as const, +}; diff --git a/resources/js/packages/composables/src/testUtils.ts b/resources/js/packages/composables/src/testUtils.ts new file mode 100644 index 00000000..3a4f1a57 --- /dev/null +++ b/resources/js/packages/composables/src/testUtils.ts @@ -0,0 +1,84 @@ +import { createApp, ref, type Ref } from 'vue'; +import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'; +import { vi } from 'vitest'; +import type { TimeEntry } from '@/packages/api/src'; +import { SolidtimeComposables, type SolidtimeApiClient } from './context'; + +export function timeEntry(overrides: Partial = {}): TimeEntry { + return { + id: 'entry-1', + description: 'Work', + user_id: 'user-1', + start: '2026-07-14T10:00:00Z', + end: null, + duration: null, + task_id: null, + project_id: null, + tags: [], + billable: false, + type: 'work', + organization_id: 'org-1', + ...overrides, + } as TimeEntry; +} + +export function createFakeApiClient() { + return { + createTimeEntry: vi.fn(), + updateTimeEntry: vi.fn(), + deleteTimeEntry: vi.fn(), + deleteTimeEntries: vi.fn(), + updateMultipleTimeEntries: vi.fn(), + getMyActiveTimeEntry: vi.fn(), + getProjects: vi.fn(), + getTasks: vi.fn(), + getTags: vi.fn(), + getClients: vi.fn(), + }; +} + +export type FakeApiClient = ReturnType; + +/** + * Runs a composable inside a Vue app with vue-query and the + * SolidtimeComposables plugin installed. + */ +export function withSetup( + composable: () => T, + options: { + apiClient?: FakeApiClient; + organizationId?: Ref; + selectOrganization?: (organizationId: string) => void; + } = {} +) { + const apiClient = options.apiClient ?? createFakeApiClient(); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + let result!: T; + const app = createApp({ + setup() { + result = composable(); + return () => null; + }, + }); + app.use(VueQueryPlugin, { queryClient }); + app.use(SolidtimeComposables, { + apiClient: () => apiClient as unknown as SolidtimeApiClient, + currentOrganizationId: options.organizationId ?? ref('org-1'), + currentMembershipId: ref('member-1'), + selectOrganization: options.selectOrganization, + }); + app.mount(document.createElement('div')); + return { result, apiClient, queryClient, unmount: () => app.unmount() }; +} + +export function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} diff --git a/resources/js/packages/composables/src/timeEntries.test.ts b/resources/js/packages/composables/src/timeEntries.test.ts new file mode 100644 index 00000000..688b9dcd --- /dev/null +++ b/resources/js/packages/composables/src/timeEntries.test.ts @@ -0,0 +1,219 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { flushPromises } from '@vue/test-utils'; +import { queryKeys } from './queryKeys'; +import { useProjectsQuery } from './queries'; +import { useTimeEntriesDeleteMutation } from './timeEntries/mutations'; +import { useCurrentTimeEntrySync, useTimer } from './timeEntries/useTimer'; +import { createFakeApiClient, deferred, timeEntry, withSetup } from './testUtils'; + +let unmount: (() => void) | undefined; + +beforeEach(() => { + localStorage.clear(); +}); + +afterEach(() => { + unmount?.(); + unmount = undefined; +}); + +describe('useTimer', () => { + it('stops a timer whose create is still pending, using the id from the server', async () => { + const apiClient = createFakeApiClient(); + const create = deferred<{ data: ReturnType }>(); + apiClient.createTimeEntry.mockReturnValue(create.promise); + apiClient.updateTimeEntry.mockResolvedValue({ data: timeEntry({ id: 'server-id' }) }); + const setup = withSetup(() => useTimer(), { apiClient }); + unmount = setup.unmount; + const timer = setup.result; + + timer.currentTimeEntry.value = { ...timer.currentTimeEntry.value, description: 'Race' }; + timer.startTimer(); + expect(timer.isActive.value).toBe(true); + expect(timer.currentTimeEntry.value.organization_id).toBe('org-1'); + const stopped = timer.stopTimer(); + + // The stop waits for the create, as both run in the same mutation scope + await flushPromises(); + expect(apiClient.updateTimeEntry).not.toHaveBeenCalled(); + + create.resolve({ data: timeEntry({ id: 'server-id', description: 'Race' }) }); + await stopped; + + expect(apiClient.createTimeEntry).toHaveBeenCalledWith( + expect.objectContaining({ description: 'Race', member_id: 'member-1' }), + { params: { organization: 'org-1' } } + ); + expect(apiClient.updateTimeEntry).toHaveBeenCalledWith( + expect.objectContaining({ id: 'server-id', end: expect.any(String) }), + { params: { organization: 'org-1', timeEntry: 'server-id' } } + ); + expect(timer.isActive.value).toBe(false); + }); + + it('restores the running timer when stopping fails', async () => { + const apiClient = createFakeApiClient(); + apiClient.updateTimeEntry.mockRejectedValue(new Error('offline')); + const setup = withSetup(() => useTimer(), { apiClient }); + unmount = setup.unmount; + const timer = setup.result; + const running = timeEntry({ id: 'running' }); + timer.currentTimeEntry.value = running; + + await expect(timer.stopTimer()).rejects.toThrow('offline'); + expect(timer.currentTimeEntry.value).toEqual(running); + }); + + it('switches to the organization of a timer running elsewhere when stopping it', async () => { + const apiClient = createFakeApiClient(); + apiClient.updateTimeEntry.mockResolvedValue({ data: timeEntry() }); + const selectOrganization = vi.fn(); + const setup = withSetup(() => useTimer(), { apiClient, selectOrganization }); + unmount = setup.unmount; + setup.result.currentTimeEntry.value = timeEntry({ organization_id: 'org-2' }); + + await setup.result.stopTimer(); + + expect(selectOrganization).toHaveBeenCalledWith('org-2'); + expect(apiClient.updateTimeEntry).toHaveBeenCalledWith(expect.anything(), { + params: { organization: 'org-2', timeEntry: 'entry-1' }, + }); + }); + + it('continues the last work entry', async () => { + const apiClient = createFakeApiClient(); + apiClient.createTimeEntry.mockResolvedValue({ data: timeEntry({ id: 'new' }) }); + const setup = withSetup(() => useTimer(), { apiClient }); + unmount = setup.unmount; + setup.result.lastTimeEntry.value = timeEntry({ + description: 'Last', + project_id: 'project-1', + end: '2026-07-14T11:00:00Z', + }); + + setup.result.continueLastTimer(); + await flushPromises(); + + expect(apiClient.createTimeEntry).toHaveBeenCalledWith( + expect.objectContaining({ description: 'Last', project_id: 'project-1', end: null }), + expect.anything() + ); + }); + + it('stops the work timer before starting a break', async () => { + const apiClient = createFakeApiClient(); + apiClient.updateTimeEntry.mockResolvedValue({ data: timeEntry() }); + apiClient.createTimeEntry.mockResolvedValue({ data: timeEntry({ id: 'break' }) }); + const setup = withSetup(() => useTimer(), { apiClient }); + unmount = setup.unmount; + setup.result.currentTimeEntry.value = timeEntry({ id: 'work' }); + + setup.result.startBreak(); + expect(setup.result.isOnBreak.value).toBe(true); + await flushPromises(); + + const stopEnd = apiClient.updateTimeEntry.mock.calls[0]![0].end; + const breakStart = apiClient.createTimeEntry.mock.calls[0]![0].start; + expect(stopEnd).toBe(breakStart); + expect(apiClient.createTimeEntry.mock.calls[0]![0].type).toBe('break'); + }); +}); + +describe('useTimeEntriesDeleteMutation', () => { + it('deletes all entries in one request and removes them from cached lists', async () => { + const apiClient = createFakeApiClient(); + const request = deferred(); + apiClient.deleteTimeEntries.mockReturnValue(request.promise); + const setup = withSetup(() => useTimeEntriesDeleteMutation(), { apiClient }); + unmount = setup.unmount; + const listKey = [...queryKeys.timeEntries, 'org-1']; + setup.queryClient.setQueryData(listKey, { + data: [timeEntry({ id: 'a' }), timeEntry({ id: 'b' }), timeEntry({ id: 'c' })], + }); + + setup.result.mutate([timeEntry({ id: 'a' }), timeEntry({ id: 'b' })]); + await flushPromises(); + + expect(apiClient.deleteTimeEntries).toHaveBeenCalledOnce(); + expect(apiClient.deleteTimeEntries).toHaveBeenCalledWith(undefined, { + queries: { ids: ['a', 'b'] }, + params: { organization: 'org-1' }, + }); + const cached = setup.queryClient.getQueryData<{ data: { id: string }[] }>(listKey); + expect(cached?.data.map((entry) => entry.id)).toEqual(['c']); + request.resolve({}); + }); + + it('restores the cached lists when the delete fails', async () => { + const apiClient = createFakeApiClient(); + apiClient.deleteTimeEntries.mockRejectedValue(new Error('offline')); + const setup = withSetup(() => useTimeEntriesDeleteMutation(), { apiClient }); + unmount = setup.unmount; + const listKey = [...queryKeys.timeEntries, 'org-1']; + const list = { data: [timeEntry({ id: 'a' })] }; + setup.queryClient.setQueryData(listKey, list); + // Keep the restored data observable, invalidation would refetch otherwise + vi.spyOn(setup.queryClient, 'invalidateQueries').mockResolvedValue(); + + await expect(setup.result.mutateAsync([timeEntry({ id: 'a' })])).rejects.toThrow(); + + expect(setup.queryClient.getQueryData(listKey)).toEqual(list); + }); +}); + +describe('useProjectsQuery', () => { + it('loads every page of projects', async () => { + const apiClient = createFakeApiClient(); + apiClient.getProjects.mockImplementation(({ queries }: { queries: { page: number } }) => + Promise.resolve({ + data: [{ id: `project-${queries.page}` }], + meta: { per_page: 1, last_page: 2 }, + }) + ); + const setup = withSetup(() => useProjectsQuery(), { apiClient }); + unmount = setup.unmount; + + await vi.waitFor(() => expect(setup.result.projects.value).toHaveLength(2)); + expect(apiClient.getProjects).toHaveBeenCalledWith({ + params: { organization: 'org-1' }, + queries: { archived: 'all', page: 2 }, + }); + }); +}); + +describe('useCurrentTimeEntrySync', () => { + it('shows a timer started elsewhere and clears it once it is stopped there', async () => { + const apiClient = createFakeApiClient(); + apiClient.getMyActiveTimeEntry.mockResolvedValue({ data: timeEntry({ id: 'remote' }) }); + const setup = withSetup(() => ({ timer: useTimer(), query: useCurrentTimeEntrySync() }), { + apiClient, + }); + unmount = setup.unmount; + const { timer, query } = setup.result; + + await vi.waitFor(() => expect(timer.currentTimeEntry.value.id).toBe('remote')); + + apiClient.getMyActiveTimeEntry.mockRejectedValue( + Object.assign(new Error('No active time entry'), { response: { status: 404 } }) + ); + await query.refetch(); + await vi.waitFor(() => expect(timer.currentTimeEntry.value.id).toBe('')); + }); + + it('keeps an entry the user is preparing when nothing is running', async () => { + const apiClient = createFakeApiClient(); + apiClient.getMyActiveTimeEntry.mockResolvedValue({ data: null }); + const setup = withSetup(() => ({ timer: useTimer(), query: useCurrentTimeEntrySync() }), { + apiClient, + }); + unmount = setup.unmount; + setup.result.timer.currentTimeEntry.value = { + ...setup.result.timer.currentTimeEntry.value, + description: 'Draft', + }; + + await vi.waitFor(() => expect(apiClient.getMyActiveTimeEntry).toHaveBeenCalled()); + await flushPromises(); + expect(setup.result.timer.currentTimeEntry.value.description).toBe('Draft'); + }); +}); diff --git a/resources/js/packages/composables/src/timeEntries/cache.ts b/resources/js/packages/composables/src/timeEntries/cache.ts new file mode 100644 index 00000000..c35a2a4b --- /dev/null +++ b/resources/js/packages/composables/src/timeEntries/cache.ts @@ -0,0 +1,63 @@ +import type { QueryClient } from '@tanstack/vue-query'; +import type { TimeEntry } from '@/packages/api/src'; +import { queryKeys } from '../queryKeys'; + +type TimeEntryPage = { data: TimeEntry[] }; + +function isTimeEntryPage(value: unknown): value is TimeEntryPage { + return ( + !!value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data) + ); +} + +/** + * Applies `update` to the entries of a cached time entry list. Supports the + * list shapes the apps use: a single page (`{ data }`) and infinite queries + * (`{ pages: [{ data }] }`). Unknown shapes are returned unchanged. + */ +export function mapTimeEntryList( + cached: unknown, + update: (entries: TimeEntry[], pageIndex: number) => TimeEntry[] +): unknown { + if (!cached || typeof cached !== 'object') { + return cached; + } + const pages = (cached as { pages?: unknown }).pages; + if (Array.isArray(pages)) { + return { + ...cached, + pages: pages.map((page, index) => + isTimeEntryPage(page) ? { ...page, data: update(page.data, index) } : page + ), + }; + } + if (isTimeEntryPage(cached)) { + return { ...cached, data: update(cached.data, 0) }; + } + return cached; +} + +/** + * Optimistically updates every cached time entry list and returns a function + * that restores the previous state. + */ +export async function updateTimeEntryLists( + queryClient: QueryClient, + update: (entries: TimeEntry[], pageIndex: number) => TimeEntry[] +): Promise<() => void> { + await queryClient.cancelQueries({ queryKey: queryKeys.timeEntries }); + const previous = queryClient.getQueriesData({ queryKey: queryKeys.timeEntries }); + queryClient.setQueriesData({ queryKey: queryKeys.timeEntries }, (cached: unknown) => + mapTimeEntryList(cached, update) + ); + return () => { + for (const [queryKey, data] of previous) { + queryClient.setQueryData(queryKey, data); + } + }; +} + +export function invalidateTimeEntries(queryClient: QueryClient) { + queryClient.invalidateQueries({ queryKey: queryKeys.timeEntries }); + queryClient.invalidateQueries({ queryKey: queryKeys.currentTimeEntry }); +} diff --git a/resources/js/packages/composables/src/timeEntries/mutations.ts b/resources/js/packages/composables/src/timeEntries/mutations.ts new file mode 100644 index 00000000..8c7b8e2e --- /dev/null +++ b/resources/js/packages/composables/src/timeEntries/mutations.ts @@ -0,0 +1,274 @@ +import { useMutation, useQueryClient } from '@tanstack/vue-query'; +import { toValue } from 'vue'; +import type { + CreateTimeEntryBody, + TimeEntry, + UpdateMultipleTimeEntriesChangeset, +} from '@/packages/api/src'; +import { useSolidtimeContext } from '../context'; +import { queryKeys } from '../queryKeys'; +import { invalidateTimeEntries, updateTimeEntryLists } from './cache'; +import { emptyTimeEntry } from './timeEntry'; + +/** + * All time entry mutations share one scope, so they run one after another in + * the order they were triggered (e.g. a stop is sent after the create of the + * same entry has finished). + */ +const scope = { id: 'timeEntry' }; + +/** + * Maps the optimistic id of an entry that was created on the client to the id + * the server assigned, so queued mutations of that entry reach the server. + */ +const serverIds: Record = {}; + +export function resolveTimeEntryId(id: string): string { + return serverIds[id] ?? id; +} + +function requireOrganizationId(organizationId: string | null | undefined, action: string) { + if (!organizationId) { + throw new Error(`No organization id - ${action}`); + } + return organizationId; +} + +export function useTimeEntryCreateMutation() { + const queryClient = useQueryClient(); + const { apiClient, currentOrganizationId } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntry: CreateTimeEntryBody) => { + const organization = requireOrganizationId( + toValue(currentOrganizationId), + 'create time entry' + ); + return apiClient().createTimeEntry(timeEntry, { params: { organization } }); + }, + onMutate: async (variables) => { + // Reuse the caller's optimistic id so the entry is stoppable before the POST settles + const callerId = (variables as { id?: string }).id; + const optimisticTimeEntry = { + data: { + ...variables, + organization_id: toValue(currentOrganizationId) ?? '', + id: callerId ? callerId : crypto.randomUUID(), + }, + }; + // Entries with an end (e.g. added manually) are not the running timer + if (!variables.end) { + await queryClient.cancelQueries({ queryKey: queryKeys.currentTimeEntry }); + queryClient.setQueryData(queryKeys.currentTimeEntry, () => optimisticTimeEntry); + } + return { optimisticTimeEntry }; + }, + onSuccess: (data, _variables, context) => { + serverIds[context.optimisticTimeEntry.data.id] = data.data.id; + }, + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useTimeEntryStopMutation() { + const queryClient = useQueryClient(); + const { apiClient } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntry: TimeEntry) => { + const organization = requireOrganizationId( + timeEntry.organization_id, + 'stop time entry' + ); + if (timeEntry.id === '') { + throw new Error('No time entry id - stop time entry'); + } + const id = resolveTimeEntryId(timeEntry.id); + return apiClient().updateTimeEntry( + { ...timeEntry, id }, + { params: { organization, timeEntry: id } } + ); + }, + onMutate: async (timeEntry: TimeEntry) => { + await queryClient.cancelQueries({ queryKey: queryKeys.currentTimeEntry }); + const restoreLists = await updateTimeEntryLists(queryClient, (entries, pageIndex) => { + if (entries.some((entry) => entry.id === timeEntry.id)) { + return entries.map((entry) => (entry.id === timeEntry.id ? timeEntry : entry)); + } + return pageIndex === 0 ? [timeEntry, ...entries] : entries; + }); + // Only clear the running entry if the cache still holds the entry + // being stopped, a follow-up create (e.g. a break) may have + // already written its optimistic entry here + queryClient.setQueryData(queryKeys.currentTimeEntry, (old: unknown) => { + const oldEntry = ( + old && typeof old === 'object' && 'data' in old + ? (old as { data: TimeEntry }).data + : old + ) as TimeEntry | undefined; + if (oldEntry?.id && oldEntry.id !== timeEntry.id) { + return old; + } + return emptyTimeEntry; + }); + return { restoreLists }; + }, + onError: (_error, _timeEntry, context) => context?.restoreLists(), + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useTimeEntryUpdateMutation() { + const queryClient = useQueryClient(); + const { apiClient } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntry: TimeEntry) => { + const organization = requireOrganizationId( + timeEntry.organization_id, + 'update time entry' + ); + if (timeEntry.id === '') { + throw new Error('No time entry id - update time entry'); + } + const id = resolveTimeEntryId(timeEntry.id); + return apiClient().updateTimeEntry( + { ...timeEntry, id }, + { params: { organization, timeEntry: id } } + ); + }, + onMutate: async (timeEntry: TimeEntry) => { + const restoreLists = await updateTimeEntryLists(queryClient, (entries) => + entries.map((entry) => (entry.id === timeEntry.id ? { ...timeEntry } : entry)) + ); + return { restoreLists }; + }, + onError: (_error, _timeEntry, context) => context?.restoreLists(), + // The edited entry may be the running one + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useCurrentTimeEntryUpdateMutation() { + const queryClient = useQueryClient(); + const { apiClient } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntry: TimeEntry) => { + const organization = requireOrganizationId( + timeEntry.organization_id, + 'update current time entry' + ); + if (timeEntry.id === '') { + throw new Error('No time entry id - update current time entry'); + } + const id = resolveTimeEntryId(timeEntry.id); + return apiClient().updateTimeEntry( + { ...timeEntry, id }, + { params: { organization, timeEntry: id } } + ); + }, + onMutate: async (timeEntry: TimeEntry) => { + await queryClient.cancelQueries({ queryKey: queryKeys.currentTimeEntry }); + queryClient.setQueryData(queryKeys.currentTimeEntry, () => ({ + data: { ...timeEntry }, + })); + }, + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useTimeEntriesUpdateMutation() { + const queryClient = useQueryClient(); + const { apiClient, currentOrganizationId } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: ({ + ids, + changes, + }: { + ids: string[]; + changes: UpdateMultipleTimeEntriesChangeset; + }) => { + const organization = requireOrganizationId( + toValue(currentOrganizationId), + 'update time entries' + ); + return apiClient().updateMultipleTimeEntries( + { ids: ids.map(resolveTimeEntryId), changes }, + { params: { organization } } + ); + }, + onMutate: async ({ ids, changes }) => { + const restoreLists = await updateTimeEntryLists(queryClient, (entries) => + entries.map((entry) => + ids.includes(entry.id) ? ({ ...entry, ...changes } as TimeEntry) : entry + ) + ); + return { restoreLists }; + }, + onError: (_error, _variables, context) => context?.restoreLists(), + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useTimeEntriesDeleteMutation() { + const queryClient = useQueryClient(); + const { apiClient } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntries: TimeEntry[]) => { + const organization = requireOrganizationId( + timeEntries[0]?.organization_id, + 'delete time entries' + ); + return apiClient().deleteTimeEntries(undefined, { + queries: { ids: timeEntries.map((entry) => resolveTimeEntryId(entry.id)) }, + params: { organization }, + }); + }, + onMutate: async (timeEntries: TimeEntry[]) => { + const ids = timeEntries.map((entry) => entry.id); + const restoreLists = await updateTimeEntryLists(queryClient, (entries) => + entries.filter((entry) => !ids.includes(entry.id)) + ); + return { restoreLists }; + }, + onError: (_error, _timeEntries, context) => context?.restoreLists(), + // A deleted entry may be the running one + onSettled: () => invalidateTimeEntries(queryClient), + }); +} + +export function useTimeEntryDeleteMutation() { + const queryClient = useQueryClient(); + const { apiClient } = useSolidtimeContext(); + + return useMutation({ + scope, + mutationFn: (timeEntry: TimeEntry) => { + const organization = requireOrganizationId( + timeEntry.organization_id, + 'delete time entry' + ); + const id = resolveTimeEntryId(timeEntry.id); + return apiClient().deleteTimeEntry(undefined, { + params: { organization, timeEntry: id }, + }); + }, + onMutate: async (timeEntry: TimeEntry) => { + const restoreLists = await updateTimeEntryLists(queryClient, (entries) => + entries.filter((entry) => entry.id !== timeEntry.id) + ); + return { restoreLists }; + }, + onError: (_error, _timeEntry, context) => context?.restoreLists(), + onSettled: () => invalidateTimeEntries(queryClient), + }); +} diff --git a/resources/js/packages/composables/src/timeEntries/timeEntry.ts b/resources/js/packages/composables/src/timeEntries/timeEntry.ts new file mode 100644 index 00000000..360131ce --- /dev/null +++ b/resources/js/packages/composables/src/timeEntries/timeEntry.ts @@ -0,0 +1,38 @@ +import type { TimeEntry } from '@/packages/api/src'; +import dayjs, { type Dayjs } from 'dayjs'; +import utc from 'dayjs/plugin/utc'; + +dayjs.extend(utc); + +export const emptyTimeEntry = { + id: '', + description: null, + user_id: '', + start: '', + end: null, + duration: null, + task_id: null, + project_id: null, + tags: [], + billable: false, + type: 'work', + organization_id: '', +} as TimeEntry; + +/** + * Time entries are loaded newest-first. Ignore breaks and scheduled entries so + * continuing or resuming always uses the latest work entry that has actually + * started. + */ +export function getLastWorkTimeEntry( + timeEntries: TimeEntry[], + currentTime: Dayjs = dayjs().utc() +): TimeEntry | null { + return ( + timeEntries.find( + // Servers without break support omit `type`, treat those entries as work + (entry) => + (entry.type ?? 'work') === 'work' && !dayjs(entry.start).utc().isAfter(currentTime) + ) ?? null + ); +} diff --git a/resources/js/packages/composables/src/timeEntries/useTimer.ts b/resources/js/packages/composables/src/timeEntries/useTimer.ts new file mode 100644 index 00000000..b3e739b9 --- /dev/null +++ b/resources/js/packages/composables/src/timeEntries/useTimer.ts @@ -0,0 +1,246 @@ +import { useIsMutating, useQuery, useQueryClient } from '@tanstack/vue-query'; +import { useStorage } from '@vueuse/core'; +import { computed, toValue, watch } from 'vue'; +import type { CreateTimeEntryBody, TimeEntry } from '@/packages/api/src'; +import dayjs from 'dayjs'; +import { useSolidtimeContext } from '../context'; +import { queryKeys } from '../queryKeys'; +import { useTimeEntryCreateMutation, useTimeEntryStopMutation } from './mutations'; +import { emptyTimeEntry } from './timeEntry'; + +/** + * The running time entry (or the one being prepared) and the last work entry, + * persisted in local storage so they survive a reload and are shared between + * windows of the same app. + */ +export function useTimerState() { + const currentTimeEntry = useStorage('currentTimeEntry', { ...emptyTimeEntry }); + const lastTimeEntry = useStorage('lastTimeEntry', { ...emptyTimeEntry }); + return { currentTimeEntry, lastTimeEntry }; +} + +/** + * Starting, stopping and continuing timers, including breaks. + */ +export function useTimer() { + const { currentTimeEntry, lastTimeEntry } = useTimerState(); + const { currentOrganizationId, currentMembershipId, selectOrganization } = + useSolidtimeContext(); + + const timeEntryStop = useTimeEntryStopMutation(); + const timeEntryCreate = useTimeEntryCreateMutation(); + const queryClient = useQueryClient(); + + const isActive = computed(() => { + if (!currentTimeEntry.value) { + return false; + } + return ( + currentTimeEntry.value.start !== '' && + currentTimeEntry.value.start !== null && + currentTimeEntry.value.end === null + ); + }); + + const isOnBreak = computed(() => isActive.value && currentTimeEntry.value.type === 'break'); + + function createRunningEntry(values: Partial, start: string) { + currentTimeEntry.value = { + ...emptyTimeEntry, + organization_id: toValue(currentOrganizationId) ?? '', + ...values, + id: crypto.randomUUID(), + start, + }; + timeEntryCreate.mutate({ + ...currentTimeEntry.value, + member_id: toValue(currentMembershipId) ?? '', + } as CreateTimeEntryBody); + } + + /** + * Stops the running timer. + * @param endTime - Optional end time (ISO string), defaults to now + */ + async function stopTimer(endTime?: string) { + const stoppedTimeEntry = { ...currentTimeEntry.value }; + if (stoppedTimeEntry.id === '') { + // The entry may still be creating, pick up its optimistic id from + // the query cache so the queued stop can resolve it to the real one + const cached = queryClient.getQueryData<{ data: TimeEntry }>( + queryKeys.currentTimeEntry + ); + if (cached?.data?.id && cached.data.start === stoppedTimeEntry.start) { + stoppedTimeEntry.id = cached.data.id; + } + } + if ( + stoppedTimeEntry.organization_id && + stoppedTimeEntry.organization_id !== toValue(currentOrganizationId) + ) { + selectOrganization?.(stoppedTimeEntry.organization_id); + } + currentTimeEntry.value = { ...emptyTimeEntry }; + + try { + await timeEntryStop.mutateAsync({ + ...stoppedTimeEntry, + end: dayjs(endTime).utc().format(), + }); + } catch (error) { + // The server still has this entry running, put the UI back in + // sync unless another entry (e.g. a break) was started meanwhile + if (currentTimeEntry.value.start === '' && currentTimeEntry.value.id === '') { + currentTimeEntry.value = stoppedTimeEntry; + } + throw error; + } + } + + /** + * Starts a timer with the values currently entered for the running entry + * (description, project, task, ...). + */ + function startTimer() { + const current = currentTimeEntry.value; + createRunningEntry( + { + project_id: current.project_id, + task_id: current.task_id, + description: current.description, + tags: current.tags, + billable: current.billable, + }, + dayjs().utc().format() + ); + } + + /** + * Starts a timer with the values of the last work entry, e.g. from a tray, + * widget or after discarding idle time. + */ + function continueLastTimer() { + const last = lastTimeEntry.value; + if (last && last.start) { + createRunningEntry( + { + organization_id: last.organization_id || toValue(currentOrganizationId) || '', + project_id: last.project_id, + task_id: last.task_id, + description: last.description, + tags: last.tags, + billable: last.billable, + }, + dayjs().utc().format() + ); + } else { + createRunningEntry({}, dayjs().utc().format()); + } + } + + /** + * Stops the running work timer (if any) and starts a break. Both use one + * timestamp, so the entries touch exactly. + */ + function startBreak() { + if (isOnBreak.value) { + return; + } + const switchTime = dayjs().utc().format(); + if (isActive.value) { + // The mutation scope sends the stop before the create below, + // so the UI does not need to wait for the network + stopTimer(switchTime).catch((error) => { + console.error('Failed to stop the running timer before the break', error); + }); + } + createRunningEntry({ billable: false, type: 'break' }, switchTime); + } + + /** + * Stops the running break and starts a work timer with the values of the + * given time entry. + */ + function resumeWorkAfterBreak(timeEntry: TimeEntry) { + // Never start a second work entry next to a running one (double-click race) + if (isActive.value && !isOnBreak.value) { + return; + } + if (isOnBreak.value) { + stopTimer().catch((error) => { + console.error('Failed to stop the break before resuming work', error); + }); + } + createRunningEntry( + { + project_id: timeEntry.project_id, + task_id: timeEntry.task_id, + description: timeEntry.description, + tags: timeEntry.tags, + billable: timeEntry.billable, + }, + dayjs().utc().format() + ); + } + + return { + currentTimeEntry, + lastTimeEntry, + isActive, + isOnBreak, + stopTimer, + startTimer, + continueLastTimer, + startBreak, + resumeWorkAfterBreak, + timeEntryStop, + timeEntryCreate, + }; +} + +/** + * Fetches the running time entry from the server and keeps the local timer + * state in sync with it, e.g. when the timer was started or stopped in + * another app. + */ +export function useCurrentTimeEntrySync() { + const { apiClient } = useSolidtimeContext(); + const { currentTimeEntry } = useTimerState(); + + const pendingTimeEntryMutations = useIsMutating({ + predicate: (mutation) => mutation.options.scope?.id === 'timeEntry', + }); + + const query = useQuery({ + queryKey: queryKeys.currentTimeEntry, + queryFn: () => apiClient().getMyActiveTimeEntry({}), + // Always refetch on focus to catch changes made elsewhere + staleTime: 0, + // While time entry mutations are in flight the server state is + // behind, the query refetches once the mutation queue has drained + enabled: computed(() => pendingTimeEntryMutations.value === 0), + }); + + function reconcile() { + if (query.isError.value) { + // The server answers 404 when no entry is running. Only reset a + // started timer, keep an entry the user is preparing (no id yet) + if (currentTimeEntry.value.id !== '') { + currentTimeEntry.value = { ...emptyTimeEntry }; + } + return; + } + const running = query.data.value?.data; + if (running) { + currentTimeEntry.value = { ...running }; + } else if (currentTimeEntry.value.id !== '') { + currentTimeEntry.value = { ...emptyTimeEntry }; + } + } + + // The timestamps change on every settled fetch, even when the data stays + // the same, a watch on the data would miss a refetch with an unchanged result + watch([query.dataUpdatedAt, query.errorUpdatedAt], reconcile); + + return query; +} diff --git a/resources/js/packages/composables/tsconfig.json b/resources/js/packages/composables/tsconfig.json new file mode 100644 index 00000000..a406cfb2 --- /dev/null +++ b/resources/js/packages/composables/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "Bundler", + "resolveJsonModule": true, + "noImplicitThis": true, + "strict": true, + "verbatimModuleSyntax": true, + "target": "ESNext", + "useDefineForClassFields": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "outDir": "./dist", + "rootDir": "../../", + "declaration": true, + "paths": { + "@/*": ["../../*"], + } + }, + "include": [ + "src/**/*.ts" + ], + + "exclude": [ + "./dist", + "./node_modules", + "./__tests__", + "./coverage", + "src/**/*.test.ts" + ], +} diff --git a/resources/js/packages/composables/vite.config.js b/resources/js/packages/composables/vite.config.js new file mode 100644 index 00000000..bf070eda --- /dev/null +++ b/resources/js/packages/composables/vite.config.js @@ -0,0 +1,38 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; + +export default defineConfig({ + build: { + lib: { + entry: resolve(__dirname, 'src/index.ts'), + name: 'SolidtimeComposables', + fileName: 'solidtime-composables', + }, + rollupOptions: { + // Peer dependencies are provided by the consuming app + external: [ + 'vue', + '@tanstack/vue-query', + '@vueuse/core', + 'axios', + 'dayjs', + /^dayjs\/.*/, + ], + output: { + globals: { + 'vue': 'Vue', + '@tanstack/vue-query': 'VueQuery', + '@vueuse/core': 'VueUse', + 'axios': 'axios', + 'dayjs': 'dayjs', + 'dayjs/plugin/utc': 'dayjs_plugin_utc', + }, + }, + }, + }, + resolve: { + alias: { + '@': resolve('../../'), + }, + }, +});