diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index 684b9880a..f085fdca8 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -140,7 +140,7 @@ // MobileShell own their subsequent data loading. appInitialized = true; if (!setupCompleted) { - moduleSettings.load(); + moduleSettings.ensureLoaded(); } else if ($authStore.isAuthenticated) { // An OAuth callback just landed here: send the user back to the // page that started the flow (replaces the callback redirect entry). diff --git a/frontend/src/lib/api/workspaces.js b/frontend/src/lib/api/workspaces.js index 979a8b3d4..3c9765091 100644 --- a/frontend/src/lib/api/workspaces.js +++ b/frontend/src/lib/api/workspaces.js @@ -66,7 +66,8 @@ export const workspaces = { ), getItemTypes: (id) => fetchV2Data(`/workspaces/${id}/item-types`), getWorkflows: (id) => fetchV2Data(`/workspaces/${id}/workflows`), - getPriorities: (id) => fetchV2Data(`/workspaces/${id}/priorities`), + getPriorities: (id, requestOptions = {}) => + fetchV2Data(`/workspaces/${id}/priorities`, requestOptions), // Resolved effective configuration: assigned config set (else the global // default), its condition/approval sets, effective screens per mode with // hydrated fields, and config-set priorities. diff --git a/frontend/src/lib/features/milestones/Milestones.svelte b/frontend/src/lib/features/milestones/Milestones.svelte index d832e82a4..f1bdbf76a 100644 --- a/frontend/src/lib/features/milestones/Milestones.svelte +++ b/frontend/src/lib/features/milestones/Milestones.svelte @@ -192,7 +192,7 @@ onMount(async () => { await Promise.all([ loadData(), - moduleSettings.load() + moduleSettings.ensureLoaded() ]); // Load test statistics if test management is enabled diff --git a/frontend/src/lib/pickers/PriorityPicker.svelte b/frontend/src/lib/pickers/PriorityPicker.svelte index f4c52750d..75f1c6aab 100644 --- a/frontend/src/lib/pickers/PriorityPicker.svelte +++ b/frontend/src/lib/pickers/PriorityPicker.svelte @@ -1,11 +1,9 @@ {#if loading} diff --git a/frontend/src/lib/settings/ModuleSettings.svelte b/frontend/src/lib/settings/ModuleSettings.svelte index 204c86cfe..dbcddf0c6 100644 --- a/frontend/src/lib/settings/ModuleSettings.svelte +++ b/frontend/src/lib/settings/ModuleSettings.svelte @@ -61,7 +61,7 @@ }); onMount(() => { - moduleSettings.load().then(() => { + moduleSettings.ensureLoaded().then(() => { initialLoad = false; // Enable auto-save after initial load }); loadPlugins(); diff --git a/frontend/src/lib/stores/collectionEditorOptions.svelte.js b/frontend/src/lib/stores/collectionEditorOptions.svelte.js index db8710bdc..5eb7c808f 100644 --- a/frontend/src/lib/stores/collectionEditorOptions.svelte.js +++ b/frontend/src/lib/stores/collectionEditorOptions.svelte.js @@ -1,5 +1,4 @@ import { assets } from '../api/assets.js'; -import { priorities } from '../api/configuration.js'; import { iterations, milestones } from '../api/planning.js'; import { customerOrganisations, portalCustomers } from '../api/portal.js'; import { teams } from '../api/teams.js'; @@ -36,21 +35,7 @@ const OPTION_LOADERS = { milestones: (workspaceId, options) => milestones.getAll({ workspace_id: workspaceId, include_global: true }, options), iterations: (workspaceId, options) => iterations.getAll({ workspace_id: workspaceId }, options), - priorities: async (workspaceId, options) => { - const workspace = await workspaces.get(workspaceId, options); - options.signal.throwIfAborted(); - const configurationSetId = workspace?.configuration_set_id; - if (!configurationSetId) return priorities.getAll({}, options); - - const configuredPriorities = await priorities.getAll( - { - configuration_set_id: configurationSetId, - }, - options - ); - options.signal.throwIfAborted(); - return configuredPriorities.length > 0 ? configuredPriorities : priorities.getAll({}, options); - }, + priorities: (workspaceId, options) => workspaces.getPriorities(workspaceId, options), projects: (workspaceId, options) => workspaces.getProjects(workspaceId, options), portalCustomers: (_workspaceId, options) => portalCustomers.getAll({}, options), customerOrganisations: async (_workspaceId, options) => diff --git a/frontend/src/lib/stores/collectionPreferences.svelte.js b/frontend/src/lib/stores/collectionPreferences.svelte.js index 8d6a780cb..55c2e502b 100644 --- a/frontend/src/lib/stores/collectionPreferences.svelte.js +++ b/frontend/src/lib/stores/collectionPreferences.svelte.js @@ -27,9 +27,15 @@ class CollectionPreferencesStore { #userId = null; #loadPromise = null; #generation = 0; - #dirtyViewScopes = new Set(); - #dirtyFilterScopes = new Set(); - #dirtyCommentSort = false; + // Unsaved writes belong to the authenticated session that produced them. + // They are stored as the actual patch to send, not as dirty scope names, so + // a later flush cannot reconstruct a delete from whichever snapshot happens + // to be current. #session increments on reset so a stale rejection cannot + // re-arm an old account's write. + #session = 0; + #pendingViewState = {}; + #pendingSavedFilters = {}; + #pendingCommentSort = null; #saveTimer = null; #saving = null; @@ -74,6 +80,7 @@ class CollectionPreferencesStore { /** Clear the cache on logout or user change. */ reset() { this.#generation += 1; + this.#session += 1; setCalendarPreference('auto'); setWeekStartPreference('auto'); this.viewState = {}; @@ -83,9 +90,9 @@ class CollectionPreferencesStore { this.loadError = false; this.#userId = null; this.#loadPromise = null; - this.#dirtyViewScopes.clear(); - this.#dirtyFilterScopes.clear(); - this.#dirtyCommentSort = false; + this.#pendingViewState = {}; + this.#pendingSavedFilters = {}; + this.#pendingCommentSort = null; if (this.#saveTimer) { clearTimeout(this.#saveTimer); this.#saveTimer = null; @@ -112,11 +119,12 @@ class CollectionPreferencesStore { const scope = collectionScopeId(workspaceId, collectionId); const currentScope = this.viewState[scope] ?? {}; const currentView = currentScope[view] ?? {}; + const nextScope = { ...currentScope, [view]: { ...currentView, ...patch } }; this.viewState = { ...this.viewState, - [scope]: { ...currentScope, [view]: { ...currentView, ...patch } }, + [scope]: nextScope, }; - this.#dirtyViewScopes.add(scope); + this.#pendingViewState[scope] = nextScope; this.#scheduleSave(); } @@ -129,7 +137,7 @@ class CollectionPreferencesStore { setSavedFilters(workspaceId, collectionId, filters) { const scope = collectionScopeId(workspaceId, collectionId); this.savedFilters = { ...this.savedFilters, [scope]: filters }; - this.#dirtyFilterScopes.add(scope); + this.#pendingSavedFilters[scope] = filters; this.#scheduleSave(); } @@ -138,7 +146,7 @@ class CollectionPreferencesStore { const next = order === 'newest' ? 'newest' : 'oldest'; if (this.commentSortOrder === next) return; this.commentSortOrder = next; - this.#dirtyCommentSort = true; + this.#pendingCommentSort = next; this.#scheduleSave(); } @@ -157,42 +165,44 @@ class CollectionPreferencesStore { this.#saveTimer = null; } if (this.#saving) { - // A save is already in flight; the new dirty scopes ride the next flush. + // A save is already in flight; the new pending writes ride the next flush. await this.#saving; } - const viewScopes = [...this.#dirtyViewScopes]; - const filterScopes = [...this.#dirtyFilterScopes]; - const commentSortDirty = this.#dirtyCommentSort; - if (viewScopes.length === 0 && filterScopes.length === 0 && !commentSortDirty) return; - - this.#dirtyViewScopes.clear(); - this.#dirtyFilterScopes.clear(); - this.#dirtyCommentSort = false; + const session = this.#session; + const viewState = this.#pendingViewState; + const savedFilters = this.#pendingSavedFilters; + const commentSort = this.#pendingCommentSort; + this.#pendingViewState = {}; + this.#pendingSavedFilters = {}; + this.#pendingCommentSort = null; + + const viewScopes = Object.keys(viewState); + const filterScopes = Object.keys(savedFilters); + if (viewScopes.length === 0 && filterScopes.length === 0 && commentSort === null) return; const body = {}; - if (viewScopes.length > 0) { - body.view_state = Object.fromEntries( - viewScopes.map((scope) => [scope, this.viewState[scope] ?? null]) - ); - } - if (filterScopes.length > 0) { - body.saved_filters = Object.fromEntries( - filterScopes.map((scope) => [scope, this.savedFilters[scope] ?? null]) - ); - } - if (commentSortDirty) { - body.comment_sort_order = this.commentSortOrder; - } + if (viewScopes.length > 0) body.view_state = viewState; + if (filterScopes.length > 0) body.saved_filters = savedFilters; + if (commentSort !== null) body.comment_sort_order = commentSort; const save = keepalive ? userPreferences.update(body, { keepalive: true }) : userPreferences.update(body); this.#saving = save .catch((error) => { - // Re-mark for retry; the local state stays authoritative. - for (const scope of viewScopes) this.#dirtyViewScopes.add(scope); - for (const scope of filterScopes) this.#dirtyFilterScopes.add(scope); - if (commentSortDirty) this.#dirtyCommentSort = true; + // Retry the exact failed patch, but only inside the session that made + // it. A newer pending value for the same scope wins over the retry. + if (session !== this.#session) return; + for (const scope of viewScopes) { + if (!(scope in this.#pendingViewState)) this.#pendingViewState[scope] = viewState[scope]; + } + for (const scope of filterScopes) { + if (!(scope in this.#pendingSavedFilters)) + this.#pendingSavedFilters[scope] = savedFilters[scope]; + } + if (commentSort !== null && this.#pendingCommentSort === null) { + this.#pendingCommentSort = commentSort; + } console.warn('[collectionPreferences] failed to save preferences', error); }) .finally(() => { diff --git a/frontend/src/lib/stores/itemDetailStore.svelte.js b/frontend/src/lib/stores/itemDetailStore.svelte.js index f6276c4a8..6ff27c21e 100644 --- a/frontend/src/lib/stores/itemDetailStore.svelte.js +++ b/frontend/src/lib/stores/itemDetailStore.svelte.js @@ -2,13 +2,11 @@ import { actions } from '../api/actions.js'; import { hierarchyLevels as hierarchyLevelsApi, links as linksApi } from '../api/configuration.js'; import { items } from '../api/items.js'; import { getDiagrams } from '../api/misc.js'; -import { customerOrganisations } from '../api/portal.js'; import { time } from '../api/time.js'; import { childItemTypesForParent } from '../utils/hierarchy.js'; import { buildDetailScreenFieldConfig, isMainColumnScreenField } from '../utils/screenFields.js'; import { authStore } from './auth.svelte.js'; import { workspaceDataStore } from './workspaceDataStore.svelte.js'; -import { workspacesStore } from './workspaces.svelte.js'; const FIELD_MAP = { description: 'description', @@ -107,9 +105,6 @@ class ItemDetailStore { #diagramsPromise = null; #diagramsPromiseItemId = null; #diagramsLoadedItemId = null; - #timeModalDataController = null; - #timeModalDataPromise = null; - #timeModalDataLoaded = false; // === Current Item === item = $state(null); @@ -181,10 +176,6 @@ class ItemDetailStore { timeProjects = $state([]); timeWorklogs = $state([]); timeWorklogsLoading = $state(false); - timeModalDataLoading = $state(false); - customers = $state([]); - workItems = $state([]); - workspaces = $state([]); // Cache the optional child-item rollup for the current item. includeChildItems = $state(false); timeRollup = $state(null); @@ -538,7 +529,6 @@ class ItemDetailStore { this.#linksController?.abort(); this.#worklogsController?.abort(); this.#diagramsController?.abort(); - this.#timeModalDataController?.abort(); this.item = null; this.#refreshController = null; this.#refreshInFlight = false; @@ -591,48 +581,6 @@ class ItemDetailStore { return promise; } - // Load TimeLogModal-only picker data lazily and once. - async loadTimeModalData() { - if (this.#timeModalDataLoaded) return; - if (this.#timeModalDataPromise) return this.#timeModalDataPromise; - - const controller = new AbortController(); - this.#timeModalDataController = controller; - this.timeModalDataLoading = true; - const requestOptions = { signal: controller.signal }; - const fallback = (promise, label) => - promise.catch((err) => { - if (isAbortError(err)) throw err; - console.warn(`Failed to load ${label} for time logging:`, err); - return []; - }); - - const promise = Promise.all([ - fallback(customerOrganisations.getAll({}, requestOptions), 'customers'), - fallback(items.getAll({ limit: 100 }, requestOptions), 'work items'), - fallback(workspacesStore.load(), 'workspaces'), - ]) - .then(([customers, workItems, workspaces]) => { - if (this.#timeModalDataController !== controller || controller.signal.aborted) return; - this.customers = customers || []; - this.workItems = workItems?.data ?? []; - this.workspaces = workspaces || []; - this.#timeModalDataLoaded = true; - }) - .catch((err) => { - if (!isAbortError(err)) console.error('Failed to load time-log modal data:', err); - }) - .finally(() => { - if (this.#timeModalDataController === controller) { - this.#timeModalDataController = null; - this.#timeModalDataPromise = null; - this.timeModalDataLoading = false; - } - }); - this.#timeModalDataPromise = promise; - return promise; - } - /** Reload worklogs after a timer or manual time-entry mutation. */ async reloadWorklogs() { const token = this.#loadToken; @@ -1527,7 +1475,6 @@ class ItemDetailStore { this.#linksController?.abort(); this.#worklogsController?.abort(); this.#diagramsController?.abort(); - this.#timeModalDataController?.abort(); this.#loadController = null; this.#refreshController = null; this.#refreshInFlight = false; @@ -1540,9 +1487,6 @@ class ItemDetailStore { this.#diagramsPromise = null; this.#diagramsPromiseItemId = null; this.#diagramsLoadedItemId = null; - this.#timeModalDataController = null; - this.#timeModalDataPromise = null; - this.#timeModalDataLoaded = false; this.item = null; this.itemId = null; this.workspaceId = null; @@ -1585,13 +1529,9 @@ class ItemDetailStore { this.timeProjects = []; this.timeWorklogs = []; this.timeWorklogsLoading = false; - this.timeModalDataLoading = false; this.includeChildItems = false; this.timeRollup = null; this.timeRollupLoading = false; - this.customers = []; - this.workItems = []; - this.workspaces = []; this.diagrams = []; this.loadingDiagrams = false; this.diagramsLoaded = false; diff --git a/frontend/src/lib/stores/moduleSettings.js b/frontend/src/lib/stores/moduleSettings.js index 7deb89c11..6ad86adeb 100644 --- a/frontend/src/lib/stores/moduleSettings.js +++ b/frontend/src/lib/stores/moduleSettings.js @@ -1,21 +1,35 @@ -import { writable } from 'svelte/store'; +import { get, writable } from 'svelte/store'; import { setup } from '../api/admin.js'; +const DEFAULT_SETTINGS = { + time_tracking_enabled: true, + test_management_enabled: true, + workspace_managed_agents: true, +}; + // Create the module settings store with default values function createModuleSettingsStore() { - const { subscribe, set, update } = writable({ - time_tracking_enabled: true, - test_management_enabled: true, - workspace_managed_agents: true, + const store = writable({ + ...DEFAULT_SETTINGS, loaded: false, loading: false, }); + const { subscribe, set, update } = store; + // Shared in-flight request so concurrent ensureLoaded() callers fetch once. + let inFlight = null; + // Bumped whenever a newer request, reload, or hydration takes ownership. + // Only the request that still owns the generation may publish or clear + // itself, so a slow GET cannot overwrite a forced reload or a shell snapshot. + let generation = 0; return { subscribe, hydrate(settings) { if (!settings) return; + // The shell snapshot supersedes any pending GET. + generation += 1; + inFlight = null; set({ ...settings, loaded: true, @@ -23,31 +37,34 @@ function createModuleSettingsStore() { }); }, - // Load module settings from API (only if not already loaded) - async load() { - update((state) => { - if (state.loaded || state.loading) { - return state; // Already loaded or loading + // Load module settings once. The shell hydrates this store during + // authenticated bootstrap, so this is normally a no-op; it exists for + // pre-bootstrap callers. A failed fetch stays unloaded so the next call + // retries instead of serving defaults as if they were the server value. + async ensureLoaded() { + if (get(store).loaded) return; + if (inFlight) return inFlight; + const requestGeneration = ++generation; + update((state) => ({ ...state, loading: true })); + const request = (async () => { + try { + const settings = await setup.getModuleSettings(); + if (requestGeneration !== generation) return; + set({ + ...settings, + loaded: true, + loading: false, + }); + } catch (error) { + console.error('Failed to load module settings:', error); + if (requestGeneration !== generation) return; + update((state) => ({ ...state, loading: false })); + } finally { + if (requestGeneration === generation) inFlight = null; } - return { ...state, loading: true }; - }); - - try { - const settings = await setup.getModuleSettings(); - set({ - ...settings, - loaded: true, - loading: false, - }); - } catch (error) { - console.error('Failed to load module settings:', error); - // Keep default values but mark as loaded to prevent retrying constantly - update((state) => ({ - ...state, - loaded: true, - loading: false, - })); - } + })(); + inFlight = request; + return request; }, // Update module settings both in store and API @@ -64,16 +81,17 @@ function createModuleSettingsStore() { } }, - // Force reload from API + // Force reload from API. Supersede any in-flight GET so its late response + // cannot restore the previous value. async reload() { + generation += 1; + inFlight = null; set({ - time_tracking_enabled: true, - test_management_enabled: true, - workspace_managed_agents: true, + ...DEFAULT_SETTINGS, loaded: false, loading: false, }); - await this.load(); + await this.ensureLoaded(); }, }; } diff --git a/frontend/src/lib/stores/timeLogStore.svelte.js b/frontend/src/lib/stores/timeLogStore.svelte.js index 82158c3a2..ee2a606c1 100644 --- a/frontend/src/lib/stores/timeLogStore.svelte.js +++ b/frontend/src/lib/stores/timeLogStore.svelte.js @@ -45,24 +45,33 @@ class TimeLogStore { async #loadPickerData() { if (this.#pickerPromise) return this.#pickerPromise; const generation = this.#generation; - const fallback = (promise, label) => + // A failed directory resolves to null: last-good data stays on screen and + // the next open retries it instead of caching an empty directory. + const load = (promise, label) => promise.catch((err) => { surfaceError(err, { context: `loadTimeLogPicker:${label}`, silent: true }); - return []; + return null; }); - this.#pickerPromise = Promise.all([ - fallback(time.projects.getAll(), 'time projects'), - fallback(customerOrganisations.getAll(), 'customers'), - fallback(items.getAll({ limit: 100 }), 'work items'), - fallback(workspacesStore.load(), 'workspaces'), - ]).then(([projects, customers, workItems, workspaces]) => { - if (generation !== this.#generation) return; - this.projects = projects || []; - this.customers = customers || []; - this.workItems = workItems?.data ?? []; - this.workspaces = workspaces || []; - }); - return this.#pickerPromise; + let promise; + promise = Promise.all([ + load(time.projects.getAll(), 'time projects'), + load(customerOrganisations.getAll(), 'customers'), + load(items.getAll({ limit: 100 }), 'work items'), + load(workspacesStore.load(), 'workspaces'), + ]) + .then(([projects, customers, workItems, workspaces]) => { + if (generation !== this.#generation) return; + if (projects !== null) this.projects = projects; + if (customers !== null) this.customers = customers; + if (workItems !== null) this.workItems = workItems?.data ?? []; + if (workspaces !== null) this.workspaces = workspaces; + }) + .finally(() => { + // The promise represents only an in-flight load, never a cached result. + if (this.#pickerPromise === promise) this.#pickerPromise = null; + }); + this.#pickerPromise = promise; + return promise; } /** Load projects/customers/items/workspaces for the pickers and menu. */ diff --git a/frontend/src/lib/stores/workspaces.svelte.js b/frontend/src/lib/stores/workspaces.svelte.js index 6d66bb3d6..a61eee2e3 100644 --- a/frontend/src/lib/stores/workspaces.svelte.js +++ b/frontend/src/lib/stores/workspaces.svelte.js @@ -149,13 +149,13 @@ function createWorkspacesStore() { return nextWorkspaces; }) .catch((error) => { - if (lifecycle !== lifecycleGeneration || generation !== listLoadGeneration) return []; - if (isExpectedBackgroundSyncError(error)) return []; + if (lifecycle !== lifecycleGeneration || generation !== listLoadGeneration) + return get(workspaces); + if (isExpectedBackgroundSyncError(error)) return get(workspaces); console.error('Failed to load workspaces:', error); - workspaces.set([]); - total.set(0); - loaded.set(true); - return []; + // Preserve the last good directory and leave the load retryable: + // never cache an empty list or mark a failed load as loaded. + return get(workspaces); }) .finally(() => { if (lifecycle === lifecycleGeneration && generation === listLoadGeneration) { diff --git a/frontend/src/lib/workspaces/WorkspaceSettings.svelte b/frontend/src/lib/workspaces/WorkspaceSettings.svelte index 28f95a338..80bbada46 100644 --- a/frontend/src/lib/workspaces/WorkspaceSettings.svelte +++ b/frontend/src/lib/workspaces/WorkspaceSettings.svelte @@ -106,7 +106,7 @@ import WorkspaceCannedResponses from './WorkspaceCannedResponses.svelte'; let workspaceLoadVersion = 0; onMount(async () => { - await moduleSettings.load(); + await moduleSettings.ensureLoaded(); // Redirect from base settings route to general tab if (window.location.pathname === `/workspaces/${workspaceId}/settings`) { diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 44f516b70..2ce3b769c 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3700,6 +3700,33 @@ BEGIN END $$; `, }, + { + // A priority catalog must have at most one default. The partial unique + // index makes that a database invariant instead of a per-transaction + // convention, so two concurrent saves cannot both win. Existing + // duplicates from before the index are collapsed to the lowest id. + Version: "20261203_priorities_single_default", + Name: "Enforce a single default priority", + CheckSQLite: `SELECT CASE WHEN EXISTS ( + SELECT 1 FROM sqlite_master WHERE type='index' AND name='uq_priorities_single_default' + ) THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN (SELECT COUNT(*) FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind = 'i' AND c.relname = 'uq_priorities_single_default' AND n.nspname = current_schema()) > 0 + THEN 1 ELSE 0 END`, + SQLite: ` + UPDATE priorities SET is_default = false + WHERE is_default = true + AND id <> (SELECT id FROM priorities WHERE is_default = true ORDER BY id LIMIT 1); + CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; + `, + Postgres: ` + UPDATE priorities SET is_default = false + WHERE is_default = true + AND id <> (SELECT id FROM priorities WHERE is_default = true ORDER BY id LIMIT 1); + CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; + `, + }, } // domainEventClaimableIndexMigration adds the partial index the claim query diff --git a/internal/database/schema/config_workflows.sql b/internal/database/schema/config_workflows.sql index 9ad590900..6a6ab49bd 100644 --- a/internal/database/schema/config_workflows.sql +++ b/internal/database/schema/config_workflows.sql @@ -194,6 +194,7 @@ CREATE INDEX IF NOT EXISTS idx_workflow_transitions_screen_id ON workflow_transi CREATE UNIQUE INDEX IF NOT EXISTS uq_configuration_sets_builtin_key ON configuration_sets(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_item_types_builtin_key ON item_types(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_builtin_key ON priorities(builtin_key) WHERE builtin_key IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; CREATE UNIQUE INDEX IF NOT EXISTS uq_hierarchy_levels_builtin_key ON hierarchy_levels(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_screens_builtin_key ON screens(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_status_categories_builtin_key ON status_categories(builtin_key) WHERE builtin_key IS NOT NULL; diff --git a/internal/database/schema/config_workflows_postgres.sql b/internal/database/schema/config_workflows_postgres.sql index 886047f8e..ff3bca873 100644 --- a/internal/database/schema/config_workflows_postgres.sql +++ b/internal/database/schema/config_workflows_postgres.sql @@ -142,6 +142,7 @@ CREATE INDEX IF NOT EXISTS idx_configuration_sets_workflow_id ON configuration_s CREATE UNIQUE INDEX IF NOT EXISTS uq_configuration_sets_builtin_key ON configuration_sets(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_item_types_builtin_key ON item_types(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_builtin_key ON priorities(builtin_key) WHERE builtin_key IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; CREATE UNIQUE INDEX IF NOT EXISTS uq_hierarchy_levels_builtin_key ON hierarchy_levels(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_screens_builtin_key ON screens(builtin_key) WHERE builtin_key IS NOT NULL; CREATE UNIQUE INDEX IF NOT EXISTS uq_status_categories_builtin_key ON status_categories(builtin_key) WHERE builtin_key IS NOT NULL; diff --git a/internal/handlers/items.go b/internal/handlers/items.go index 4b128dcf9..574ab722e 100644 --- a/internal/handlers/items.go +++ b/internal/handlers/items.go @@ -44,7 +44,7 @@ func NewItemHandler(db database.Database, permissionService *services.Permission if notificationService != nil { notify = notificationService.EmitEvent } - itemUpdate.SetFallbackEmitter(services.NewLegacyItemUpdatedEmitter(db, notify, nil, nil)) + itemUpdate.SetEmitter(services.NewLegacyItemUpdatedEmitter(db, notify, nil, nil)) itemDeletion := services.NewItemDeletionApplicationService(db, permissionService) itemDeletion.SetCache(itemCache, hierarchy) return &ItemHandler{ @@ -57,7 +57,7 @@ func NewItemHandler(db database.Database, permissionService *services.Permission func (h *ItemHandler) SetWebhookSender(sender *webhook.WebhookSender) { h.webhookSender = sender - h.itemUpdate.SetFallbackWebhook(sender) + h.itemUpdate.SetEmitterWebhook(sender) } func (h *ItemHandler) SetMentionService(mentionService *services.MentionService) { @@ -68,7 +68,7 @@ func (h *ItemHandler) SetMentionService(mentionService *services.MentionService) func (h *ItemHandler) SetActionService(actionService interface { EmitActionEvent(event *models.ActionEvent) }) { - h.itemUpdate.SetFallbackAction(actionService) + h.itemUpdate.SetEmitterAction(actionService) } func (h *ItemHandler) SetEventCoordinator(coordinator *services.EventCoordinator) { diff --git a/internal/repository/asset_repository.go b/internal/repository/asset_repository.go index cd1b6aad1..0a9e2f114 100644 --- a/internal/repository/asset_repository.go +++ b/internal/repository/asset_repository.go @@ -1331,12 +1331,15 @@ func (r *AssetRepository) GetDefaultStatus(setID int) (*int, error) { SELECT id FROM asset_statuses WHERE set_id = ? AND is_default = true LIMIT 1 `, setID).Scan(&statusID) - if errors.Is(err, sql.ErrNoRows) || !statusID.Valid { + if errors.Is(err, sql.ErrNoRows) { return nil, nil } if err != nil { return nil, fmt.Errorf("failed to get default status: %w", err) } + if !statusID.Valid { + return nil, nil + } id := int(statusID.Int64) return &id, nil diff --git a/internal/repository/errors.go b/internal/repository/errors.go index 705acb478..e2dd11548 100644 --- a/internal/repository/errors.go +++ b/internal/repository/errors.go @@ -17,6 +17,11 @@ var ( // ErrDuplicateEntry is returned when a unique constraint is violated ErrDuplicateEntry = errors.New("duplicate entry") + // ErrDefaultConflict is returned when two concurrent priority saves try to + // become the single default. It is a default-selection conflict, distinct + // from a duplicate name. + ErrDefaultConflict = errors.New("another priority is already the default") + // ErrConcurrentUpdate is returned when an optimistic write loses a race. ErrConcurrentUpdate = errors.New("concurrent update") diff --git a/internal/repository/priority_repository.go b/internal/repository/priority_repository.go index 51f6c2a1d..5df55af4f 100644 --- a/internal/repository/priority_repository.go +++ b/internal/repository/priority_repository.go @@ -4,6 +4,7 @@ import ( "database/sql" "errors" "fmt" + "strings" "time" "windshift/internal/database" @@ -34,17 +35,23 @@ func (r *PriorityRepository) NameExists(name string, excludeID int) (bool, error func (r *PriorityRepository) Create(priority *models.Priority) (int, error) { now := time.Now() var id int - err := r.db.QueryRow(` - INSERT INTO priorities (name, description, is_default, icon, color, sort_order, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id - `, priority.Name, priority.Description, priority.IsDefault, priority.Icon, priority.Color, priority.SortOrder, now, now).Scan(&id) - if err != nil { - if database.IsUniqueConstraintError(err) { - return 0, ErrDuplicateEntry + err := database.WithTx(r.db, func(tx database.Tx) error { + // Clear the old default before writing the new one so the partial + // unique index never observes two defaults inside one transaction. + if priority.IsDefault { + if err := clearOtherDefaults(tx, 0); err != nil { + return err + } } - return 0, fmt.Errorf("create priority: %w", err) - } - if err := r.replaceConfigurationSets(id, priority.ConfigurationSetIDs, now); err != nil { + if err := tx.QueryRow(` + INSERT INTO priorities (name, description, is_default, icon, color, sort_order, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id + `, priority.Name, priority.Description, priority.IsDefault, priority.Icon, priority.Color, priority.SortOrder, now, now).Scan(&id); err != nil { + return priorityWriteError(err, "create priority") + } + return replaceConfigurationSets(tx, id, priority.ConfigurationSetIDs, now) + }) + if err != nil { return 0, err } return id, nil @@ -52,15 +59,19 @@ func (r *PriorityRepository) Create(priority *models.Priority) (int, error) { func (r *PriorityRepository) Update(id int, priority *models.Priority) error { now := time.Now() - if _, err := r.db.ExecWrite(` - UPDATE priorities SET name = ?, description = ?, is_default = ?, icon = ?, color = ?, sort_order = ?, updated_at = ? WHERE id = ? - `, priority.Name, priority.Description, priority.IsDefault, priority.Icon, priority.Color, priority.SortOrder, now, id); err != nil { - if database.IsUniqueConstraintError(err) { - return ErrDuplicateEntry + return database.WithTx(r.db, func(tx database.Tx) error { + if priority.IsDefault { + if err := clearOtherDefaults(tx, id); err != nil { + return err + } } - return fmt.Errorf("update priority %d: %w", id, err) - } - return r.replaceConfigurationSets(id, priority.ConfigurationSetIDs, now) + if _, err := tx.ExecWrite(` + UPDATE priorities SET name = ?, description = ?, is_default = ?, icon = ?, color = ?, sort_order = ?, updated_at = ? WHERE id = ? + `, priority.Name, priority.Description, priority.IsDefault, priority.Icon, priority.Color, priority.SortOrder, now, id); err != nil { + return priorityWriteError(err, fmt.Sprintf("update priority %d", id)) + } + return replaceConfigurationSets(tx, id, priority.ConfigurationSetIDs, now) + }) } func (r *PriorityRepository) Delete(id int) error { @@ -70,21 +81,68 @@ func (r *PriorityRepository) Delete(id int) error { return nil } -func (r *PriorityRepository) ClearOtherDefaults(excludeID int) error { +// priorityWriter is satisfied by database.Database and database.Tx so the +// default-status transfer and membership replacement can share one transaction +// with the priority insert/update. +type priorityWriter interface { + ExecWrite(query string, args ...any) (sql.Result, error) +} + +// priorityWriteError maps a priority write failure to a repository sentinel. +// The single-default partial unique index is a default-selection conflict, not +// a duplicate name. +func priorityWriteError(err error, context string) error { + if isSingleDefaultViolation(err) { + return ErrDefaultConflict + } + if database.IsUniqueConstraintError(err) { + return ErrDuplicateEntry + } + return fmt.Errorf("%s: %w", context, err) +} + +// isSingleDefaultViolation reports whether err is the partial unique index that +// keeps at most one priority default. PostgreSQL names the index; SQLite names +// the indexed column. +func isSingleDefaultViolation(err error) bool { + if err == nil { + return false + } + message := err.Error() + return strings.Contains(message, "uq_priorities_single_default") || + strings.Contains(message, "priorities.is_default") +} + +// clearOtherDefaults removes default status from every priority except +// excludeID (0 clears all). It runs before the new default is written so the +// partial unique index never observes two defaults inside one transaction. +func clearOtherDefaults(tx priorityWriter, excludeID int) error { if excludeID == 0 { - _, err := r.db.ExecWrite("UPDATE priorities SET is_default = false WHERE is_default = true") - return err + if _, err := tx.ExecWrite("UPDATE priorities SET is_default = false WHERE is_default = true"); err != nil { + return fmt.Errorf("clear other default priorities: %w", err) + } + return nil + } + if _, err := tx.ExecWrite("UPDATE priorities SET is_default = false WHERE is_default = true AND id != ?", excludeID); err != nil { + return fmt.Errorf("clear other default priorities: %w", err) } - _, err := r.db.ExecWrite("UPDATE priorities SET is_default = false WHERE is_default = true AND id != ?", excludeID) - return err + return nil } -func (r *PriorityRepository) replaceConfigurationSets(priorityID int, ids []int, now time.Time) error { - if _, err := r.db.ExecWrite("DELETE FROM configuration_set_priorities WHERE priority_id = ?", priorityID); err != nil { +// replaceConfigurationSets rewrites a priority's memberships. Duplicate ids are +// treated as a set so a repeated id cannot trip the membership unique index and +// surface as a misleading name conflict. +func replaceConfigurationSets(tx priorityWriter, priorityID int, ids []int, now time.Time) error { + if _, err := tx.ExecWrite("DELETE FROM configuration_set_priorities WHERE priority_id = ?", priorityID); err != nil { return fmt.Errorf("clear configuration sets for priority %d: %w", priorityID, err) } + seen := make(map[int]struct{}, len(ids)) for _, id := range ids { - if _, err := r.db.ExecWrite(`INSERT INTO configuration_set_priorities (configuration_set_id, priority_id, created_at) VALUES (?, ?, ?)`, id, priorityID, now); err != nil { + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + if _, err := tx.ExecWrite(`INSERT INTO configuration_set_priorities (configuration_set_id, priority_id, created_at) VALUES (?, ?, ?)`, id, priorityID, now); err != nil { return fmt.Errorf("associate priority %d with configuration set %d: %w", priorityID, id, err) } } diff --git a/internal/repository/time_worklog_draft_repository.go b/internal/repository/time_worklog_draft_repository.go index 389811fe8..70089cd23 100644 --- a/internal/repository/time_worklog_draft_repository.go +++ b/internal/repository/time_worklog_draft_repository.go @@ -221,8 +221,20 @@ type Booking struct { // GetBooking returns the booking recorded for a caller-scoped idempotency key, // or ErrNotFound. func (r *TimeWorklogDraftRepository) GetBooking(userID int, key string) (*Booking, error) { + return bookingByKey(r.db, userID, key) +} + +// bookingQueryer is satisfied by both database.Database and database.Tx, so the +// booking lookup runs inside the same transaction that records it. +type bookingQueryer interface { + QueryRow(query string, args ...any) *sql.Row +} + +// bookingByKey reads one idempotency-key booking, returning ErrNotFound when +// the key is unrecorded. +func bookingByKey(q bookingQueryer, userID int, key string) (*Booking, error) { booking := &Booking{} - err := r.db.QueryRow( + err := q.QueryRow( `SELECT user_id, idempotency_key, worklog_id, draft_id FROM time_worklog_bookings WHERE user_id = ? AND idempotency_key = ?`, userID, key, ).Scan(&booking.UserID, &booking.IdempotencyKey, &booking.WorklogID, &booking.DraftID) @@ -235,19 +247,37 @@ func (r *TimeWorklogDraftRepository) GetBooking(userID int, key string) (*Bookin return booking, nil } +// errDuplicateBooking reports that a concurrent transaction recorded the +// idempotency key first. BookDraft re-reads the winning booking outside the +// rolled-back transaction. +var errDuplicateBooking = errors.New("booking key already recorded") + // BookDraft atomically materializes an owned draft as a worklog and deletes the // draft. The delete is conditional on the expected version, so exactly one // concurrent booking wins and a concurrent update cannot be silently lost. The // booking is recorded in the same transaction for idempotent replay. -func (r *TimeWorklogDraftRepository) BookDraft(draftID, userID, expectedVersion int, in CreateWorklogInput, bookingKey string) (int, error) { - var worklogID int +// +// The returned Booking identifies the worklog this call produced or replayed. +// Callers compare its DraftID to the requested draft to tell a replay of this +// draft apart from a conflicting use of the same key. +func (r *TimeWorklogDraftRepository) BookDraft(draftID, userID, expectedVersion int, in CreateWorklogInput, bookingKey string) (*Booking, error) { + var booked *Booking err := database.WithTx(r.db, func(tx database.Tx) error { - if err := tx.QueryRow(insertBookedWorklogQuery, - in.ProjectID, in.UserID, in.ItemID, in.Description, - in.DateUnix, in.StartTimeUnix, in.EndTimeUnix, in.DurationMinutes, in.NowUnix, in.NowUnix, - ).Scan(&worklogID); err != nil { - return err + // A replay must resolve before the draft-existence check: the draft is + // gone once booked, but the recorded key still maps to its worklog. + if bookingKey != "" { + existing, err := bookingByKey(tx, userID, bookingKey) + if err == nil { + booked = existing + return nil + } + if !errors.Is(err, ErrNotFound) { + return err + } } + // Claim the draft before writing the worklog. The conditional delete is + // the only winner selector, so a transaction that loses the race has no + // worklog to roll back and cannot double-book the same draft. result, err := tx.ExecWrite( `DELETE FROM time_worklog_drafts WHERE id = ? AND user_id = ? AND version = ?`, draftID, userID, expectedVersion, @@ -260,8 +290,37 @@ func (r *TimeWorklogDraftRepository) BookDraft(draftID, userID, expectedVersion return err } if affected != 1 { + // The draft is missing or at a newer version. A concurrent booking + // with this key may have consumed it, so replay the recorded booking + // when one exists before reporting the draft's own outcome. + if bookingKey != "" { + if existing, berr := bookingByKey(tx, userID, bookingKey); berr == nil { + booked = existing + return nil + } else if !errors.Is(berr, ErrNotFound) { + return berr + } + } + var exists int + if err := tx.QueryRow( + `SELECT COUNT(*) FROM time_worklog_drafts WHERE id = ? AND user_id = ?`, + draftID, userID, + ).Scan(&exists); err != nil { + return err + } + if exists == 0 { + return ErrNotFound + } return ErrConflict } + var worklogID int + if err := tx.QueryRow(insertBookedWorklogQuery, + in.ProjectID, in.UserID, in.ItemID, in.Description, + in.DateUnix, in.StartTimeUnix, in.EndTimeUnix, in.DurationMinutes, in.NowUnix, in.NowUnix, + ).Scan(&worklogID); err != nil { + // The transaction rolls back and restores the claimed draft. + return err + } if bookingKey != "" { if _, err := tx.ExecWrite( `INSERT INTO time_worklog_bookings (user_id, idempotency_key, worklog_id, draft_id, created_at) @@ -269,17 +328,24 @@ func (r *TimeWorklogDraftRepository) BookDraft(draftID, userID, expectedVersion userID, bookingKey, worklogID, draftID, in.NowUnix, ); err != nil { if database.IsUniqueConstraintError(err) { - return ErrDuplicateEntry + return errDuplicateBooking } return err } } + booked = &Booking{UserID: userID, IdempotencyKey: bookingKey, WorklogID: worklogID, DraftID: &draftID} return nil }) + if errors.Is(err, errDuplicateBooking) { + // A concurrent transaction recorded the key first; its worklog and + // draft deletion are committed. Re-read the winning booking so the + // caller can compare it to the requested draft. + return r.GetBooking(userID, bookingKey) + } if err != nil { - return 0, err + return nil, err } - return worklogID, nil + return booked, nil } // insertBookedWorklogQuery inserts a worklog and returns its id. It is shared by diff --git a/internal/repository/time_worklog_repository.go b/internal/repository/time_worklog_repository.go index 4e389f84e..255b0b856 100644 --- a/internal/repository/time_worklog_repository.go +++ b/internal/repository/time_worklog_repository.go @@ -411,7 +411,9 @@ func (r *TimeWorklogRepository) Update(in UpdateWorklog) error { } // Create inserts a worklog row, stamping created_at/updated_at, and returns -// the new row's id. +// the new row's id. Callers that only need the committed id use this; callers +// that must return the joined display row use CreateDetail so the insert and +// the read share one success boundary. func (r *TimeWorklogRepository) Create(in NewWorklog) (int64, error) { now := time.Now().Unix() var id int64 @@ -427,6 +429,35 @@ func (r *TimeWorklogRepository) Create(in NewWorklog) (int64, error) { return id, nil } +// CreateDetail inserts a worklog and returns its joined display row in the +// same transaction. A failed detail read rolls the insert back, so an error +// never means "actually booked" and a caller retry cannot double-book time. +func (r *TimeWorklogRepository) CreateDetail(in NewWorklog) (*models.Worklog, error) { + now := time.Now().Unix() + var worklog models.Worklog + err := database.WithTx(r.db, func(tx database.Tx) error { + var id int64 + if err := tx.QueryRow(` + INSERT INTO time_worklogs (project_id, user_id, item_id, description, date, start_time, end_time, duration_minutes, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id`, + in.ProjectID, in.UserID, in.ItemID, in.Description, + in.DateUnix, in.StartTimeUnix, in.EndTimeUnix, in.DurationMinutes, now, now, + ).Scan(&id); err != nil { + return fmt.Errorf("create worklog: %w", err) + } + row, err := scanWorklogDetail(tx.QueryRow(worklogDetailSelect+"\nWHERE w.id = ?", id)) + if err != nil { + return fmt.Errorf("read created worklog: %w", err) + } + worklog = row + return nil + }) + if err != nil { + return nil, err + } + return &worklog, nil +} + // WorklogListFilter narrows ListForUser results. Nil pointer fields disable // the corresponding filter. Date bounds are interval overlaps against the // stored start/end timestamps; the upper bound is exclusive. diff --git a/internal/services/catalog_mutation_service.go b/internal/services/catalog_mutation_service.go index 41c824d6d..170d457f4 100644 --- a/internal/services/catalog_mutation_service.go +++ b/internal/services/catalog_mutation_service.go @@ -624,9 +624,9 @@ func (s *CatalogMutationService) preparePriority(item *models.Priority, excludeI if exists { return NewServiceError(http.StatusConflict, "priority name already exists") } - if item.IsDefault { - return s.priorities.ClearOtherDefaults(excludeID) - } + // Default-status transfer and membership replacement happen with the save in + // one transaction; preparation must stay read-only so a failed save cannot + // leave the catalog without a default. return nil } @@ -684,6 +684,9 @@ func validateLinkType(item models.LinkType) error { return nil } func catalogRepositoryError(err error) error { + if errors.Is(err, repository.ErrDefaultConflict) { + return NewServiceError(http.StatusConflict, "another priority is already the default") + } if errors.Is(err, repository.ErrDuplicateEntry) || database.IsUniqueConstraintError(err) { return NewServiceError(http.StatusConflict, "catalog name already exists") } diff --git a/internal/services/event_coordinator.go b/internal/services/event_coordinator.go index d2738d519..b18d706a3 100644 --- a/internal/services/event_coordinator.go +++ b/internal/services/event_coordinator.go @@ -177,22 +177,7 @@ func (ec *EventCoordinator) emitItemUpdatedInternal(original, updated *models.It applyActionContext(event, actionContext) ec.actionService.EmitActionEvent(event) } else { - oldVals := make(map[string]any) - newVals := make(map[string]any) - for _, fc := range fieldChanges { - fieldName := actionEventFieldName(fc.FieldName) - oldVals[fieldName] = fc.OldValue - newVals[fieldName] = fc.NewValue - } - event := &models.ActionEvent{ - EventType: models.ActionTriggerItemUpdated, - WorkspaceID: updated.WorkspaceID, - ItemID: updated.ID, - ActorUserID: actorUserID, - ItemTypeID: updated.ItemTypeID, - OldValues: oldVals, - NewValues: newVals, - } + event := buildItemUpdatedActionEvent(updated, actorUserID, fieldChanges) applyActionContext(event, actionContext) ec.actionService.EmitActionEvent(event) } @@ -208,6 +193,28 @@ func actionEventFieldName(historyFieldName string) string { return historyFieldName } +// buildItemUpdatedActionEvent turns the actual changed fields into the +// item_updated action payload. The coordinator and the legacy emitter share it +// so every transport emits the same shape. +func buildItemUpdatedActionEvent(updated *models.Item, actorUserID int, fieldChanges []HistoryEntry) *models.ActionEvent { + oldVals := make(map[string]any) + newVals := make(map[string]any) + for _, fc := range fieldChanges { + fieldName := actionEventFieldName(fc.FieldName) + oldVals[fieldName] = fc.OldValue + newVals[fieldName] = fc.NewValue + } + return &models.ActionEvent{ + EventType: models.ActionTriggerItemUpdated, + WorkspaceID: updated.WorkspaceID, + ItemID: updated.ID, + ActorUserID: actorUserID, + ItemTypeID: updated.ItemTypeID, + OldValues: oldVals, + NewValues: newVals, + } +} + func applyActionContext(event *models.ActionEvent, actionContext *ActionContext) { if actionContext == nil { return diff --git a/internal/services/item_update_application_service.go b/internal/services/item_update_application_service.go index 0e49fdfc4..ee4a45626 100644 --- a/internal/services/item_update_application_service.go +++ b/internal/services/item_update_application_service.go @@ -33,7 +33,6 @@ type ItemUpdateApplicationService struct { hierarchy *HierarchyService mentionService *MentionService emitter ItemUpdatedEmitter - fallback ItemUpdatedEmitter } func NewItemUpdateApplicationService(db database.Database, perm *PermissionService) *ItemUpdateApplicationService { @@ -71,25 +70,19 @@ func (s *ItemUpdateApplicationService) SetEmitter(emitter ItemUpdatedEmitter) { s.emitter = emitter } -// SetFallbackEmitter installs the event pipeline used when no EventCoordinator -// is wired. Legacy transports configure it with the original per-service -// notifier so lightweight embeddings keep identical side effects. -func (s *ItemUpdateApplicationService) SetFallbackEmitter(emitter ItemUpdatedEmitter) { - s.fallback = emitter -} - -// SetFallbackWebhook forwards the webhook sender into the legacy fallback -// emitter when one is installed. -func (s *ItemUpdateApplicationService) SetFallbackWebhook(dispatcher WebhookDispatcher) { - if legacy, ok := s.fallback.(*LegacyItemUpdatedEmitter); ok { +// SetEmitterWebhook configures the installed emitter's webhook sink. The +// coordinator owns its own sinks, so this only affects the legacy emitter used +// by lightweight embeddings. +func (s *ItemUpdateApplicationService) SetEmitterWebhook(dispatcher WebhookDispatcher) { + if legacy, ok := s.emitter.(*LegacyItemUpdatedEmitter); ok { legacy.SetWebhook(dispatcher) } } -// SetFallbackAction forwards the automation action service into the legacy -// fallback emitter when one is installed. -func (s *ItemUpdateApplicationService) SetFallbackAction(action ActionEventEmitter) { - if legacy, ok := s.fallback.(*LegacyItemUpdatedEmitter); ok { +// SetEmitterAction configures the installed emitter's automation sink. As with +// SetEmitterWebhook, the coordinator is unaffected. +func (s *ItemUpdateApplicationService) SetEmitterAction(action ActionEventEmitter) { + if legacy, ok := s.emitter.(*LegacyItemUpdatedEmitter); ok { legacy.SetAction(action) } } @@ -324,38 +317,16 @@ func (s *ItemUpdateApplicationService) updateItem( } assigneeChanged := !itemIntPtrEqual(result.OriginalItem.AssigneeID, result.Item.AssigneeID) - if contextual, ok := s.emitter.(contextualItemUpdatedEmitter); ok && actionContext != nil { - contextual.EmitItemUpdatedWithContext( - result.OriginalItem, - result.Item, - result.StatusChanged, - assigneeChanged, - actorUserID, - result.FieldChanges, - *actionContext, - actorUsername, - ) - } else if s.emitter != nil { - s.emitter.EmitItemUpdated( - result.OriginalItem, - result.Item, - result.StatusChanged, - assigneeChanged, - actorUserID, - result.FieldChanges, - actorUsername, - ) - } else if s.fallback != nil { - s.fallback.EmitItemUpdated( - result.OriginalItem, - result.Item, - result.StatusChanged, - assigneeChanged, - actorUserID, - result.FieldChanges, - actorUsername, - ) - } + s.emitItemUpdated( + result.OriginalItem, + result.Item, + result.StatusChanged, + assigneeChanged, + actorUserID, + result.FieldChanges, + actionContext, + actorUsername, + ) if s.mentionService != nil && result.OriginalItem.Description != result.Item.Description { if err := s.mentionService.ProcessMentions(ProcessMentionsParams{ @@ -390,31 +361,33 @@ func (s *ItemUpdateApplicationService) AddMilestoneWithContext( if err != nil || !changed { return result, changed, err } - if contextual, ok := s.emitter.(contextualItemUpdatedEmitter); ok { - contextual.EmitItemUpdatedWithContext( - result.OriginalItem, - result.Item, - false, - false, - actorUserID, - result.FieldChanges, - actionContext, - actorUsername, - ) - } else if s.emitter != nil { - s.emitter.EmitItemUpdated( - result.OriginalItem, - result.Item, - false, - false, - actorUserID, - result.FieldChanges, - actorUsername, - ) - } + s.emitItemUpdated( + result.OriginalItem, + result.Item, + false, + false, + actorUserID, + result.FieldChanges, + &actionContext, + actorUsername, + ) return result, true, nil } +// emitItemUpdated is the single dispatch point for item-update side effects. A +// contextual emitter receives the automation provenance; every other emitter +// gets the plain update. Callers select the emitter once at construction. +func (s *ItemUpdateApplicationService) emitItemUpdated(original, updated *models.Item, statusChanged, assigneeChanged bool, actorUserID int, fieldChanges []HistoryEntry, actionContext *ActionContext, actorUsername string) { + if s.emitter == nil { + return + } + if contextual, ok := s.emitter.(contextualItemUpdatedEmitter); ok && actionContext != nil { + contextual.EmitItemUpdatedWithContext(original, updated, statusChanged, assigneeChanged, actorUserID, fieldChanges, *actionContext, actorUsername) + return + } + s.emitter.EmitItemUpdated(original, updated, statusChanged, assigneeChanged, actorUserID, fieldChanges, actorUsername) +} + func itemProjectResolutionChanged(original, updated *models.Item) bool { return original.InheritProject != updated.InheritProject || !itemIntPtrEqual(original.ProjectID, updated.ProjectID) || diff --git a/internal/services/legacy_item_events.go b/internal/services/legacy_item_events.go index a2cdba397..754c738a7 100644 --- a/internal/services/legacy_item_events.go +++ b/internal/services/legacy_item_events.go @@ -54,26 +54,7 @@ func (e *LegacyItemUpdatedEmitter) EmitItemUpdated(original, updated *models.Ite if statusChanged { e.action.EmitActionEvent(newStatusTransitionActionEvent(original, updated, actorUserID)) } else { - e.action.EmitActionEvent(&models.ActionEvent{ - EventType: models.ActionTriggerItemUpdated, - WorkspaceID: updated.WorkspaceID, - ItemID: updated.ID, - ActorUserID: actorUserID, - ItemTypeID: updated.ItemTypeID, - OldValues: map[string]any{ - "status_id": original.StatusID, - "assignee_id": original.AssigneeID, - "title": original.Title, - "priority_id": original.PriorityID, - }, - NewValues: map[string]any{ - "status_id": updated.StatusID, - "assignee_id": updated.AssigneeID, - "title": updated.Title, - "priority_id": updated.PriorityID, - "creator_id": updated.CreatorID, - }, - }) + e.action.EmitActionEvent(buildItemUpdatedActionEvent(updated, actorUserID, fieldChanges)) } } diff --git a/internal/services/test_management_application_service.go b/internal/services/test_management_application_service.go index d24bfd18d..a7ee5c5e3 100644 --- a/internal/services/test_management_application_service.go +++ b/internal/services/test_management_application_service.go @@ -179,12 +179,15 @@ func (s *TestManagementApplicationService) CoverageSummary(userID int, scope Tes return models.TestCoverageSummary{}, err } typeIDs, workspaceID, err := s.coverageTypeIDs(scope) - if errors.Is(err, repository.ErrNotFound) || len(typeIDs) == 0 { - return models.TestCoverageSummary{}, nil - } if err != nil { + if errors.Is(err, repository.ErrNotFound) { + return models.TestCoverageSummary{}, nil + } return models.TestCoverageSummary{}, err } + if len(typeIDs) == 0 { + return models.TestCoverageSummary{}, nil + } total, covered, err := s.coverage.GetCoverageSummary(workspaceID, typeIDs) return coverageSummary(total, covered), err } @@ -194,12 +197,15 @@ func (s *TestManagementApplicationService) CoverageRequirements(userID int, scop return nil, 0, models.TestCoverageSummary{}, err } typeIDs, workspaceID, err := s.coverageTypeIDs(scope) - if errors.Is(err, repository.ErrNotFound) || len(typeIDs) == 0 { - return []models.RequirementCoverageItem{}, 0, models.TestCoverageSummary{}, nil - } if err != nil { + if errors.Is(err, repository.ErrNotFound) { + return []models.RequirementCoverageItem{}, 0, models.TestCoverageSummary{}, nil + } return nil, 0, models.TestCoverageSummary{}, err } + if len(typeIDs) == 0 { + return []models.RequirementCoverageItem{}, 0, models.TestCoverageSummary{}, nil + } if filter.ItemTypeID != nil { matched := false for _, id := range typeIDs { diff --git a/internal/services/time_worklog_service.go b/internal/services/time_worklog_service.go index c2b74bebe..71f44d373 100644 --- a/internal/services/time_worklog_service.go +++ b/internal/services/time_worklog_service.go @@ -72,7 +72,7 @@ func (s *TimeWorklogService) Create(userID int, input WorklogMutationInput) (*Wo if err != nil { return nil, err } - id, err := s.worklogs.Create(repository.NewWorklog{ + worklog, err := s.worklogs.CreateDetail(repository.NewWorklog{ ProjectID: input.ProjectID, UserID: userID, ItemID: input.ItemID, Description: prepared.description, DateUnix: WorklogDateUnix(prepared.date), StartTimeUnix: prepared.startUnix, EndTimeUnix: prepared.endUnix, DurationMinutes: prepared.durationMinutes, @@ -80,7 +80,7 @@ func (s *TimeWorklogService) Create(userID int, input WorklogMutationInput) (*Wo if err != nil { return nil, err } - return s.result(int(id), prepared) + return worklogMutationResult(worklog, prepared), nil } // Update validates, fully updates, and reloads a worklog. @@ -428,9 +428,13 @@ func (s *TimeWorklogService) result(worklogID int, prepared preparedWorklog) (*W if err != nil { return nil, err } + return worklogMutationResult(worklog, prepared), nil +} + +func worklogMutationResult(worklog *models.Worklog, prepared preparedWorklog) *WorklogMutationResult { return &WorklogMutationResult{ Worklog: worklog, Warnings: prepared.warnings, Timezone: prepared.timezone, Location: prepared.location, StartTimeUnix: prepared.startUnix, EndTimeUnix: prepared.endUnix, DurationMinutes: prepared.durationMinutes, - }, nil + } } diff --git a/internal/services/timer_service.go b/internal/services/timer_service.go index 43a9c32c7..e372e2191 100644 --- a/internal/services/timer_service.go +++ b/internal/services/timer_service.go @@ -665,16 +665,15 @@ func (s *TimerService) BookDraft(userID, id, expectedVersion int, idempotencyKey // the original worklog. if idempotencyKey != "" { booking, err := s.draftRepo.GetBooking(userID, idempotencyKey) - switch { - case err == nil: - if booking.DraftID != nil && *booking.DraftID == id { - return s.worklogs.Get(booking.WorklogID) - } - return nil, ErrTimerDraftConflict - case !errors.Is(err, repository.ErrNotFound): + if err == nil { + return s.bookingWorklog(id, booking) + } + if !errors.Is(err, repository.ErrNotFound) { return nil, err } } + // Ownership and existence are checked before validation so a foreign or + // missing draft keeps its not-found contract regardless of the payload. if _, err := s.draftRepo.GetDraft(id, userID); err != nil { if errors.Is(err, repository.ErrNotFound) { return nil, ErrTimerDraftNotFound @@ -697,7 +696,7 @@ func (s *TimerService) BookDraft(userID, id, expectedVersion int, idempotencyKey return nil, ErrTimerForbidden } } - worklogID, err := s.draftRepo.BookDraft(id, userID, expectedVersion, repository.CreateWorklogInput{ + booking, err := s.draftRepo.BookDraft(id, userID, expectedVersion, repository.CreateWorklogInput{ ProjectID: input.ProjectID, UserID: userID, ItemID: s.visibleDraftItem(userID, input.ItemID), @@ -708,31 +707,27 @@ func (s *TimerService) BookDraft(userID, id, expectedVersion int, idempotencyKey DurationMinutes: prepared.DurationMinutes, NowUnix: time.Now().UTC().Unix(), }, idempotencyKey) - if errors.Is(err, repository.ErrDuplicateEntry) { - booking, lookupErr := s.draftRepo.GetBooking(userID, idempotencyKey) - if lookupErr != nil { - return nil, lookupErr - } - return s.worklogs.Get(booking.WorklogID) + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound } if errors.Is(err, repository.ErrConflict) { - if _, gerr := s.draftRepo.GetDraft(id, userID); errors.Is(gerr, repository.ErrNotFound) { - // A concurrent booking with the same idempotency key may have won - // the race and consumed the draft; replay its worklog instead of - // reporting the draft missing. - if idempotencyKey != "" { - if booking, berr := s.draftRepo.GetBooking(userID, idempotencyKey); berr == nil && booking.DraftID != nil && *booking.DraftID == id { - return s.worklogs.Get(booking.WorklogID) - } - } - return nil, ErrTimerDraftNotFound - } return nil, ErrTimerDraftConflict } if err != nil { return nil, err } - return s.worklogs.Get(worklogID) + return s.bookingWorklog(id, booking) +} + +// bookingWorklog resolves a recorded booking to its worklog. It is the single +// place that compares the recorded draft to the requested one: a booking for a +// different draft is a conflicting key, never a successful replay. The booking +// lookup is already scoped to the authenticated user. +func (s *TimerService) bookingWorklog(draftID int, booking *repository.Booking) (*models.Worklog, error) { + if booking.DraftID == nil || *booking.DraftID != draftID { + return nil, ErrTimerDraftConflict + } + return s.worklogs.Get(booking.WorklogID) } // visibleDraftItem drops an item link the caller can no longer view, mirroring diff --git a/internal/validation/workspace_configuration.go b/internal/validation/workspace_configuration.go index d531782b5..f91aff0bc 100644 --- a/internal/validation/workspace_configuration.go +++ b/internal/validation/workspace_configuration.go @@ -32,12 +32,17 @@ func IsPriorityAllowedInWorkspace(q WorkspaceConfigurationQueryer, workspaceID, "SELECT configuration_set_id FROM workspace_configuration_sets WHERE workspace_id = ?", workspaceID, ).Scan(&configSetID) - if errors.Is(err, sql.ErrNoRows) || configSetID == nil { + if errors.Is(err, sql.ErrNoRows) { + // An unassigned workspace uses the global catalog. return true, nil } if err != nil { return false, fmt.Errorf("failed to query workspace config set: %w", err) } + if configSetID == nil { + // A NULL assignment is normal for an unassigned workspace. + return true, nil + } var allowed bool if err := q.QueryRow(