From ebba69a616fa9ca138a1fd00a68cdb023ae2cf36 Mon Sep 17 00:00:00 2001 From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:25:38 +0100 Subject: [PATCH 1/6] feat(time): draft worklogs and projectless timers for seamless tracking (GitHub #496) Add a persisted, user-owned draft worklog model and let timers run without a project. On stop the server books directly when booking information is complete and otherwise persists a recoverable draft. - time_worklog_drafts and time_worklog_bookings tables (SQLite + Postgres) - nullable active_timers.project_id with a SQLite table rebuild migration - TimeWorklogDraftRepository: ownership-scoped CRUD, atomic book with optimistic version, idempotent booking replay - TimerService: optional project/description start, book-or-draft stop with retry recovery; v1 keeps its frozen complete-only contract - v2: stop body identifies the timer, draft CRUD/book endpoints, AI tool schema and response updates --- api/openapi-v2.json | 979 +++++++++++++++++- internal/aitools/time.go | 16 +- internal/database/migrations.go | 166 +++ internal/database/schema/system.sql | 3 +- internal/database/schema/system_postgres.sql | 3 +- internal/database/schema/time_tracking.sql | 47 + .../schema/time_worklogs_postgres.sql | 48 +- internal/models/integration.go | 33 +- .../repository/active_timer_repository.go | 6 +- .../time_worklog_draft_repository.go | 368 +++++++ internal/restapi/v1/handlers/timers.go | 4 +- internal/restapi/v1/router.go | 3 +- internal/restapi/v2/contract-metadata.json | 133 +++ internal/restapi/v2/router.go | 17 + internal/restapi/v2/time_drafts.go | 186 ++++ internal/restapi/v2/time_projects.go | 34 +- internal/server/server.go | 3 +- internal/services/time_worklog_service.go | 68 +- internal/services/timer_service.go | 419 ++++++-- 19 files changed, 2429 insertions(+), 107 deletions(-) create mode 100644 internal/repository/time_worklog_draft_repository.go create mode 100644 internal/restapi/v2/time_drafts.go diff --git a/api/openapi-v2.json b/api/openapi-v2.json index ebd964217..2d8795cd6 100644 --- a/api/openapi-v2.json +++ b/api/openapi-v2.json @@ -30809,6 +30809,7 @@ }, "project_id": { "description": "The project id value.", + "nullable": true, "type": "integer" }, "project_name": { @@ -30848,7 +30849,6 @@ "created_at", "description", "id", - "project_id", "start_time_utc", "user_id", "workspace_id" @@ -30861,6 +30861,251 @@ ], "type": "object" }, + "GetTimeWorklogDraftsDraftIdResult": { + "additionalProperties": false, + "properties": { + "data": { + "additionalProperties": false, + "properties": { + "created_at": { + "description": "The created at value.", + "type": "integer" + }, + "customer_builtin_key": { + "description": "The customer builtin key value.", + "type": "string" + }, + "customer_name": { + "description": "The customer name value.", + "type": "string" + }, + "date": { + "description": "The date value.", + "nullable": true, + "type": "integer" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "nullable": true, + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "nullable": true, + "type": "integer" + }, + "id": { + "description": "The id value.", + "type": "integer" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "item_title": { + "description": "The item title value.", + "type": "string" + }, + "project_id": { + "description": "The project id value.", + "nullable": true, + "type": "integer" + }, + "project_name": { + "description": "The project name value.", + "type": "string" + }, + "source": { + "description": "The source value.", + "type": "string" + }, + "source_timer_id": { + "description": "The source timer id value.", + "nullable": true, + "type": "integer" + }, + "start_time": { + "description": "The start time value.", + "nullable": true, + "type": "integer" + }, + "updated_at": { + "description": "The updated at value.", + "type": "integer" + }, + "user_id": { + "description": "The user id value.", + "type": "integer" + }, + "version": { + "description": "The version value.", + "type": "integer" + }, + "workspace_id": { + "description": "The workspace id value.", + "nullable": true, + "type": "integer" + }, + "workspace_key": { + "description": "The workspace key value.", + "type": "string" + }, + "workspace_name": { + "description": "The workspace name value.", + "type": "string" + } + }, + "required": [ + "created_at", + "customer_name", + "description", + "id", + "item_title", + "project_name", + "source", + "updated_at", + "user_id", + "version", + "workspace_key", + "workspace_name" + ], + "type": "object" + } + }, + "required": [ + "data" + ], + "type": "object" + }, + "GetTimeWorklogDraftsResult": { + "additionalProperties": false, + "properties": { + "data": { + "items": { + "additionalProperties": false, + "properties": { + "created_at": { + "description": "The created at value.", + "type": "integer" + }, + "customer_builtin_key": { + "description": "The customer builtin key value.", + "type": "string" + }, + "customer_name": { + "description": "The customer name value.", + "type": "string" + }, + "date": { + "description": "The date value.", + "nullable": true, + "type": "integer" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "nullable": true, + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "nullable": true, + "type": "integer" + }, + "id": { + "description": "The id value.", + "type": "integer" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "item_title": { + "description": "The item title value.", + "type": "string" + }, + "project_id": { + "description": "The project id value.", + "nullable": true, + "type": "integer" + }, + "project_name": { + "description": "The project name value.", + "type": "string" + }, + "source": { + "description": "The source value.", + "type": "string" + }, + "source_timer_id": { + "description": "The source timer id value.", + "nullable": true, + "type": "integer" + }, + "start_time": { + "description": "The start time value.", + "nullable": true, + "type": "integer" + }, + "updated_at": { + "description": "The updated at value.", + "type": "integer" + }, + "user_id": { + "description": "The user id value.", + "type": "integer" + }, + "version": { + "description": "The version value.", + "type": "integer" + }, + "workspace_id": { + "description": "The workspace id value.", + "nullable": true, + "type": "integer" + }, + "workspace_key": { + "description": "The workspace key value.", + "type": "string" + }, + "workspace_name": { + "description": "The workspace name value.", + "type": "string" + } + }, + "required": [ + "created_at", + "customer_name", + "description", + "id", + "item_title", + "project_name", + "source", + "updated_at", + "user_id", + "version", + "workspace_key", + "workspace_name" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "type": "object" + }, "GetTimeWorklogsAggregateResult": { "additionalProperties": false, "properties": { @@ -59523,6 +59768,190 @@ ], "type": "object" }, + "PatchTimeWorklogDraftsDraftIdPayload": { + "additionalProperties": false, + "properties": { + "date": { + "description": "The date value.", + "type": "string" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration": { + "description": "The duration value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "type": "string" + }, + "idempotency_key": { + "description": "The idempotency key value.", + "type": "string" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "project_id": { + "description": "The project id value.", + "nullable": true, + "type": "integer" + }, + "start_time": { + "description": "The start time value.", + "type": "string" + }, + "timezone": { + "description": "The timezone value.", + "type": "string" + }, + "version": { + "description": "The version value.", + "type": "integer" + } + }, + "required": [ + "date", + "description", + "duration", + "duration_minutes", + "end_time", + "idempotency_key", + "start_time", + "timezone", + "version" + ], + "type": "object" + }, + "PatchTimeWorklogDraftsDraftIdResult": { + "additionalProperties": false, + "properties": { + "data": { + "additionalProperties": false, + "properties": { + "created_at": { + "description": "The created at value.", + "type": "integer" + }, + "customer_builtin_key": { + "description": "The customer builtin key value.", + "type": "string" + }, + "customer_name": { + "description": "The customer name value.", + "type": "string" + }, + "date": { + "description": "The date value.", + "nullable": true, + "type": "integer" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "nullable": true, + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "nullable": true, + "type": "integer" + }, + "id": { + "description": "The id value.", + "type": "integer" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "item_title": { + "description": "The item title value.", + "type": "string" + }, + "project_id": { + "description": "The project id value.", + "nullable": true, + "type": "integer" + }, + "project_name": { + "description": "The project name value.", + "type": "string" + }, + "source": { + "description": "The source value.", + "type": "string" + }, + "source_timer_id": { + "description": "The source timer id value.", + "nullable": true, + "type": "integer" + }, + "start_time": { + "description": "The start time value.", + "nullable": true, + "type": "integer" + }, + "updated_at": { + "description": "The updated at value.", + "type": "integer" + }, + "user_id": { + "description": "The user id value.", + "type": "integer" + }, + "version": { + "description": "The version value.", + "type": "integer" + }, + "workspace_id": { + "description": "The workspace id value.", + "nullable": true, + "type": "integer" + }, + "workspace_key": { + "description": "The workspace key value.", + "type": "string" + }, + "workspace_name": { + "description": "The workspace name value.", + "type": "string" + } + }, + "required": [ + "created_at", + "customer_name", + "description", + "id", + "item_title", + "project_name", + "source", + "updated_at", + "user_id", + "version", + "workspace_key", + "workspace_name" + ], + "type": "object" + } + }, + "required": [ + "data" + ], + "type": "object" + }, "PatchTimeWorklogsWorklogIdPayload": { "additionalProperties": false, "properties": { @@ -89531,16 +89960,36 @@ ], "type": "object" }, + "PostTimeTimersActiveStopPayload": { + "additionalProperties": false, + "properties": { + "timer_id": { + "description": "The timer id value.", + "nullable": true, + "type": "integer" + } + }, + "type": "object" + }, "PostTimeTimersActiveStopResult": { "additionalProperties": false, "properties": { "data": { "additionalProperties": false, "properties": { + "booked": { + "description": "The booked value.", + "type": "boolean" + }, "description": { "description": "The description value.", "type": "string" }, + "draft_id": { + "description": "The draft id value.", + "nullable": true, + "type": "integer" + }, "duration_minutes": { "description": "The duration minutes value.", "type": "integer" @@ -89557,18 +90006,19 @@ "description": "The timer id value.", "type": "integer" }, - "worklog_created": { - "description": "The worklog created value.", - "type": "boolean" + "worklog_id": { + "description": "The worklog id value.", + "nullable": true, + "type": "integer" } }, "required": [ + "booked", "description", "duration_minutes", "duration_seconds", "stopped", - "timer_id", - "worklog_created" + "timer_id" ], "type": "object" } @@ -89592,6 +90042,7 @@ }, "project_id": { "description": "The project id value.", + "nullable": true, "type": "integer" }, "workspace_id": { @@ -89601,7 +90052,6 @@ }, "required": [ "description", - "project_id", "workspace_id" ], "type": "object" @@ -89647,6 +90097,7 @@ }, "project_id": { "description": "The project id value.", + "nullable": true, "type": "integer" }, "project_name": { @@ -89686,7 +90137,6 @@ "created_at", "description", "id", - "project_id", "start_time_utc", "user_id", "workspace_id" @@ -89699,6 +90149,202 @@ ], "type": "object" }, + "PostTimeWorklogDraftsDraftIdBookPayload": { + "additionalProperties": false, + "properties": { + "date": { + "description": "The date value.", + "type": "string" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration": { + "description": "The duration value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "type": "string" + }, + "idempotency_key": { + "description": "The idempotency key value.", + "type": "string" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "project_id": { + "description": "The project id value.", + "nullable": true, + "type": "integer" + }, + "start_time": { + "description": "The start time value.", + "type": "string" + }, + "timezone": { + "description": "The timezone value.", + "type": "string" + }, + "version": { + "description": "The version value.", + "type": "integer" + } + }, + "required": [ + "date", + "description", + "duration", + "duration_minutes", + "end_time", + "idempotency_key", + "start_time", + "timezone", + "version" + ], + "type": "object" + }, + "PostTimeWorklogDraftsDraftIdBookResult": { + "additionalProperties": false, + "properties": { + "data": { + "additionalProperties": false, + "properties": { + "created_at": { + "description": "The created at value.", + "type": "integer" + }, + "customer_builtin_key": { + "description": "The customer builtin key value.", + "type": "string" + }, + "customer_id": { + "description": "The customer id value.", + "type": "integer" + }, + "customer_name": { + "description": "The customer name value.", + "type": "string" + }, + "date": { + "description": "The date value.", + "type": "integer" + }, + "description": { + "description": "The description value.", + "type": "string" + }, + "duration_minutes": { + "description": "The duration minutes value.", + "type": "integer" + }, + "end_time": { + "description": "The end time value.", + "type": "integer" + }, + "id": { + "description": "The id value.", + "type": "integer" + }, + "item_id": { + "description": "The item id value.", + "nullable": true, + "type": "integer" + }, + "item_title": { + "description": "The item title value.", + "type": "string" + }, + "project_id": { + "description": "The project id value.", + "type": "integer" + }, + "project_max_hours": { + "description": "The project max hours value.", + "nullable": true, + "type": "number" + }, + "project_name": { + "description": "The project name value.", + "type": "string" + }, + "project_total_hours": { + "description": "The project total hours value.", + "nullable": true, + "type": "number" + }, + "start_time": { + "description": "The start time value.", + "type": "integer" + }, + "updated_at": { + "description": "The updated at value.", + "type": "integer" + }, + "user_id": { + "description": "The user id value.", + "nullable": true, + "type": "integer" + }, + "user_name": { + "description": "The user name value.", + "type": "string" + }, + "warnings": { + "description": "The warnings value.", + "items": { + "type": "string" + }, + "type": "array" + }, + "workspace_id": { + "description": "The workspace id value.", + "nullable": true, + "type": "integer" + }, + "workspace_item_number": { + "description": "The workspace item number value.", + "type": "integer" + }, + "workspace_key": { + "description": "The workspace key value.", + "type": "string" + } + }, + "required": [ + "created_at", + "customer_id", + "customer_name", + "date", + "description", + "duration_minutes", + "end_time", + "id", + "item_title", + "project_id", + "project_name", + "start_time", + "updated_at", + "user_name", + "workspace_item_number", + "workspace_key" + ], + "type": "object" + } + }, + "required": [ + "data" + ], + "type": "object" + }, "PostTimeWorklogsPayload": { "additionalProperties": false, "properties": { @@ -120913,6 +121559,16 @@ "description": "Stop timer. The server validates resource ownership and command preconditions before persisting changes. Unknown JSON fields are rejected when the operation accepts a body.", "operationId": "postTimeTimersActiveStop", "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PostTimeTimersActiveStopPayload" + } + } + }, + "required": true + }, "responses": { "200": { "content": { @@ -120924,6 +121580,9 @@ }, "description": "Stop timer response." }, + "400": { + "$ref": "#/components/responses/InvalidRequestError" + }, "401": { "$ref": "#/components/responses/AuthenticationError" }, @@ -120933,6 +121592,12 @@ "404": { "$ref": "#/components/responses/NotFoundError" }, + "413": { + "$ref": "#/components/responses/PayloadTooLargeError" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaTypeError" + }, "429": { "$ref": "#/components/responses/RateLimitError" }, @@ -120954,6 +121619,304 @@ ] } }, + "/time/worklog-drafts": { + "get": { + "description": "List draft worklogs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", + "operationId": "getTimeWorklogDrafts", + "parameters": [], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetTimeWorklogDraftsResult" + } + } + }, + "description": "List draft worklogs response." + }, + "401": { + "$ref": "#/components/responses/AuthenticationError" + }, + "403": { + "$ref": "#/components/responses/PermissionError" + }, + "429": { + "$ref": "#/components/responses/RateLimitError" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "List draft worklogs", + "tags": [ + "Time tracking" + ], + "x-required-scopes": [ + "time:read" + ] + } + }, + "/time/worklog-drafts/{draft_id}": { + "delete": { + "description": "Delete a draft worklog. The server verifies resource ownership and deletion preconditions before removing the resource.", + "operationId": "deleteTimeWorklogDraftsDraftId", + "parameters": [ + { + "description": "The draft worklog identifier.", + "in": "path", + "name": "draft_id", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "204": { + "description": "Request completed successfully with no response body." + }, + "401": { + "$ref": "#/components/responses/AuthenticationError" + }, + "403": { + "$ref": "#/components/responses/PermissionError" + }, + "404": { + "$ref": "#/components/responses/NotFoundError" + }, + "429": { + "$ref": "#/components/responses/RateLimitError" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Delete a draft worklog", + "tags": [ + "Time tracking" + ], + "x-required-scopes": [ + "time:write" + ] + }, + "get": { + "description": "Get a draft worklog. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", + "operationId": "getTimeWorklogDraftsDraftId", + "parameters": [ + { + "description": "The draft worklog identifier.", + "in": "path", + "name": "draft_id", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GetTimeWorklogDraftsDraftIdResult" + } + } + }, + "description": "Get a draft worklog response." + }, + "401": { + "$ref": "#/components/responses/AuthenticationError" + }, + "403": { + "$ref": "#/components/responses/PermissionError" + }, + "404": { + "$ref": "#/components/responses/NotFoundError" + }, + "429": { + "$ref": "#/components/responses/RateLimitError" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Get a draft worklog", + "tags": [ + "Time tracking" + ], + "x-required-scopes": [ + "time:read" + ] + }, + "patch": { + "description": "Update a draft worklog. The operation uses JSON Merge Patch: omitted fields remain unchanged and documented nullable fields accept null. Unknown fields are rejected.", + "operationId": "patchTimeWorklogDraftsDraftId", + "parameters": [ + { + "description": "The draft worklog identifier.", + "in": "path", + "name": "draft_id", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/PatchTimeWorklogDraftsDraftIdPayload" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PatchTimeWorklogDraftsDraftIdResult" + } + } + }, + "description": "Update a draft worklog response." + }, + "400": { + "$ref": "#/components/responses/InvalidRequestError" + }, + "401": { + "$ref": "#/components/responses/AuthenticationError" + }, + "403": { + "$ref": "#/components/responses/PermissionError" + }, + "404": { + "$ref": "#/components/responses/NotFoundError" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLargeError" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaTypeError" + }, + "429": { + "$ref": "#/components/responses/RateLimitError" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Update a draft worklog", + "tags": [ + "Time tracking" + ], + "x-required-scopes": [ + "time:write" + ] + } + }, + "/time/worklog-drafts/{draft_id}/book": { + "post": { + "description": "Book a draft worklog. The server validates resource ownership and command preconditions before persisting changes. Unknown JSON fields are rejected when the operation accepts a body.", + "operationId": "postTimeWorklogDraftsDraftIdBook", + "parameters": [ + { + "description": "The draft worklog identifier.", + "in": "path", + "name": "draft_id", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PostTimeWorklogDraftsDraftIdBookPayload" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PostTimeWorklogDraftsDraftIdBookResult" + } + } + }, + "description": "Book a draft worklog response." + }, + "400": { + "$ref": "#/components/responses/InvalidRequestError" + }, + "401": { + "$ref": "#/components/responses/AuthenticationError" + }, + "403": { + "$ref": "#/components/responses/PermissionError" + }, + "404": { + "$ref": "#/components/responses/NotFoundError" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLargeError" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaTypeError" + }, + "429": { + "$ref": "#/components/responses/RateLimitError" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + }, + "security": [ + { + "BearerAuth": [] + } + ], + "summary": "Book a draft worklog", + "tags": [ + "Time tracking" + ], + "x-required-scopes": [ + "time:write" + ] + } + }, "/time/worklogs": { "get": { "description": "List worklogs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", diff --git a/internal/aitools/time.go b/internal/aitools/time.go index 27c54beb7..14ada315b 100644 --- a/internal/aitools/time.go +++ b/internal/aitools/time.go @@ -110,7 +110,7 @@ type logTimeOut struct { // ---------------------------------------------------------------------------- type startTimerArgs struct { - ProjectID int `json:"project_id" jsonschema:"Time project ID"` + ProjectID *int `json:"project_id,omitempty" jsonschema:"Optional time project ID; when omitted the timer stops into a recoverable draft"` WorkspaceID int `json:"workspace_id" jsonschema:"Workspace ID"` Description string `json:"description" jsonschema:"Timer description"` ItemID *int `json:"item_id,omitempty" jsonschema:"Optional linked work item ID (alternative: item_key)"` @@ -132,7 +132,9 @@ type stopTimerOut struct { Description string `json:"description"` DurationSeconds int64 `json:"duration_seconds"` DurationMinutes int `json:"duration_minutes"` - WorklogCreated bool `json:"worklog_created"` + Booked bool `json:"booked"` + WorklogID *int `json:"worklog_id,omitempty"` + DraftID *int `json:"draft_id,omitempty"` } func init() { @@ -329,7 +331,7 @@ func init() { Group: CapabilityTime, Access: AccessWrite, Risk: RiskMedium, - Description: "Start a time tracking timer. Only one timer can be active at a time. An optional work item can be linked by numeric ID or key (e.g. PROJ-42).", + Description: "Start a time tracking timer. Only one timer can be active at a time. Project is optional; a timer without a project stops into a recoverable draft. An optional work item can be linked by numeric ID or key (e.g. PROJ-42).", Scopes: []string{auth.ScopeTimeWrite}, Run: func(_ context.Context, env *Env, args startTimerArgs) (any, error) { itemID, toolErr := resolveOptionalItemRef(env, args.ItemID, args.ItemKey) @@ -358,10 +360,10 @@ func init() { Group: CapabilityTime, Access: AccessWrite, Risk: RiskMedium, - Description: "Stop the user's currently running timer and create a worklog entry.", + Description: "Stop the user's currently running timer. When booking information is complete the time is booked; otherwise a recoverable draft is created.", Scopes: []string{auth.ScopeTimeWrite}, Run: func(_ context.Context, env *Env, _ stopTimerArgs) (any, error) { - res, err := env.TimerService.StopActiveForUser(env.UserID) + res, err := env.TimerService.StopActiveTimer(env.UserID, nil) if err != nil { if errors.Is(err, services.ErrTimerNotFound) { return map[string]string{"error": "no active timer running"}, nil @@ -378,7 +380,9 @@ func init() { Description: res.Description, DurationSeconds: res.DurationSeconds, DurationMinutes: res.DurationMinutes, - WorklogCreated: res.WorklogCreated, + Booked: res.Booked, + WorklogID: res.WorklogID, + DraftID: res.DraftID, }, nil }, }) diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 526a274f3..388be2027 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3378,8 +3378,102 @@ CREATE INDEX IF NOT EXISTS idx_plane_import_mappings_windshift ON plane_import_m SQLite: customerAccessMigration, Postgres: strings.ReplaceAll(customerAccessMigration, "DATETIME", "TIMESTAMPTZ"), }, + { + Version: "20261123_active_timer_nullable_project", + Name: "Allow a running timer without a project for seamless time tracking", + // Effect present when project_id is nullable. SQLite cannot drop a NOT + // NULL constraint in place, so ApplySQLite rebuilds the table; the SQL + // field is the checksum marker. + CheckSQLite: `SELECT CASE WHEN (SELECT "notnull" FROM pragma_table_info('active_timers') WHERE name='project_id') = 0 THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN (SELECT is_nullable FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='active_timers' AND column_name='project_id') = 'YES' THEN 1 ELSE 0 END`, + SQLite: "active-timer-nullable-project:v1", + ApplySQLite: applySQLiteActiveTimerNullableProject, + Postgres: `ALTER TABLE active_timers ALTER COLUMN project_id DROP NOT NULL;`, + }, + { + Version: "20261124_time_worklog_drafts", + Name: "Persist incomplete time entries as user-owned draft worklogs", + CheckSQLite: `SELECT CASE WHEN (SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('time_worklog_drafts','time_worklog_bookings')) = 2 THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=current_schema() AND table_name IN ('time_worklog_drafts','time_worklog_bookings')) = 2 THEN 1 ELSE 0 END`, + SQLite: timeWorklogDraftsMigrationSQLite, + Postgres: timeWorklogDraftsMigrationPostgres, + }, } +const timeWorklogDraftsMigrationSQLite = ` +CREATE TABLE IF NOT EXISTS time_worklog_drafts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + project_id INTEGER, + item_id INTEGER, + workspace_id INTEGER, + description TEXT, + date INTEGER, + start_time INTEGER, + end_time INTEGER, + duration_minutes INTEGER, + source TEXT NOT NULL DEFAULT 'manual', + source_timer_id INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (project_id) REFERENCES time_projects(id) ON DELETE SET NULL, + FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE SET NULL +); +CREATE INDEX IF NOT EXISTS idx_time_worklog_drafts_user_id ON time_worklog_drafts(user_id); +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_drafts_source_timer ON time_worklog_drafts(user_id, source_timer_id) WHERE source_timer_id IS NOT NULL; +CREATE TABLE IF NOT EXISTS time_worklog_bookings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + idempotency_key TEXT NOT NULL, + worklog_id INTEGER NOT NULL, + draft_id INTEGER, + created_at INTEGER NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (worklog_id) REFERENCES time_worklogs(id) ON DELETE CASCADE +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_bookings_user_key ON time_worklog_bookings(user_id, idempotency_key); +` + +const timeWorklogDraftsMigrationPostgres = ` +CREATE TABLE IF NOT EXISTS time_worklog_drafts ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + project_id INTEGER, + item_id INTEGER, + workspace_id INTEGER, + description TEXT, + date INTEGER, + start_time INTEGER, + end_time INTEGER, + duration_minutes INTEGER, + source TEXT NOT NULL DEFAULT 'manual', + source_timer_id INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (project_id) REFERENCES time_projects(id) ON DELETE SET NULL, + FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE SET NULL +); +CREATE INDEX IF NOT EXISTS idx_time_worklog_drafts_user_id ON time_worklog_drafts(user_id); +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_drafts_source_timer ON time_worklog_drafts(user_id, source_timer_id) WHERE source_timer_id IS NOT NULL; +CREATE TABLE IF NOT EXISTS time_worklog_bookings ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + idempotency_key TEXT NOT NULL, + worklog_id INTEGER NOT NULL, + draft_id INTEGER, + created_at INTEGER NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (worklog_id) REFERENCES time_worklogs(id) ON DELETE CASCADE +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_bookings_user_key ON time_worklog_bookings(user_id, idempotency_key); +` + const customerAccessMigration = ` ALTER TABLE sso_providers ADD COLUMN account_type TEXT NOT NULL DEFAULT 'internal'; ALTER TABLE sso_providers ADD COLUMN customer_organisation_id INTEGER REFERENCES customer_organisations(id) ON DELETE RESTRICT; @@ -5444,3 +5538,75 @@ func applySQLiteQueuesCollectionScope(db Database) (retErr error) { } return nil } + +// applySQLiteActiveTimerNullableProject rebuilds active_timers with a nullable +// project_id so a timer can run before booking information is known. SQLite +// cannot drop a NOT NULL constraint in place, so the rows are copied into a +// fresh table and swapped. The unique timer-per-user index is recreated. +func applySQLiteActiveTimerNullableProject(db Database) (retErr error) { + sqliteDB, ok := db.(*SQLiteDB) + if !ok { + return fmt.Errorf("expected SQLite database, got %T", db) + } + + ctx := context.Background() + conn, err := sqliteDB.writeConn.Conn(ctx) + if err != nil { + return fmt.Errorf("acquire SQLite write connection: %w", err) + } + defer func() { _ = conn.Close() }() + + var foreignKeysEnabled bool + if err := conn.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&foreignKeysEnabled); err != nil { + return fmt.Errorf("read foreign_keys pragma: %w", err) + } + if foreignKeysEnabled { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil { + return fmt.Errorf("disable foreign keys: %w", err) + } + defer func() { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); retErr == nil && err != nil { + retErr = fmt.Errorf("restore foreign keys: %w", err) + } + }() + } + + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin active_timers rebuild: %w", err) + } + defer func() { _ = tx.Rollback() }() + + statements := []string{ + `CREATE TABLE active_timers_migration ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + workspace_id INTEGER NOT NULL, + item_id INTEGER, + project_id INTEGER, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + description TEXT NOT NULL, + start_time_utc INTEGER NOT NULL, + created_at INTEGER NOT NULL, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, + FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, + FOREIGN KEY (project_id) REFERENCES time_projects(id) ON DELETE CASCADE + )`, + `INSERT INTO active_timers_migration (id, workspace_id, item_id, project_id, user_id, description, start_time_utc, created_at) + SELECT id, workspace_id, item_id, project_id, user_id, description, start_time_utc, created_at FROM active_timers`, + `DROP TABLE active_timers`, + `ALTER TABLE active_timers_migration RENAME TO active_timers`, + `CREATE INDEX IF NOT EXISTS idx_active_timers_workspace_id ON active_timers(workspace_id)`, + `CREATE INDEX IF NOT EXISTS idx_active_timers_item_id ON active_timers(item_id)`, + `CREATE INDEX IF NOT EXISTS idx_active_timers_project_id ON active_timers(project_id)`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_active_timers_user_id ON active_timers(user_id)`, + } + for _, statement := range statements { + if _, err := tx.ExecContext(ctx, statement); err != nil { + return fmt.Errorf("rebuild active_timers: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit active_timers rebuild: %w", err) + } + return nil +} diff --git a/internal/database/schema/system.sql b/internal/database/schema/system.sql index b59b08444..7955cdc15 100644 --- a/internal/database/schema/system.sql +++ b/internal/database/schema/system.sql @@ -205,7 +205,8 @@ CREATE TABLE IF NOT EXISTS active_timers ( id INTEGER PRIMARY KEY AUTOINCREMENT, workspace_id INTEGER NOT NULL, item_id INTEGER, - project_id INTEGER NOT NULL, + -- Nullable: a timer may run before booking information (project) is known. + project_id INTEGER, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, description TEXT NOT NULL, start_time_utc INTEGER NOT NULL, diff --git a/internal/database/schema/system_postgres.sql b/internal/database/schema/system_postgres.sql index 237e45d9d..ea4a9918c 100644 --- a/internal/database/schema/system_postgres.sql +++ b/internal/database/schema/system_postgres.sql @@ -223,7 +223,8 @@ CREATE TABLE IF NOT EXISTS active_timers ( id SERIAL PRIMARY KEY, workspace_id INTEGER NOT NULL, item_id INTEGER, - project_id INTEGER NOT NULL, + -- Nullable: a timer may run before booking information (project) is known. + project_id INTEGER, user_id INTEGER NOT NULL, description TEXT NOT NULL, start_time_utc INTEGER NOT NULL, diff --git a/internal/database/schema/time_tracking.sql b/internal/database/schema/time_tracking.sql index 773c19571..5eda7a92b 100644 --- a/internal/database/schema/time_tracking.sql +++ b/internal/database/schema/time_tracking.sql @@ -140,3 +140,50 @@ CREATE INDEX IF NOT EXISTS idx_customer_organisation_managers_org ON customer_or CREATE INDEX IF NOT EXISTS idx_customer_organisation_members_org ON customer_organisation_members(customer_organisation_id); -- migration: 0023_time_projects_active_sqlite + +-- Draft worklogs: persisted, user-owned incomplete time entries produced when a +-- timer stops without complete booking information (project/description). They +-- are intentionally separate from time_worklogs so reporting, briefings, item +-- totals, and budget rollups cannot see unbooked time by construction. +CREATE TABLE IF NOT EXISTS time_worklog_drafts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + project_id INTEGER, + item_id INTEGER, + workspace_id INTEGER, + description TEXT, + date INTEGER, + start_time INTEGER, + end_time INTEGER, + duration_minutes INTEGER, + source TEXT NOT NULL DEFAULT 'manual', + source_timer_id INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (project_id) REFERENCES time_projects(id) ON DELETE SET NULL, + FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE SET NULL +); + +CREATE INDEX IF NOT EXISTS idx_time_worklog_drafts_user_id ON time_worklog_drafts(user_id); +-- At most one draft per source timer, so a lost stop response can be retried +-- and resolve to the original draft instead of creating a second one. +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_drafts_source_timer ON time_worklog_drafts(user_id, source_timer_id) WHERE source_timer_id IS NOT NULL; + +-- Booking idempotency: records the worklog produced by a caller-scoped +-- idempotency key so a retried booking replays the same worklog instead of +-- duplicating booked time. Timer-stop bookings use the key "timer:". +CREATE TABLE IF NOT EXISTS time_worklog_bookings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + idempotency_key TEXT NOT NULL, + worklog_id INTEGER NOT NULL, + draft_id INTEGER, + created_at INTEGER NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (worklog_id) REFERENCES time_worklogs(id) ON DELETE CASCADE +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_bookings_user_key ON time_worklog_bookings(user_id, idempotency_key); diff --git a/internal/database/schema/time_worklogs_postgres.sql b/internal/database/schema/time_worklogs_postgres.sql index 939f91b90..d82a108e7 100644 --- a/internal/database/schema/time_worklogs_postgres.sql +++ b/internal/database/schema/time_worklogs_postgres.sql @@ -17,4 +17,50 @@ CREATE TABLE IF NOT EXISTS time_worklogs ( CREATE INDEX IF NOT EXISTS idx_time_worklogs_project_id ON time_worklogs(project_id); CREATE INDEX IF NOT EXISTS idx_time_worklogs_date ON time_worklogs(date); CREATE INDEX IF NOT EXISTS idx_time_worklogs_item_id ON time_worklogs(item_id); -CREATE INDEX IF NOT EXISTS idx_time_worklogs_user_id ON time_worklogs(user_id); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_time_worklogs_user_id ON time_worklogs(user_id); +-- Draft worklogs: persisted, user-owned incomplete time entries produced when a +-- timer stops without complete booking information (project/description). They +-- are intentionally separate from time_worklogs so reporting, briefings, item +-- totals, and budget rollups cannot see unbooked time by construction. +CREATE TABLE IF NOT EXISTS time_worklog_drafts ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + project_id INTEGER, + item_id INTEGER, + workspace_id INTEGER, + description TEXT, + date INTEGER, + start_time INTEGER, + end_time INTEGER, + duration_minutes INTEGER, + source TEXT NOT NULL DEFAULT 'manual', + source_timer_id INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (project_id) REFERENCES time_projects(id) ON DELETE SET NULL, + FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE SET NULL, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE SET NULL +); + +CREATE INDEX IF NOT EXISTS idx_time_worklog_drafts_user_id ON time_worklog_drafts(user_id); +-- At most one draft per source timer, so a lost stop response can be retried +-- and resolve to the original draft instead of creating a second one. +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_drafts_source_timer ON time_worklog_drafts(user_id, source_timer_id) WHERE source_timer_id IS NOT NULL; + +-- Booking idempotency: records the worklog produced by a caller-scoped +-- idempotency key so a retried booking replays the same worklog instead of +-- duplicating booked time. Timer-stop bookings use the key "timer:". +CREATE TABLE IF NOT EXISTS time_worklog_bookings ( + id SERIAL PRIMARY KEY, + user_id INTEGER NOT NULL, + idempotency_key TEXT NOT NULL, + worklog_id INTEGER NOT NULL, + draft_id INTEGER, + created_at INTEGER NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (worklog_id) REFERENCES time_worklogs(id) ON DELETE CASCADE +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_time_worklog_bookings_user_key ON time_worklog_bookings(user_id, idempotency_key); diff --git a/internal/models/integration.go b/internal/models/integration.go index 67b772a24..51e1bd11a 100644 --- a/internal/models/integration.go +++ b/internal/models/integration.go @@ -345,7 +345,34 @@ type TimeProject struct { IsManager bool `json:"is_manager,omitempty"` // Whether current user is a manager of this project } -// Worklog represents a time tracking entry +// TimeWorklogDraft is a persisted, user-owned incomplete time entry. It is +// produced when a timer stops without complete booking information, or when a +// user starts a manual entry and saves it incomplete. Booking a draft creates a +// time_worklogs row and deletes the draft atomically. +type TimeWorklogDraft struct { + ID int `json:"id"` + UserID int `json:"user_id"` + ProjectID *int `json:"project_id,omitempty"` + ItemID *int `json:"item_id,omitempty"` + WorkspaceID *int `json:"workspace_id,omitempty"` + Description string `json:"description"` + Date *int64 `json:"date,omitempty"` + StartTime *int64 `json:"start_time,omitempty"` + EndTime *int64 `json:"end_time,omitempty"` + DurationMins *int `json:"duration_minutes,omitempty"` + Source string `json:"source"` + SourceTimerID *int `json:"source_timer_id,omitempty"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + Version int `json:"version"` + ProjectName string `json:"project_name,omitempty"` + ItemTitle string `json:"item_title,omitempty"` + WorkspaceKey string `json:"workspace_key,omitempty"` + WorkspaceName string `json:"workspace_name,omitempty"` + CustomerName string `json:"customer_name,omitempty"` + CustomerBuiltin string `json:"customer_builtin_key,omitempty"` +} + type Worklog struct { ID int `json:"id"` ProjectID int `json:"project_id"` @@ -372,11 +399,13 @@ type Worklog struct { } // ActiveTimer represents a running timer +// +// ProjectID is nullable: a timer may run before booking information is known. type ActiveTimer struct { ID int `json:"id"` WorkspaceID int `json:"workspace_id"` ItemID *int `json:"item_id,omitempty"` // Optional link to work item - ProjectID int `json:"project_id"` + ProjectID *int `json:"project_id,omitempty"` UserID int `json:"user_id"` Description string `json:"description"` StartTimeUTC int64 `json:"start_time_utc"` // Unix timestamp in UTC diff --git a/internal/repository/active_timer_repository.go b/internal/repository/active_timer_repository.go index 3aa04bbed..947963410 100644 --- a/internal/repository/active_timer_repository.go +++ b/internal/repository/active_timer_repository.go @@ -67,7 +67,7 @@ func (r *ActiveTimerRepository) HasActiveTimerForUser(userID int) (bool, error) type CreateTimerInput struct { WorkspaceID int ItemID *int - ProjectID int + ProjectID *int UserID int Description string StartTimeUTC int64 @@ -100,7 +100,9 @@ func (r *ActiveTimerRepository) DeleteTimer(id int) error { // FinalizeTimer atomically materializes a timer as a worklog and removes the // active timer. Keeping both writes in one transaction prevents a failed timer -// delete from leaving behind a worklog that would be duplicated on retry. +// delete from leaving behind a worklog that would be duplicated on retry. It is +// retained for callers that do not need booking-idempotency; the timer stop path +// uses FinalizeTimerBooking. func (r *ActiveTimerRepository) FinalizeTimer(timerID int, in CreateWorklogInput) error { return database.WithTx(r.db, func(tx database.Tx) error { if _, err := tx.ExecWrite(createWorklogQuery, diff --git a/internal/repository/time_worklog_draft_repository.go b/internal/repository/time_worklog_draft_repository.go new file mode 100644 index 000000000..389811fe8 --- /dev/null +++ b/internal/repository/time_worklog_draft_repository.go @@ -0,0 +1,368 @@ +package repository + +import ( + "database/sql" + "errors" + + "windshift/internal/database" + "windshift/internal/models" +) + +// ErrConflict reports an optimistic-concurrency conflict: the caller's version +// no longer matches the stored row. Callers map it to HTTP 409. +var ErrConflict = errors.New("conflict") + +// TimeWorklogDraftRepository persists time_worklog_drafts rows: incomplete, +// user-owned time entries produced when a timer stops without booking +// information, or when a manual entry is saved incomplete. Drafts are separate +// from time_worklogs so reporting and billing never see unbooked time. +type TimeWorklogDraftRepository struct { + db database.Database +} + +// NewTimeWorklogDraftRepository creates a TimeWorklogDraftRepository. +func NewTimeWorklogDraftRepository(db database.Database) *TimeWorklogDraftRepository { + return &TimeWorklogDraftRepository{db: db} +} + +// CreateDraftInput captures the fields of a new draft. Every booking field is +// optional because the draft exists precisely because booking information is +// incomplete. +type CreateDraftInput struct { + UserID int + ProjectID *int + ItemID *int + WorkspaceID *int + Description string + DateUnix *int64 + StartTimeUnix *int64 + EndTimeUnix *int64 + DurationMinutes *int + Source string + SourceTimerID *int + NowUnix int64 +} + +const insertDraftQuery = ` + INSERT INTO time_worklog_drafts ( + user_id, project_id, item_id, workspace_id, description, date, + start_time, end_time, duration_minutes, source, source_timer_id, + created_at, updated_at, version + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1) + RETURNING id` + +// CreateDraft inserts a draft and returns its id. A unique violation on +// (user_id, source_timer_id) means a concurrent or retried stop already +// produced the draft; it is mapped to ErrDuplicateEntry so the caller can +// recover the existing draft. +func (r *TimeWorklogDraftRepository) CreateDraft(in CreateDraftInput) (int, error) { + var id int64 + err := r.db.QueryRow(insertDraftQuery, + in.UserID, in.ProjectID, in.ItemID, in.WorkspaceID, in.Description, in.DateUnix, + in.StartTimeUnix, in.EndTimeUnix, in.DurationMinutes, in.Source, in.SourceTimerID, + in.NowUnix, in.NowUnix, + ).Scan(&id) + if err != nil { + if database.IsUniqueConstraintError(err) { + return 0, ErrDuplicateEntry + } + return 0, err + } + return int(id), nil +} + +// draftJoinedSelect returns the draft plus its linked labels. Joins are LEFT +// because every association is optional. The caller is responsible for +// redacting labels the user may no longer be allowed to see. +const draftJoinedSelect = ` + SELECT + d.id, d.user_id, d.project_id, d.item_id, d.workspace_id, d.description, + d.date, d.start_time, d.end_time, d.duration_minutes, d.source, + d.source_timer_id, d.created_at, d.updated_at, d.version, + COALESCE(tp.name, ''), COALESCE(tc.name, ''), COALESCE(tc.builtin_key, ''), + COALESCE(i.title, ''), COALESCE(ws.key, ''), COALESCE(ws.name, '') + FROM time_worklog_drafts d + LEFT JOIN time_projects tp ON d.project_id = tp.id + LEFT JOIN customer_organisations tc ON tp.customer_id = tc.id + LEFT JOIN items i ON d.item_id = i.id + LEFT JOIN workspaces ws ON d.workspace_id = ws.id` + +func scanDraft(row interface{ Scan(...any) error }) (*models.TimeWorklogDraft, error) { + draft := &models.TimeWorklogDraft{} + var projectName, customerName, customerBuiltin, itemTitle, workspaceKey, workspaceName string + var version int + err := row.Scan( + &draft.ID, &draft.UserID, &draft.ProjectID, &draft.ItemID, &draft.WorkspaceID, &draft.Description, + &draft.Date, &draft.StartTime, &draft.EndTime, &draft.DurationMins, &draft.Source, + &draft.SourceTimerID, &draft.CreatedAt, &draft.UpdatedAt, &version, + &projectName, &customerName, &customerBuiltin, &itemTitle, &workspaceKey, &workspaceName, + ) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + draft.ProjectName = projectName + draft.CustomerName = customerName + draft.CustomerBuiltin = customerBuiltin + draft.ItemTitle = itemTitle + draft.WorkspaceKey = workspaceKey + draft.WorkspaceName = workspaceName + draft.Version = version + return draft, nil +} + +// GetDraft returns one draft owned by userID, joined with its labels. +func (r *TimeWorklogDraftRepository) GetDraft(id, userID int) (*models.TimeWorklogDraft, error) { + return scanDraft(r.db.QueryRow(draftJoinedSelect+` WHERE d.id = ? AND d.user_id = ?`, id, userID)) +} + +// GetDraftBySourceTimer returns the draft a timer produced, if it still exists. +func (r *TimeWorklogDraftRepository) GetDraftBySourceTimer(userID, timerID int) (*models.TimeWorklogDraft, error) { + return scanDraft(r.db.QueryRow(draftJoinedSelect+` WHERE d.user_id = ? AND d.source_timer_id = ?`, userID, timerID)) +} + +// ListDrafts returns all of a user's drafts, newest first. +func (r *TimeWorklogDraftRepository) ListDrafts(userID int) ([]models.TimeWorklogDraft, error) { + rows, err := r.db.Query(draftJoinedSelect+` WHERE d.user_id = ? ORDER BY d.updated_at DESC, d.id DESC`, userID) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + out := []models.TimeWorklogDraft{} + for rows.Next() { + draft, err := scanDraft(rows) + if err != nil { + return nil, err + } + out = append(out, *draft) + } + return out, rows.Err() +} + +// UpdateDraftInput fully replaces the editable fields of a draft. Nil pointers +// clear the corresponding field; the draft stays incomplete until booking. +type UpdateDraftInput struct { + ProjectID *int + ItemID *int + Description string + DateUnix *int64 + StartTimeUnix *int64 + EndTimeUnix *int64 + DurationMinutes *int + NowUnix int64 +} + +// UpdateDraft applies a full replace scoped to the owner and the caller's +// expected version, incrementing the version. It returns ErrConflict when the +// version is stale and ErrNotFound when the draft is missing or owned by +// someone else. +func (r *TimeWorklogDraftRepository) UpdateDraft(id, userID, expectedVersion int, in UpdateDraftInput) error { + result, err := r.db.ExecWrite(` + UPDATE time_worklog_drafts + SET project_id = ?, item_id = ?, description = ?, date = ?, start_time = ?, + end_time = ?, duration_minutes = ?, updated_at = ?, version = version + 1 + WHERE id = ? AND user_id = ? AND version = ?`, + in.ProjectID, in.ItemID, in.Description, in.DateUnix, in.StartTimeUnix, + in.EndTimeUnix, in.DurationMinutes, in.NowUnix, id, userID, expectedVersion) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return r.missingOrStale(id, userID) + } + return nil +} + +// DeleteDraft removes an owned draft. It reports ErrNotFound when the draft is +// missing or owned by someone else. +func (r *TimeWorklogDraftRepository) DeleteDraft(id, userID int) error { + result, err := r.db.ExecWrite(`DELETE FROM time_worklog_drafts WHERE id = ? AND user_id = ?`, id, userID) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return ErrNotFound + } + return nil +} + +// missingOrStale distinguishes a stale-version conflict from a missing/foreign +// draft for an update that matched no row. +func (r *TimeWorklogDraftRepository) missingOrStale(id, userID int) error { + var exists int + err := r.db.QueryRow(`SELECT COUNT(*) FROM time_worklog_drafts WHERE id = ? AND user_id = ?`, id, userID).Scan(&exists) + if err != nil { + return err + } + if exists == 0 { + return ErrNotFound + } + return ErrConflict +} + +// Booking is a recorded idempotent worklog booking. +type Booking struct { + UserID int + IdempotencyKey string + WorklogID int + DraftID *int +} + +// GetBooking returns the booking recorded for a caller-scoped idempotency key, +// or ErrNotFound. +func (r *TimeWorklogDraftRepository) GetBooking(userID int, key string) (*Booking, error) { + booking := &Booking{} + err := r.db.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) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return booking, nil +} + +// 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 + 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 + } + result, err := tx.ExecWrite( + `DELETE FROM time_worklog_drafts WHERE id = ? AND user_id = ? AND version = ?`, + draftID, userID, expectedVersion, + ) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected != 1 { + return ErrConflict + } + if bookingKey != "" { + if _, err := tx.ExecWrite( + `INSERT INTO time_worklog_bookings (user_id, idempotency_key, worklog_id, draft_id, created_at) + VALUES (?, ?, ?, ?, ?)`, + userID, bookingKey, worklogID, draftID, in.NowUnix, + ); err != nil { + if database.IsUniqueConstraintError(err) { + return ErrDuplicateEntry + } + return err + } + } + return nil + }) + if err != nil { + return 0, err + } + return worklogID, nil +} + +// insertBookedWorklogQuery inserts a worklog and returns its id. It is shared by +// the draft-book and timer-stop paths so both produce the same shape. +const insertBookedWorklogQuery = ` + 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` + +// FinalizeTimerBooking atomically books a timer as a worklog, removes the timer, +// and records the idempotency key so a retried stop replays the same worklog +// instead of stopping a newer timer or duplicating booked time. +func (r *ActiveTimerRepository) FinalizeTimerBooking(timerID int, in CreateWorklogInput, bookingKey string) (int, error) { + var worklogID int + 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 + } + result, err := tx.ExecWrite("DELETE FROM active_timers WHERE id = ?", timerID) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected != 1 { + return ErrNotFound + } + if bookingKey != "" { + if _, err := tx.ExecWrite( + `INSERT INTO time_worklog_bookings (user_id, idempotency_key, worklog_id, draft_id, created_at) + VALUES (?, ?, ?, NULL, ?)`, + in.UserID, bookingKey, worklogID, in.NowUnix, + ); err != nil { + if database.IsUniqueConstraintError(err) { + return ErrDuplicateEntry + } + return err + } + } + return nil + }) + if err != nil { + return 0, err + } + return worklogID, nil +} + +// FinalizeTimerDraft atomically records a draft produced by a stopping timer and +// removes the timer. The draft is returned so the caller can open the completion +// modal without a second round trip. +func (r *ActiveTimerRepository) FinalizeTimerDraft(timerID int, in CreateDraftInput) (int, error) { + var draftID int + err := database.WithTx(r.db, func(tx database.Tx) error { + if err := tx.QueryRow(insertDraftQuery, + in.UserID, in.ProjectID, in.ItemID, in.WorkspaceID, in.Description, in.DateUnix, + in.StartTimeUnix, in.EndTimeUnix, in.DurationMinutes, in.Source, in.SourceTimerID, + in.NowUnix, in.NowUnix, + ).Scan(&draftID); err != nil { + if database.IsUniqueConstraintError(err) { + return ErrDuplicateEntry + } + return err + } + result, err := tx.ExecWrite("DELETE FROM active_timers WHERE id = ?", timerID) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected != 1 { + return ErrNotFound + } + return nil + }) + if err != nil { + return 0, err + } + return draftID, nil +} diff --git a/internal/restapi/v1/handlers/timers.go b/internal/restapi/v1/handlers/timers.go index 3c0c2322e..790dd0823 100644 --- a/internal/restapi/v1/handlers/timers.go +++ b/internal/restapi/v1/handlers/timers.go @@ -63,7 +63,7 @@ func (h *ActiveTimerHandler) StartTimer(w http.ResponseWriter, r *http.Request) } sanitize.Apply(&req.Description, sanitize.RichText) - timer, err := h.timer.StartTimer(user.ID, req.WorkspaceID, req.ProjectID, req.ItemID, req.Description) + timer, err := h.timer.StartTimerLegacy(user.ID, req.WorkspaceID, req.ProjectID, req.ItemID, req.Description) if err != nil { writeTimerV1Error(w, r, err) return @@ -139,7 +139,7 @@ func (h *ActiveTimerHandler) StopTimer(w http.ResponseWriter, r *http.Request) { "description": res.Description, "duration_seconds": res.DurationSeconds, "duration_minutes": res.DurationMinutes, - "worklog_created": res.WorklogCreated, + "worklog_created": res.Booked, }) } diff --git a/internal/restapi/v1/router.go b/internal/restapi/v1/router.go index 2ae9a68a1..3cbd2c3d4 100644 --- a/internal/restapi/v1/router.go +++ b/internal/restapi/v1/router.go @@ -119,8 +119,9 @@ func RegisterRoutes(deps restapi.Deps) { timeProjectHandler := handlers.NewTimeProjectHandler(handlers.NewBaseHandler(db, permissionService), timePermService) timeWorklogHandler := handlers.NewTimeWorklogHandler(handlers.NewBaseHandler(db, permissionService), timePermService) timerRepo := repository.NewActiveTimerRepository(db) + draftRepo := repository.NewTimeWorklogDraftRepository(db) itemRepo := repository.NewItemRepository(db) - timerService := services.NewTimerService(timerRepo, itemRepo, timePermService, permissionService) + timerService := services.NewTimerService(timerRepo, draftRepo, itemRepo, services.NewTimeWorklogService(db), timePermService, permissionService) activeTimerHandler := handlers.NewActiveTimerHandler(handlers.NewBaseHandler(db, permissionService), timerRepo, timerService) // Public discovery routes (no bearer auth). Mounted on a sibling group diff --git a/internal/restapi/v2/contract-metadata.json b/internal/restapi/v2/contract-metadata.json index 2a35c4af4..d9e7911e4 100644 --- a/internal/restapi/v2/contract-metadata.json +++ b/internal/restapi/v2/contract-metadata.json @@ -10654,9 +10654,12 @@ "description": "Stop timer. The server validates resource ownership and command preconditions before persisting changes. Unknown JSON fields are rejected when the operation accepts a body.", "parameters": [], "responses": { + "400": {}, "401": {}, "403": {}, "404": {}, + "413": {}, + "415": {}, "429": {}, "500": {} }, @@ -10666,6 +10669,136 @@ ] } }, + "/time/worklog-drafts": { + "get": { + "description": "List draft worklogs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", + "parameters": [], + "responses": { + "401": {}, + "403": {}, + "429": {}, + "500": {} + }, + "summary": "List draft worklogs", + "tags": [ + "Time tracking" + ] + } + }, + "/time/worklog-drafts/{draft_id}": { + "delete": { + "description": "Delete a draft worklog. The server verifies resource ownership and deletion preconditions before removing the resource.", + "parameters": [ + { + "Name": "draft_id", + "In": "path", + "Description": "The draft worklog identifier.", + "Required": true, + "Schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "401": {}, + "403": {}, + "404": {}, + "429": {}, + "500": {} + }, + "summary": "Delete a draft worklog", + "tags": [ + "Time tracking" + ] + }, + "get": { + "description": "Get a draft worklog. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", + "parameters": [ + { + "Name": "draft_id", + "In": "path", + "Description": "The draft worklog identifier.", + "Required": true, + "Schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "401": {}, + "403": {}, + "404": {}, + "429": {}, + "500": {} + }, + "summary": "Get a draft worklog", + "tags": [ + "Time tracking" + ] + }, + "patch": { + "description": "Update a draft worklog. The operation uses JSON Merge Patch: omitted fields remain unchanged and documented nullable fields accept null. Unknown fields are rejected.", + "parameters": [ + { + "Name": "draft_id", + "In": "path", + "Description": "The draft worklog identifier.", + "Required": true, + "Schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "400": {}, + "401": {}, + "403": {}, + "404": {}, + "413": {}, + "415": {}, + "429": {}, + "500": {} + }, + "summary": "Update a draft worklog", + "tags": [ + "Time tracking" + ] + } + }, + "/time/worklog-drafts/{draft_id}/book": { + "post": { + "description": "Book a draft worklog. The server validates resource ownership and command preconditions before persisting changes. Unknown JSON fields are rejected when the operation accepts a body.", + "parameters": [ + { + "Name": "draft_id", + "In": "path", + "Description": "The draft worklog identifier.", + "Required": true, + "Schema": { + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "400": {}, + "401": {}, + "403": {}, + "404": {}, + "413": {}, + "415": {}, + "429": {}, + "500": {} + }, + "summary": "Book a draft worklog", + "tags": [ + "Time tracking" + ] + } + }, "/time/worklogs": { "get": { "description": "List worklogs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.", diff --git a/internal/restapi/v2/router.go b/internal/restapi/v2/router.go index 88e6e3423..00e4762e4 100644 --- a/internal/restapi/v2/router.go +++ b/internal/restapi/v2/router.go @@ -1196,6 +1196,23 @@ func applyParameterCorrections(route *Route) { upsertParameter(route, dateQuery("from", "Includes worklogs on or after this civil date.")) upsertParameter(route, dateQuery("to", "Includes worklogs on or before this civil date.")) upsertParameter(route, stringQuery("timezone", "IANA timezone that from/to are interpreted in; defaults to the caller's profile timezone.")) + case "GET /time/worklog-drafts", + "GET /time/worklog-drafts/{draft_id}", + "PATCH /time/worklog-drafts/{draft_id}", + "DELETE /time/worklog-drafts/{draft_id}", + "POST /time/worklog-drafts/{draft_id}/book": + route.Tag = "Time tracking" + route.Summary = map[string]string{ + "GET /time/worklog-drafts": "List draft worklogs", + "GET /time/worklog-drafts/{draft_id}": "Get a draft worklog", + "PATCH /time/worklog-drafts/{draft_id}": "Update a draft worklog", + "DELETE /time/worklog-drafts/{draft_id}": "Delete a draft worklog", + "POST /time/worklog-drafts/{draft_id}/book": "Book a draft worklog", + }[route.Method+" "+route.Path] + route.Description = semanticRouteDescription(route.Method, route.Summary) + if strings.Contains(route.Path, "{draft_id}") { + upsertParameter(route, ParameterMetadata{Name: "draft_id", In: "path", Required: true, Description: "The draft worklog identifier.", Schema: map[string]any{"type": "integer", "minimum": 1}}) + } case "GET /asset-sets/{asset_set_id}/assets": for _, name := range []string{"type_id", "category_id", "status_id"} { upsertParameter(route, stringQuery(name, "Restricts assets by "+strings.ReplaceAll(name, "_", " ")+".")) diff --git a/internal/restapi/v2/time_drafts.go b/internal/restapi/v2/time_drafts.go new file mode 100644 index 000000000..2df930c6b --- /dev/null +++ b/internal/restapi/v2/time_drafts.go @@ -0,0 +1,186 @@ +package v2 + +import ( + "errors" + "net/http" + + "windshift/internal/models" + "windshift/internal/services" +) + +// draftDTO is the wire shape of a user-owned draft worklog. Absolute unix +// timestamps are exposed alongside the civil fields the completion modal edits. +type draftDTO struct { + ID int `json:"id"` + UserID int `json:"user_id"` + ProjectID *int `json:"project_id"` + ItemID *int `json:"item_id"` + WorkspaceID *int `json:"workspace_id"` + Description string `json:"description"` + Date *int64 `json:"date"` + StartTime *int64 `json:"start_time"` + EndTime *int64 `json:"end_time"` + DurationMinutes *int `json:"duration_minutes"` + Source string `json:"source"` + SourceTimerID *int `json:"source_timer_id"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + Version int `json:"version"` + ProjectName string `json:"project_name"` + CustomerName string `json:"customer_name"` + CustomerBuiltinKey string `json:"customer_builtin_key,omitempty"` + ItemTitle string `json:"item_title"` + WorkspaceKey string `json:"workspace_key"` + WorkspaceName string `json:"workspace_name"` +} + +// draftWriteRequest carries the completion form for a draft. It is used for +// both PATCH (save progress) and book (finalize). version is the optimistic +// concurrency token returned by the draft DTO. +type draftWriteRequest struct { + Version int `json:"version"` + ProjectID *int `json:"project_id"` + ItemID *int `json:"item_id"` + Description string `json:"description"` + Date string `json:"date"` + Duration string `json:"duration"` + DurationMinutes int `json:"duration_minutes"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + Timezone string `json:"timezone"` + IdempotencyKey string `json:"idempotency_key"` +} + +func listDrafts(timers timerApplication) readOperation[[]draftDTO] { + return func(r *http.Request) ([]draftDTO, error) { + user, err := principal(r) + if err != nil { + return nil, err + } + drafts, err := timers.ListDrafts(user.ID) + if err != nil { + return nil, internalError(err) + } + return mapDrafts(drafts), nil + } +} + +func getDraft(timers timerApplication) readOperation[draftDTO] { + return func(r *http.Request) (draftDTO, error) { + user, err := principal(r) + if err != nil { + return draftDTO{}, err + } + id, err := pathID(r, "draft_id") + if err != nil { + return draftDTO{}, err + } + draft, err := timers.GetDraft(user.ID, id) + if err != nil { + return draftDTO{}, draftError(err) + } + return draftFromModel(draft), nil + } +} + +func updateDraft(timers timerApplication) jsonOperation[draftWriteRequest, draftDTO] { + return func(r *http.Request, input draftWriteRequest) (draftDTO, error) { + user, err := principal(r) + if err != nil { + return draftDTO{}, err + } + id, err := pathID(r, "draft_id") + if err != nil { + return draftDTO{}, err + } + draft, err := timers.UpdateDraft(user.ID, id, input.Version, draftMutationInput(input, user.Timezone)) + if err != nil { + return draftDTO{}, draftError(err) + } + return draftFromModel(draft), nil + } +} + +func deleteDraft(timers timerApplication) commandOperation { + return func(r *http.Request) error { + user, err := principal(r) + if err != nil { + return err + } + id, err := pathID(r, "draft_id") + if err != nil { + return err + } + return draftError(timers.DeleteDraft(user.ID, id)) + } +} + +func bookDraft(timers timerApplication) jsonOperation[draftWriteRequest, worklogDTO] { + return func(r *http.Request, input draftWriteRequest) (worklogDTO, error) { + user, err := principal(r) + if err != nil { + return worklogDTO{}, err + } + id, err := pathID(r, "draft_id") + if err != nil { + return worklogDTO{}, err + } + worklog, err := timers.BookDraft(user.ID, id, input.Version, input.IdempotencyKey, draftMutationInput(input, user.Timezone)) + if err != nil { + return worklogDTO{}, draftError(err) + } + return worklogFromModel(worklog, nil), nil + } +} + +func draftMutationInput(input draftWriteRequest, userTimezone string) services.WorklogMutationInput { + projectID := 0 + if input.ProjectID != nil { + projectID = *input.ProjectID + } + return services.WorklogMutationInput{ + ProjectID: projectID, ItemID: input.ItemID, Description: input.Description, + Date: input.Date, Duration: input.Duration, DurationMinutes: input.DurationMinutes, + StartTime: input.StartTime, EndTime: input.EndTime, Timezone: input.Timezone, + UserTimezone: userTimezone, + } +} + +func mapDrafts(drafts []models.TimeWorklogDraft) []draftDTO { + out := make([]draftDTO, len(drafts)) + for i := range drafts { + out[i] = draftFromModel(&drafts[i]) + } + return out +} + +func draftFromModel(draft *models.TimeWorklogDraft) draftDTO { + return draftDTO{ + ID: draft.ID, UserID: draft.UserID, ProjectID: draft.ProjectID, ItemID: draft.ItemID, + WorkspaceID: draft.WorkspaceID, Description: draft.Description, Date: draft.Date, + StartTime: draft.StartTime, EndTime: draft.EndTime, DurationMinutes: draft.DurationMins, + Source: draft.Source, SourceTimerID: draft.SourceTimerID, CreatedAt: draft.CreatedAt, + UpdatedAt: draft.UpdatedAt, Version: draft.Version, ProjectName: draft.ProjectName, + CustomerName: draft.CustomerName, CustomerBuiltinKey: draft.CustomerBuiltin, + ItemTitle: draft.ItemTitle, WorkspaceKey: draft.WorkspaceKey, WorkspaceName: draft.WorkspaceName, + } +} + +func draftError(err error) error { + if err == nil { + return nil + } + switch { + case errors.Is(err, services.ErrTimerDraftNotFound): + return newError(http.StatusNotFound, "not_found", "Draft was not found") + case errors.Is(err, services.ErrTimerDraftConflict): + return newError(http.StatusConflict, "conflict", "Draft was modified; reload and try again") + case errors.Is(err, services.ErrWorklogProjectNotFound): + return newError(http.StatusNotFound, "not_found", "Time project was not found") + case errors.Is(err, services.ErrWorklogProjectInactive), + errors.Is(err, services.ErrWorklogInvalidInput): + return newError(http.StatusBadRequest, "invalid_request", err.Error()) + default: + return internalError(err) + } +} diff --git a/internal/restapi/v2/time_projects.go b/internal/restapi/v2/time_projects.go index d5caecca2..1801de30f 100644 --- a/internal/restapi/v2/time_projects.go +++ b/internal/restapi/v2/time_projects.go @@ -33,7 +33,12 @@ func registerTimeRoutes(builder *routeBuilder, deps Deps) { builder.Command(http.MethodDelete, "/time/projects/{project_id}/members/{assignment_id}", AuthAuthenticated, []string{"time:write"}, removeTimeProjectMember(projects)) builder.JSON(http.MethodPost, "/time/timers", http.StatusCreated, false, AuthAuthenticated, []string{"time:write"}, startTimer(deps.Timers)) builder.Read("/time/timers/active", AuthAuthenticated, []string{"time:read"}, getActiveTimer(deps.Timers)) - builder.Action(http.MethodPost, "/time/timers/active/stop", http.StatusOK, AuthAuthenticated, []string{"time:write"}, stopTimer(deps.Timers)) + builder.JSON(http.MethodPost, "/time/timers/active/stop", http.StatusOK, false, AuthAuthenticated, []string{"time:write"}, stopTimer(deps.Timers)) + builder.Read("/time/worklog-drafts", AuthAuthenticated, []string{"time:read"}, listDrafts(deps.Timers)) + builder.Read("/time/worklog-drafts/{draft_id}", AuthAuthenticated, []string{"time:read"}, getDraft(deps.Timers)) + builder.JSON(http.MethodPatch, "/time/worklog-drafts/{draft_id}", http.StatusOK, true, AuthAuthenticated, []string{"time:write"}, updateDraft(deps.Timers)) + builder.Command(http.MethodDelete, "/time/worklog-drafts/{draft_id}", AuthAuthenticated, []string{"time:write"}, deleteDraft(deps.Timers)) + builder.JSON(http.MethodPost, "/time/worklog-drafts/{draft_id}/book", http.StatusOK, false, AuthAuthenticated, []string{"time:write"}, bookDraft(deps.Timers)) } type timeProjectApplication interface { @@ -58,9 +63,14 @@ type timeProjectApplication interface { } type timerApplication interface { - StartTimer(int, int, int, *int, string) (*models.ActiveTimer, error) + StartTimer(int, int, *int, *int, string) (*models.ActiveTimer, error) GetActiveForUser(int) (*models.ActiveTimer, error) - StopActiveForUser(int) (*services.StopResult, error) + StopActiveTimer(int, *int) (*services.StopResult, error) + ListDrafts(int) ([]models.TimeWorklogDraft, error) + GetDraft(int, int) (*models.TimeWorklogDraft, error) + UpdateDraft(int, int, int, services.WorklogMutationInput) (*models.TimeWorklogDraft, error) + DeleteDraft(int, int) error + BookDraft(int, int, int, string, services.WorklogMutationInput) (*models.Worklog, error) } type timeProjectDTO struct { @@ -164,7 +174,7 @@ type timePrincipalRequest struct { type startTimerRequest struct { WorkspaceID int `json:"workspace_id"` - ProjectID int `json:"project_id"` + ProjectID *int `json:"project_id"` ItemID *int `json:"item_id"` Description string `json:"description"` } @@ -175,7 +185,9 @@ type stoppedTimerDTO struct { Description string `json:"description"` DurationSeconds int64 `json:"duration_seconds"` DurationMinutes int `json:"duration_minutes"` - WorklogCreated bool `json:"worklog_created"` + Booked bool `json:"booked"` + WorklogID *int `json:"worklog_id"` + DraftID *int `json:"draft_id"` } func listTimeProjects(projects timeProjectApplication) readOperation[[]timeProjectDTO] { @@ -514,24 +526,28 @@ func getActiveTimer(timers timerApplication) readOperation[*models.ActiveTimer] } } -func stopTimer(timers timerApplication) actionOperation[stoppedTimerDTO] { - return func(r *http.Request) (stoppedTimerDTO, error) { +func stopTimer(timers timerApplication) jsonOperation[stopTimerRequest, stoppedTimerDTO] { + return func(r *http.Request, input stopTimerRequest) (stoppedTimerDTO, error) { user, err := principal(r) if err != nil { return stoppedTimerDTO{}, err } - result, err := timers.StopActiveForUser(user.ID) + result, err := timers.StopActiveTimer(user.ID, input.TimerID) if err != nil { return stoppedTimerDTO{}, timerError(err) } return stoppedTimerDTO{ Stopped: true, TimerID: result.TimerID, Description: result.Description, DurationSeconds: result.DurationSeconds, DurationMinutes: result.DurationMinutes, - WorklogCreated: result.WorklogCreated, + Booked: result.Booked, WorklogID: result.WorklogID, DraftID: result.DraftID, }, nil } } +type stopTimerRequest struct { + TimerID *int `json:"timer_id"` +} + func timeProjectFromRepository(project repository.TimeProjectDetail) timeProjectDTO { return timeProjectDTO{ ID: project.ID, CustomerID: project.CustomerID, CategoryID: project.CategoryID, diff --git a/internal/server/server.go b/internal/server/server.go index ed41d300b..8b9244194 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -770,7 +770,8 @@ func (s *Server) initialize() error { timeProjectHandler := handlers.NewTimeProjectHandler(s.db, timePermissionService, customerOrgPermissionService) timeWorklogService := services.NewTimeWorklogService(s.db) activeTimerRepo := repository.NewActiveTimerRepository(s.db) - timerService := services.NewTimerService(activeTimerRepo, repository.NewItemRepository(s.db), timePermissionService, permService) + draftRepo := repository.NewTimeWorklogDraftRepository(s.db) + timerService := services.NewTimerService(activeTimerRepo, draftRepo, repository.NewItemRepository(s.db), timeWorklogService, timePermissionService, permService) customerOrgPermissionHandler := handlers.NewCustomerOrganisationPermissionHandler(logger.NewAuditor(s.db), customerOrgPermissionService) itemLinkService := services.NewItemLinkService(s.db). diff --git a/internal/services/time_worklog_service.go b/internal/services/time_worklog_service.go index 281e3eaf2..7fa6aeea3 100644 --- a/internal/services/time_worklog_service.go +++ b/internal/services/time_worklog_service.go @@ -300,16 +300,65 @@ type preparedWorklog struct { warnings []string } -func (s *TimeWorklogService) prepare(userID int, input WorklogMutationInput) (preparedWorklog, error) { - project, err := s.projects.GetBookingInfo(input.ProjectID) - if errors.Is(err, repository.ErrNotFound) { - return preparedWorklog{}, ErrWorklogProjectNotFound - } +// PreparedWorklog is the normalized interval produced by worklog validation, +// before persistence. It is exposed so the draft-book path reuses the exact +// same validation and civil-time parsing as a direct worklog create. +type PreparedWorklog struct { + Description string + DateUnix int64 + StartUnix int64 + EndUnix int64 + DurationMinutes int + Timezone string + Location *time.Location + Warnings []string +} + +// Prepare validates a complete worklog mutation and returns its normalized +// interval. It requires an active, bookable project. +func (s *TimeWorklogService) Prepare(userID int, input WorklogMutationInput) (*PreparedWorklog, error) { + return s.prepareExported(userID, input, true) +} + +// PrepareDraft validates a draft mutation. Project may be absent, and an +// inactive project does not block saving an incomplete entry. +func (s *TimeWorklogService) PrepareDraft(userID int, input WorklogMutationInput) (*PreparedWorklog, error) { + return s.prepareExported(userID, input, false) +} + +func (s *TimeWorklogService) prepareExported(userID int, input WorklogMutationInput, requireProject bool) (*PreparedWorklog, error) { + prepared, err := s.prepareWithProject(userID, input, requireProject) if err != nil { - return preparedWorklog{}, err + return nil, err } - if project.Status != "Active" { - return preparedWorklog{}, fmt.Errorf("%w: %s", ErrWorklogProjectInactive, project.Status) + return &PreparedWorklog{ + Description: prepared.description, + DateUnix: WorklogDateUnix(prepared.date), + StartUnix: prepared.startUnix, + EndUnix: prepared.endUnix, + DurationMinutes: prepared.durationMinutes, + Timezone: prepared.timezone, + Location: prepared.location, + Warnings: prepared.warnings, + }, nil +} + +func (s *TimeWorklogService) prepare(userID int, input WorklogMutationInput) (preparedWorklog, error) { + return s.prepareWithProject(userID, input, true) +} + +func (s *TimeWorklogService) prepareWithProject(userID int, input WorklogMutationInput, requireProject bool) (preparedWorklog, error) { + if requireProject { + project, err := s.projects.GetBookingInfo(input.ProjectID) + if errors.Is(err, repository.ErrNotFound) { + return preparedWorklog{}, ErrWorklogProjectNotFound + } + if err != nil { + return preparedWorklog{}, err + } + if project.Status != "Active" { + return preparedWorklog{}, fmt.Errorf("%w: %s", ErrWorklogProjectInactive, project.Status) + } } timezone := input.Timezone @@ -317,10 +366,11 @@ func (s *TimeWorklogService) prepare(userID int, input WorklogMutationInput) (pr timezone = input.UserTimezone } if timezone == "" { - timezone, err = LookupUserTimezone(s.db, userID) + resolved, err := LookupUserTimezone(s.db, userID) if err != nil { return preparedWorklog{}, err } + timezone = resolved } resolvedTimezone, location, err := ResolveTimezone(timezone) if err != nil { diff --git a/internal/services/timer_service.go b/internal/services/timer_service.go index 9a74c37eb..a065e7192 100644 --- a/internal/services/timer_service.go +++ b/internal/services/timer_service.go @@ -11,12 +11,17 @@ import ( ) // TimerService owns the start/stop lifecycle for active timers. Both the -// REST handler (handlers/active_timers.go) and the AI tools -// (aitools/time.go) go through this service so that workspace/item access -// validation and worklog creation live in exactly one place. +// REST handlers and the AI tools go through this service so that workspace/item +// access validation and worklog creation live in exactly one place. +// +// A timer may run without a project. On stop the service decides whether the +// entry can be booked directly (active, bookable project plus a description) or +// must be persisted as a recoverable draft worklog. type TimerService struct { repo *repository.ActiveTimerRepository + draftRepo *repository.TimeWorklogDraftRepository itemRepo *repository.ItemRepository + worklogs *TimeWorklogService timePerm *TimePermissionService permService *PermissionService // workspaceAccess is kept as a function so every timer response uses the @@ -28,13 +33,17 @@ type TimerService struct { // of the start/stop invariants. func NewTimerService( repo *repository.ActiveTimerRepository, + draftRepo *repository.TimeWorklogDraftRepository, itemRepo *repository.ItemRepository, + worklogs *TimeWorklogService, timePerm *TimePermissionService, permService *PermissionService, ) *TimerService { service := &TimerService{ repo: repo, + draftRepo: draftRepo, itemRepo: itemRepo, + worklogs: worklogs, timePerm: timePerm, permService: permService, } @@ -54,64 +63,58 @@ var ( ErrTimerForbidden = errors.New("timer: forbidden") ErrTimerProjectInactive = errors.New("timer: project not active") ErrTimerAlreadyRunning = errors.New("timer: a timer is already running") + ErrTimerDraftNotFound = errors.New("timer: draft not found") + ErrTimerDraftConflict = errors.New("timer: draft conflict") ) // StopResult is the data returned to callers when an active timer is stopped. +// Exactly one of Booked/WorklogID or DraftID is set: a stop either books a +// worklog directly or produces a recoverable draft. type StopResult struct { TimerID int WorkspaceID int - ProjectID int + ProjectID *int Description string StartTimeUTC int64 EndTimeUTC int64 DurationSeconds int64 DurationMinutes int - WorklogCreated bool + Booked bool + WorklogID *int + DraftID *int ProjectName string ItemTitle string WorkspaceName string } -// StartTimer creates a new active timer for userID after validating all -// access invariants. +// StartTimer creates a new active timer for userID after validating all access +// invariants. Project is optional; description may be empty. // // Order matters: a 404-style result (ErrTimerNotFound) is returned for // workspace/item permission failures so callers can't probe existence by // observing 403 vs 404 (see MEMORY.md, "Security Policy"). func (s *TimerService) StartTimer( - userID, workspaceID, projectID int, + userID, workspaceID int, + projectID *int, itemID *int, description string, ) (*models.ActiveTimer, error) { sanitize.Apply(&description, sanitize.RichText) - if description == "" { - return nil, fmt.Errorf("%w: description is required", ErrTimerValidation) + + // A contextual item can supply the workspace when the caller did not. + if workspaceID <= 0 && itemID != nil && *itemID > 0 { + wsID, err := s.itemRepo.GetWorkspaceID(*itemID) + if errors.Is(err, repository.ErrNotFound) { + return nil, fmt.Errorf("%w: item", ErrTimerNotFound) + } + if err != nil { + return nil, err + } + workspaceID = wsID } if workspaceID <= 0 { return nil, fmt.Errorf("%w: workspace_id is required", ErrTimerValidation) } - if projectID <= 0 { - return nil, fmt.Errorf("%w: project_id is required", ErrTimerValidation) - } - - canBook, err := s.timePerm.CanBookTimeOnProject(userID, projectID) - if err != nil { - return nil, err - } - if !canBook { - return nil, ErrTimerForbidden - } - - projectStatus, err := s.repo.GetProjectStatus(projectID) - if errors.Is(err, repository.ErrNotFound) { - return nil, fmt.Errorf("%w: project", ErrTimerNotFound) - } - if err != nil { - return nil, err - } - if projectStatus != "Active" { - return nil, ErrTimerProjectInactive - } // Workspace access: 404 (not 403) on failure per project policy. canViewWS, err := s.permService.HasWorkspacePermission(userID, workspaceID, models.PermissionItemView) @@ -122,10 +125,8 @@ func (s *TimerService) StartTimer( return nil, fmt.Errorf("%w: workspace", ErrTimerNotFound) } - // Item access: must exist, must belong to the supplied workspace, - // and the user must be able to view it (workspace check above - // already covers the workspace, but we re-check defensively in - // case items table moves to its own permission scope later). + // Item access: must exist, belong to the supplied workspace, and be + // viewable. Re-checked defensively in case items gain their own scope. if itemID != nil && *itemID > 0 { wsID, err := s.itemRepo.GetWorkspaceID(*itemID) if errors.Is(err, repository.ErrNotFound) { @@ -146,6 +147,30 @@ func (s *TimerService) StartTimer( } } + // Optional project: when supplied it must be active and bookable. A + // projectless timer is allowed and stops into a draft. + if projectID != nil && *projectID > 0 { + canBook, err := s.timePerm.CanBookTimeOnProject(userID, *projectID) + if err != nil { + return nil, err + } + if !canBook { + return nil, ErrTimerForbidden + } + projectStatus, err := s.repo.GetProjectStatus(*projectID) + if errors.Is(err, repository.ErrNotFound) { + return nil, fmt.Errorf("%w: project", ErrTimerNotFound) + } + if err != nil { + return nil, err + } + if projectStatus != "Active" { + return nil, ErrTimerProjectInactive + } + } else { + projectID = nil + } + // Fast-path pre-check; the UNIQUE(user_id) index on active_timers is the // authoritative backstop for the race two concurrent starts would otherwise // win (the duplicate-entry mapping below). @@ -182,6 +207,18 @@ func (s *TimerService) StartTimer( return timer, nil } +// StartTimerLegacy preserves the v1 contract: a project and a description are +// required. v1 is frozen and must not gain the projectless start behavior. +func (s *TimerService) StartTimerLegacy(userID, workspaceID, projectID int, itemID *int, description string) (*models.ActiveTimer, error) { + if projectID <= 0 { + return nil, fmt.Errorf("%w: project_id is required", ErrTimerValidation) + } + if description == "" { + return nil, fmt.Errorf("%w: description is required", ErrTimerValidation) + } + return s.StartTimer(userID, workspaceID, &projectID, itemID, description) +} + // GetActiveForUser returns the user's active timer with item/workspace // metadata removed when access has been revoked since the timer started. func (s *TimerService) GetActiveForUser(userID int) (*models.ActiveTimer, error) { @@ -195,8 +232,9 @@ func (s *TimerService) GetActiveForUser(userID int) (*models.ActiveTimer, error) return timer, nil } -// StopActiveForUser stops whichever timer the user currently has running. -// The AI tool (stop_timer) calls this — it does not pass a timer ID. +// StopActiveForUser stops whichever timer the user currently has running using +// the legacy (v1) contract: the timer must be complete or the stop is rejected +// and the timer retained. New callers use StopActiveTimer. func (s *TimerService) StopActiveForUser(userID int) (*StopResult, error) { timer, err := s.repo.GetTimerForUser(userID) if errors.Is(err, repository.ErrNotFound) { @@ -205,22 +243,26 @@ func (s *TimerService) StopActiveForUser(userID int) (*StopResult, error) { if err != nil { return nil, err } - return s.StopTimerByID(userID, timer.ID) + return s.stopTimer(userID, timer, false) } -// StopTimerByID stops the specified timer after verifying ownership. -// The REST handler calls this — it parses the ID from the URL. -// -// If the timer carries an item link that the caller can no longer view -// (the workspace was revoked between start and stop), the worklog is -// still recorded against the project but the item link is dropped. This -// is defense-in-depth for finding 2 in bughunt8: pre-existing rows from -// before StartTimer's validation tightening could otherwise be flushed -// into worklogs with a forged item association. -func (s *TimerService) StopTimerByID(userID, timerID int) (*StopResult, error) { - timer, err := s.repo.GetTimerByID(timerID) - if errors.Is(err, repository.ErrNotFound) { - return nil, ErrTimerNotFound +// StopActiveTimer stops the intended timer and books or drafts it. When timerID +// is nil the user's active timer is used. A retry for a timer that was already +// stopped recovers the original result (booked worklog or draft) instead of +// stopping a newer timer. +func (s *TimerService) StopActiveTimer(userID int, timerID *int) (*StopResult, error) { + var timer *models.ActiveTimer + var err error + if timerID != nil && *timerID > 0 { + timer, err = s.repo.GetTimerByID(*timerID) + if errors.Is(err, repository.ErrNotFound) { + return s.recoverStoppedTimer(userID, *timerID) + } + } else { + timer, err = s.repo.GetTimerForUser(userID) + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerNotFound + } } if err != nil { return nil, err @@ -228,7 +270,31 @@ func (s *TimerService) StopTimerByID(userID, timerID int) (*StopResult, error) { if timer.UserID != userID { return nil, ErrTimerForbidden } + return s.stopTimer(userID, timer, true) +} + +// recoverStoppedTimer resolves a retried stop for a timer that is already gone. +// It returns the booked worklog or the draft produced by the original stop. +func (s *TimerService) recoverStoppedTimer(userID, timerID int) (*StopResult, error) { + key := timerBookingKey(timerID) + if booking, err := s.draftRepo.GetBooking(userID, key); err == nil { + worklogID := booking.WorklogID + return &StopResult{TimerID: timerID, Booked: true, WorklogID: &worklogID}, nil + } else if !errors.Is(err, repository.ErrNotFound) { + return nil, err + } + if draft, err := s.draftRepo.GetDraftBySourceTimer(userID, timerID); err == nil { + draftID := draft.ID + return &StopResult{TimerID: timerID, Booked: false, DraftID: &draftID}, nil + } else if !errors.Is(err, repository.ErrNotFound) { + return nil, err + } + return nil, ErrTimerNotFound +} +// stopTimer performs the shared stop work. When allowDraft is false (legacy v1) +// an incomplete timer is rejected and retained. +func (s *TimerService) stopTimer(userID int, timer *models.ActiveTimer, allowDraft bool) (*StopResult, error) { metadataVisible := s.canViewTimerMetadata(userID, timer) // Drop the item link if access has since been revoked or the item no @@ -270,24 +336,99 @@ func (s *TimerService) StopTimerByID(userID, timerID int) (*StopResult, error) { dateInt := int(WorklogDateUnix(startTime)) nowUnix := time.Now().UTC().Unix() - if err := s.repo.FinalizeTimer(timer.ID, repository.CreateWorklogInput{ - ProjectID: timer.ProjectID, + bookableProject := s.bookableProject(userID, timer) + if bookableProject != nil && timer.Description != "" { + worklogID, err := s.repo.FinalizeTimerBooking(timer.ID, repository.CreateWorklogInput{ + ProjectID: *bookableProject, + UserID: userID, + ItemID: itemID, + Description: timer.Description, + DateUnix: dateInt, + StartTimeUnix: int(timer.StartTimeUTC), + EndTimeUnix: int(endTimeUTC), + DurationMinutes: durationMinutes, + NowUnix: nowUnix, + }, timerBookingKey(timer.ID)) + if errors.Is(err, repository.ErrDuplicateEntry) { + // A concurrent or retried stop already booked this timer. + booking, lookupErr := s.draftRepo.GetBooking(userID, timerBookingKey(timer.ID)) + if lookupErr != nil { + return nil, lookupErr + } + bookedID := booking.WorklogID + return buildStopResult(timer, endTimeUTC, durationSeconds, durationMinutes, true, &bookedID, nil, metadataVisible), nil + } + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerNotFound + } + if err != nil { + return nil, err + } + return buildStopResult(timer, endTimeUTC, durationSeconds, durationMinutes, true, &worklogID, nil, metadataVisible), nil + } + + if !allowDraft { + return nil, fmt.Errorf("%w: the timer is missing booking information", ErrTimerValidation) + } + + // Incomplete: persist a recoverable draft. Keep the project when it still + // exists so the completion modal can offer it, but never invent a link. + draftProject := timer.ProjectID + if draftProject != nil { + if _, err := s.repo.GetProjectStatus(*draftProject); errors.Is(err, repository.ErrNotFound) { + draftProject = nil + } + } + var draftWorkspace *int + if metadataVisible { + ws := timer.WorkspaceID + draftWorkspace = &ws + } + draftID, err := s.repo.FinalizeTimerDraft(timer.ID, repository.CreateDraftInput{ UserID: userID, + ProjectID: draftProject, ItemID: itemID, + WorkspaceID: draftWorkspace, Description: timer.Description, - DateUnix: dateInt, - StartTimeUnix: int(timer.StartTimeUTC), - EndTimeUnix: int(endTimeUTC), - DurationMinutes: durationMinutes, + DateUnix: int64Ptr(int64(dateInt)), + StartTimeUnix: int64Ptr(timer.StartTimeUTC), + EndTimeUnix: int64Ptr(endTimeUTC), + DurationMinutes: intPtr(durationMinutes), + Source: "timer", + SourceTimerID: intPtr(timer.ID), NowUnix: nowUnix, - }); err != nil { - if errors.Is(err, repository.ErrNotFound) { - return nil, ErrTimerNotFound + }) + if errors.Is(err, repository.ErrDuplicateEntry) { + draft, lookupErr := s.draftRepo.GetDraftBySourceTimer(userID, timer.ID) + if lookupErr != nil { + return nil, lookupErr } + return buildStopResult(timer, endTimeUTC, durationSeconds, durationMinutes, false, nil, &draft.ID, metadataVisible), nil + } + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerNotFound + } + if err != nil { return nil, err } + return buildStopResult(timer, endTimeUTC, durationSeconds, durationMinutes, false, nil, &draftID, metadataVisible), nil +} - return buildStopResult(timer, endTimeUTC, durationSeconds, durationMinutes, true, metadataVisible), nil +// bookableProject returns the timer's project only when it still exists, is +// active, and the user may book time on it. +func (s *TimerService) bookableProject(userID int, timer *models.ActiveTimer) *int { + if timer.ProjectID == nil || *timer.ProjectID <= 0 { + return nil + } + status, err := s.repo.GetProjectStatus(*timer.ProjectID) + if err != nil || status != "Active" { + return nil + } + canBook, err := s.timePerm.CanBookTimeOnProject(userID, *timer.ProjectID) + if err != nil || !canBook { + return nil + } + return timer.ProjectID } func (s *TimerService) canViewTimerWorkspace(userID, workspaceID int) bool { @@ -321,11 +462,17 @@ func redactActiveTimerMetadata(timer *models.ActiveTimer) { timer.WorkspaceItemNumber = nil } +func timerBookingKey(timerID int) string { + return fmt.Sprintf("timer:%d", timerID) +} + func buildStopResult( timer *models.ActiveTimer, endTimeUTC, durationSeconds int64, durationMinutes int, - worklogCreated, metadataVisible bool, + booked bool, + worklogID, draftID *int, + metadataVisible bool, ) *StopResult { res := &StopResult{ TimerID: timer.ID, @@ -335,7 +482,9 @@ func buildStopResult( EndTimeUTC: endTimeUTC, DurationSeconds: durationSeconds, DurationMinutes: durationMinutes, - WorklogCreated: worklogCreated, + Booked: booked, + WorklogID: worklogID, + DraftID: draftID, } if metadataVisible { res.WorkspaceID = timer.WorkspaceID @@ -351,3 +500,145 @@ func buildStopResult( } return res } + +func int64Ptr(v int64) *int64 { return &v } + +// --- Draft worklog operations ------------------------------------------- +// +// Drafts are user-owned incomplete entries. Every lookup and mutation is +// scoped by the authenticated user id, so another user's draft is +// indistinguishable from a missing one. + +// ListDrafts returns the caller's incomplete entries. +func (s *TimerService) ListDrafts(userID int) ([]models.TimeWorklogDraft, error) { + return s.draftRepo.ListDrafts(userID) +} + +// GetDraft returns one draft owned by the caller. +func (s *TimerService) GetDraft(userID, id int) (*models.TimeWorklogDraft, error) { + draft, err := s.draftRepo.GetDraft(id, userID) + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound + } + return draft, err +} + +// UpdateDraft saves an incomplete entry, applying the same civil-time parsing +// as a worklog create but without requiring an active project. +func (s *TimerService) UpdateDraft(userID, id, expectedVersion int, input WorklogMutationInput) (*models.TimeWorklogDraft, error) { + if _, err := s.draftRepo.GetDraft(id, userID); err != nil { + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound + } + return nil, err + } + prepared, err := s.worklogs.PrepareDraft(userID, input) + if err != nil { + return nil, err + } + var projectID *int + if input.ProjectID > 0 { + projectID = &input.ProjectID + } + if err := s.draftRepo.UpdateDraft(id, userID, expectedVersion, repository.UpdateDraftInput{ + ProjectID: projectID, + ItemID: s.visibleDraftItem(userID, input.ItemID), + Description: prepared.Description, + DateUnix: &prepared.DateUnix, + StartTimeUnix: &prepared.StartUnix, + EndTimeUnix: &prepared.EndUnix, + DurationMinutes: &prepared.DurationMinutes, + NowUnix: time.Now().UTC().Unix(), + }); err != nil { + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound + } + if errors.Is(err, repository.ErrConflict) { + return nil, ErrTimerDraftConflict + } + return nil, err + } + return s.GetDraft(userID, id) +} + +// DeleteDraft discards an owned draft. +func (s *TimerService) DeleteDraft(userID, id int) error { + err := s.draftRepo.DeleteDraft(id, userID) + if errors.Is(err, repository.ErrNotFound) { + return ErrTimerDraftNotFound + } + return err +} + +// BookDraft completes a draft into a booked worklog. It revalidates the +// project and item, consumes exactly one owned draft atomically, and records +// the idempotency key so a retry replays the same worklog. +func (s *TimerService) BookDraft(userID, id, expectedVersion int, idempotencyKey string, input WorklogMutationInput) (*models.Worklog, error) { + if _, err := s.draftRepo.GetDraft(id, userID); err != nil { + if errors.Is(err, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound + } + return nil, err + } + 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): + return nil, err + } + } + prepared, err := s.worklogs.Prepare(userID, input) + if err != nil { + return nil, err + } + worklogID, err := s.draftRepo.BookDraft(id, userID, expectedVersion, repository.CreateWorklogInput{ + ProjectID: input.ProjectID, + UserID: userID, + ItemID: s.visibleDraftItem(userID, input.ItemID), + Description: prepared.Description, + DateUnix: int(prepared.DateUnix), + StartTimeUnix: int(prepared.StartUnix), + EndTimeUnix: int(prepared.EndUnix), + 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.ErrConflict) { + if _, gerr := s.draftRepo.GetDraft(id, userID); errors.Is(gerr, repository.ErrNotFound) { + return nil, ErrTimerDraftNotFound + } + return nil, ErrTimerDraftConflict + } + if err != nil { + return nil, err + } + return s.worklogs.Get(worklogID) +} + +// visibleDraftItem drops an item link the caller can no longer view, mirroring +// the timer-stop redaction policy. +func (s *TimerService) visibleDraftItem(userID int, itemID *int) *int { + if itemID == nil || *itemID <= 0 { + return nil + } + wsID, err := s.itemRepo.GetWorkspaceID(*itemID) + if err != nil { + return nil + } + canView, err := s.permService.HasWorkspacePermission(userID, wsID, models.PermissionItemView) + if err != nil || !canView { + return nil + } + return itemID +} From 6568b512a11a5d0c926b966b882052cc6a583b72 Mon Sep 17 00:00:00 2001 From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:34:19 +0100 Subject: [PATCH 2/6] feat(time): global time-log host, sidebar timer menu, and draft recovery (GitHub #496) Move time logging onto one global surface available from every route and shell, and wire the new book-or-draft timer lifecycle through the UI. - timeLogStore + TimeLogHost mounted once in MainAppOverlays and MobileShell - command palette, item detail, /time, mobile, and hotkeys open the modal in place; dead focus-time-entry-form/item-detail-show-time-entry events removed - Time & Projects sidebar entry becomes a dropdown with a start/stop timer, project search, drafts badge, and navigation group - timer stop books silently when complete and opens the prefilled modal when it produces a draft; FloatingTimer, palette, and mobile share one helper - drafts card on the desktop Time view and mobile timer view; TimeLogModal gains a draft/complete mode with discard --- frontend/src/lib/api/time.js | 22 ++- .../lib/commands/providers/timeProvider.js | 10 +- frontend/src/lib/dialogs/TimeLogModal.svelte | 43 +++-- .../src/lib/features/items/ItemDetail.svelte | 85 ++++------ .../lib/features/time/FloatingTimer.svelte | 4 +- .../lib/features/time/TimeDraftsCard.svelte | 72 ++++++++ .../src/lib/features/time/TimeEntry.svelte | 55 +++--- .../src/lib/features/time/TimeLogHost.svelte | 63 +++++++ .../lib/features/time/stopTimerAndReview.js | 19 +++ frontend/src/lib/layout/MainSidebar.svelte | 25 ++- frontend/src/lib/layout/TimeNavMenu.svelte | 156 +++++++++++++++++ frontend/src/lib/locales/de/time.js | 12 ++ frontend/src/lib/locales/en/time.js | 12 ++ frontend/src/lib/locales/fa/time.js | 12 ++ frontend/src/lib/locales/fr/time.js | 12 ++ frontend/src/lib/locales/pl/time.js | 12 ++ frontend/src/lib/locales/ru/time.js | 12 ++ frontend/src/lib/locales/zh-CN/time.js | 12 ++ frontend/src/lib/mobile/MobileShell.svelte | 5 + frontend/src/lib/mobile/TimerView.svelte | 28 ++-- frontend/src/lib/pages/MainAppOverlays.svelte | 2 + .../src/lib/stores/timeLogStore.svelte.js | 158 ++++++++++++++++++ 22 files changed, 694 insertions(+), 137 deletions(-) create mode 100644 frontend/src/lib/features/time/TimeDraftsCard.svelte create mode 100644 frontend/src/lib/features/time/TimeLogHost.svelte create mode 100644 frontend/src/lib/features/time/stopTimerAndReview.js create mode 100644 frontend/src/lib/layout/TimeNavMenu.svelte create mode 100644 frontend/src/lib/stores/timeLogStore.svelte.js diff --git a/frontend/src/lib/api/time.js b/frontend/src/lib/api/time.js index 057073d9a..82e114c44 100644 --- a/frontend/src/lib/api/time.js +++ b/frontend/src/lib/api/time.js @@ -90,6 +90,25 @@ export const time = { getByItem: (itemId, requestOptions = {}) => fetchAllV2Pages(`/items/${itemId}/worklogs`, requestOptions), }, + + // Draft worklogs: incomplete, user-owned entries produced when a timer stops + // without booking information. Booked entries leave this list. + worklogDrafts: { + getAll: (requestOptions = {}) => fetchV2Data('/time/worklog-drafts', requestOptions), + get: (id, requestOptions = {}) => fetchV2Data(`/time/worklog-drafts/${id}`, requestOptions), + update: (id, data) => + fetchV2Data(`/time/worklog-drafts/${id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/merge-patch+json' }, + body: JSON.stringify(data), + }), + book: (id, data) => + fetchV2Data(`/time/worklog-drafts/${id}/book`, { + method: 'POST', + body: JSON.stringify(data), + }), + delete: (id) => fetchV2Data(`/time/worklog-drafts/${id}`, { method: 'DELETE' }), + }, }; export const timer = { @@ -99,8 +118,9 @@ export const timer = { body: JSON.stringify(data), }), getActive: () => fetchV2Data('/time/timers/active'), - stop: () => + stop: (timerId = null) => fetchV2Data('/time/timers/active/stop', { method: 'POST', + body: JSON.stringify(timerId ? { timer_id: timerId } : {}), }), }; diff --git a/frontend/src/lib/commands/providers/timeProvider.js b/frontend/src/lib/commands/providers/timeProvider.js index 91bd28693..c81206a94 100644 --- a/frontend/src/lib/commands/providers/timeProvider.js +++ b/frontend/src/lib/commands/providers/timeProvider.js @@ -1,4 +1,5 @@ -import { navigate } from '../../router.js'; +import { stopTimerAndReview } from '../../features/time/stopTimerAndReview.js'; +import { timeLogStore } from '../../stores/timeLogStore.svelte.js'; import { timerStore } from '../../stores/timerStore.svelte.js'; import { errorToast, infoToast, warningToast } from '../../stores/toasts.svelte.js'; import { BUCKET } from '../buckets.js'; @@ -40,10 +41,7 @@ export function timeProvider(ctx) { bucket: BUCKET.MODULE_ACTIONS, keywords: ['log', 'time', 'entry', 'hours', 'work', 'track', 'add'], execute: () => { - navigate('/time'); - setTimeout(() => { - window.dispatchEvent(new CustomEvent('focus-time-entry-form')); - }, 100); + timeLogStore.open(); }, }), ]; @@ -76,7 +74,7 @@ export function timeProvider(ctx) { execute: async () => { if (timerStore.canStop) { try { - await timerStore.stop(); + await stopTimerAndReview(timerStore, timeLogStore); } catch (err) { errorToast(t('dialogs.alerts.stopTimerFailed', { error: err.message })); } diff --git a/frontend/src/lib/dialogs/TimeLogModal.svelte b/frontend/src/lib/dialogs/TimeLogModal.svelte index 9a4821499..844c5dc6e 100644 --- a/frontend/src/lib/dialogs/TimeLogModal.svelte +++ b/frontend/src/lib/dialogs/TimeLogModal.svelte @@ -35,8 +35,10 @@ workItems = [], workspaces = [], editingWorklog = null, + draft = null, onsave = () => {}, - oncancel = () => {} + oncancel = () => {}, + ondiscard = null } = $props(); // One explicit timezone populates and interprets every form control, so @@ -55,18 +57,22 @@ } const durationSync = createDurationSync(); // Guarded updates to avoid recursive time sync + // Worklogs and drafts share the same field names (absolute unix timestamps + // plus duration_minutes), so one source record drives the editable form. + const sourceRecord = editingWorklog ?? draft ?? null; + const isDraft = $derived(!!draft && !editingWorklog); // Snapshot props for the editable form; updates are then user-driven, not prop-driven. // svelte-ignore state_referenced_locally let formData = $state({ - project_id: editingWorklog?.project_id ?? defaultProjectId, - item_id: editingWorklog?.item_id ?? defaultItemId, - description: editingWorklog?.description ?? '', - date: editingWorklog - ? dateKeyInZone(editingWorklog.start_time, formTimezone) + project_id: sourceRecord?.project_id ?? defaultProjectId, + item_id: sourceRecord?.item_id ?? defaultItemId, + description: sourceRecord?.description ?? '', + date: sourceRecord + ? dateKeyInZone(sourceRecord.date ?? sourceRecord.start_time, formTimezone) : (defaultDate ?? dateKeyInZone(Date.now() / 1000, formTimezone)), - start_time: editingWorklog ? formatClockInZone(editingWorklog.start_time, formTimezone) : (defaultStartTime ?? ''), - end_time: editingWorklog ? formatClockInZone(editingWorklog.end_time, formTimezone) : '', - duration: editingWorklog ? formatDurationFromMinutes(editingWorklog.duration_minutes) : '' + start_time: sourceRecord?.start_time != null ? formatClockInZone(sourceRecord.start_time, formTimezone) : (defaultStartTime ?? ''), + end_time: sourceRecord?.end_time != null ? formatClockInZone(sourceRecord.end_time, formTimezone) : '', + duration: sourceRecord?.duration_minutes != null ? formatDurationFromMinutes(sourceRecord.duration_minutes) : '' }); // Time fields the form was opened with; an edit that leaves them untouched @@ -244,7 +250,7 @@ > {#snippet children(submitHint)} - +
@@ -394,10 +400,23 @@ + > + {#snippet extra()} + {#if isDraft && ondiscard} + + {/if} + {/snippet} + {/snippet} diff --git a/frontend/src/lib/features/items/ItemDetail.svelte b/frontend/src/lib/features/items/ItemDetail.svelte index eb4c3d16d..629a71aa4 100644 --- a/frontend/src/lib/features/items/ItemDetail.svelte +++ b/frontend/src/lib/features/items/ItemDetail.svelte @@ -17,6 +17,7 @@ import { publicBaseURL } from '../../runtime/contextPath.js'; import { workspacePermissions } from '../../stores/workspacePermissions.svelte.js'; import { itemDetailStore } from '../../stores/itemDetailStore.svelte.js'; + import { timeLogStore } from '../../stores/timeLogStore.svelte.js'; import { t } from '../../stores/i18n.svelte.js'; import { getShortcut, matchesShortcut, isTypingInField } from '../../utils/keyboardShortcuts.js'; import Trash2 from '@lucide/svelte/icons/trash-2'; @@ -58,7 +59,6 @@ import ItemSplitDialog from './ItemSplitDialog.svelte'; // Import the shared content component import ItemDetailContent from '../items/ItemDetailContent.svelte'; -import TimeLogModal from '../../dialogs/TimeLogModal.svelte'; import TestCaseViewModal from '../../dialogs/TestCaseViewModal.svelte'; import RecurrenceEditor from '../../editors/RecurrenceEditor.svelte'; import Button from '../../components/Button.svelte'; @@ -643,13 +643,20 @@ import NativeSelect from '../../components/NativeSelect.svelte'; } async function handleLogTime() { - await itemDetailStore.loadTimeModalData(); - itemDetailStore.openTimeLogModal(); + await timeLogStore.open({ + itemId: parseInt(itemId), + defaultProjectId: getDefaultProjectForTimeLogging(), + showWorkItemField: false, + }); } async function handleEditWorklog(detail) { - await itemDetailStore.loadTimeModalData(); - itemDetailStore.openTimeLogModal(detail); + await timeLogStore.open({ + itemId: parseInt(itemId), + defaultProjectId: getDefaultProjectForTimeLogging(), + showWorkItemField: false, + editingWorklog: detail, + }); } async function handleDeleteWorklog(detail) { @@ -664,28 +671,6 @@ import NativeSelect from '../../components/NativeSelect.svelte'; } } - async function handleModalSave(event) { - try { - const data = event.detail; - if (itemDetailStore.editingWorklog) { - await time.worklogs.update(itemDetailStore.editingWorklog.id, data); - } else { - await time.worklogs.create(data); - } - - // Reload worklogs - await itemDetailStore.reloadWorklogs(); - itemDetailStore.closeTimeLogModal(); - } catch (error) { - console.error('Failed to save worklog:', error); - showError(t('items.failedToSaveTimeEntry'), error.message || t('errors.UNKNOWN')); - } - } - - function handleModalCancel() { - itemDetailStore.closeTimeLogModal(); - } - // Get default project for time logging function getDefaultProjectForTimeLogging() { return itemDetailStore.getDefaultProjectForTimeLogging(); @@ -1182,16 +1167,12 @@ import NativeSelect from '../../components/NativeSelect.svelte'; description: 'Add a time entry for this work item', keywords: ['log', 'time', 'hours', 'work', 'track', 'entry'], action: () => { - // Trigger the time entry form in the tabs component - if (tab !== 'time') { - tab = 'time'; - } - // Use a small delay to ensure tab is switched - setTimeout(() => { - window.dispatchEvent(new CustomEvent('item-detail-show-time-entry', { - detail: { itemId: item.id } - })); - }, 100); + // Open the shared time-log surface prefilled with this item. + void timeLogStore.open({ + itemId: item.id, + defaultProjectId: getDefaultProjectForTimeLogging(), + showWorkItemField: false, + }); }, priority: COMMAND_PRIORITIES.HIGH, category: 'time' @@ -1263,6 +1244,18 @@ import NativeSelect from '../../components/NativeSelect.svelte'; itemDetailStore.item && populateDropdownItems(); }); + // Reload worklogs after the shared time-log host saves or books an entry. + let lastTimeLogRevision = 0; + $effect(() => { + const revision = timeLogStore.revision; + if (revision !== lastTimeLogRevision) { + lastTimeLogRevision = revision; + itemDetailStore.reloadWorklogs().catch((err) => { + surfaceError(err, { context: 'reloadWorklogsAfterTimeLog' }); + }); + } + }); + // Reload worklogs when timer stops (activeTimer becomes null from non-null) let previousActiveTimer; // Plain variable, not reactive - prevents self-invalidation $effect(() => { @@ -1592,23 +1585,7 @@ import NativeSelect from '../../components/NativeSelect.svelte'; {/if} {/if} - -{#if itemDetailStore.showTimeLogModal} - -{/if} + + import Button from '../../components/Button.svelte'; + import Card from '../../components/Card.svelte'; + import { t } from '../../stores/i18n.svelte.js'; + import { errorToast } from '../../stores/toasts.svelte.js'; + import { timeLogStore } from '../../stores/timeLogStore.svelte.js'; + + let { class: className = '' } = $props(); + + function formatDuration(minutes) { + if (!minutes) return ''; + const hours = Math.floor(minutes / 60); + const mins = minutes % 60; + if (hours === 0) return `${mins}m`; + if (mins === 0) return `${hours}h`; + return `${hours}h ${mins}m`; + } + + function draftLabel(draft) { + return draft.item_title || draft.description || draft.project_name || t('time.drafts'); + } + + async function complete(draft) { + try { + await timeLogStore.openDraft(draft.id); + } catch (error) { + console.error('Failed to open draft:', error); + errorToast(t('time.bookFailed')); + } + } + + async function discard(draft) { + try { + await timeLogStore.removeDraft(draft.id); + } catch (error) { + console.error('Failed to discard draft:', error); + errorToast(t('time.discardFailed')); + } + } + + +{#if timeLogStore.drafts.length > 0} +
+ +

+ {t('time.drafts')} ({timeLogStore.drafts.length}) +

+
    + {#each timeLogStore.drafts as draft (draft.id)} +
  • +
    +
    {draftLabel(draft)}
    +
    + {#if draft.project_name}{draft.project_name} · {/if} + {formatDuration(draft.duration_minutes)} +
    +
    + + +
  • + {/each} +
+
+
+{/if} diff --git a/frontend/src/lib/features/time/TimeEntry.svelte b/frontend/src/lib/features/time/TimeEntry.svelte index 625ee868b..0a7c4e996 100644 --- a/frontend/src/lib/features/time/TimeEntry.svelte +++ b/frontend/src/lib/features/time/TimeEntry.svelte @@ -7,6 +7,7 @@ import AlertBox from '../../components/AlertBox.svelte'; import { navigate } from '../../router.js'; import { timeEntryStore } from '../../stores/timeEntryStore.svelte.js'; + import { timeLogStore } from '../../stores/timeLogStore.svelte.js'; import { permissionStore, isSystemAdmin } from '../../stores/permissions.svelte.js'; import Button from '../../components/Button.svelte'; import Input from '../../components/Input.svelte'; @@ -14,11 +15,10 @@ import DataTable from '../../components/DataTable.svelte'; import Card from '../../components/Card.svelte'; import TimeTrackingOnboarding from './TimeTrackingOnboarding.svelte'; - import TimeLogModal from '../../dialogs/TimeLogModal.svelte'; + import TimeDraftsCard from './TimeDraftsCard.svelte'; import { toHotkeyString } from '../../utils/keyboardShortcuts.js'; import { t } from '../../stores/i18n.svelte.js'; import { customerOrganisationName, realCustomers } from '../../utils/customerLabel.js'; - import { errorToast } from '../../stores/toasts.svelte.js'; import { confirm } from '../../composables/useConfirm.js'; import { formatDateOnly, getUserTimezone } from '../../utils/dateFormatter.js'; import { dateKeyInZone } from '../../utils/worklogTimezone.js'; @@ -28,12 +28,7 @@ // Bind to store values let worklogs = $derived(timeEntryStore.worklogs); let customers = $derived(timeEntryStore.customers); - let projects = $derived(timeEntryStore.projects); - let workItems = $derived(timeEntryStore.workItems); - let workspaces = $derived(timeEntryStore.workspaces); - let editingWorklog = $derived(timeEntryStore.editingWorklog); let showOnboarding = $derived(timeEntryStore.showOnboarding); - let showTimeLogModal = $derived(timeEntryStore.showTimeLogModal); let filters = $derived(timeEntryStore.filters); let activeProjects = $derived(timeEntryStore.activeProjects); let filteredProjects = $derived(timeEntryStore.filteredProjects); @@ -51,6 +46,7 @@ onMount(async () => { await timeEntryStore.init(); + void timeLogStore.refreshDrafts(); }); function buildWorklogDropdownItems(worklog) { @@ -62,7 +58,7 @@ title: t('common.edit'), testid: 'worklog-edit', hoverClass: 'hover-bg', - onClick: () => timeEntryStore.editWorklog(worklog) + onClick: () => timeLogStore.open({ editingWorklog: worklog }) }, { id: 'delete', @@ -76,24 +72,20 @@ ]; } - async function handleModalSave(event) { - try { - const data = event.detail; - await timeEntryStore.saveWorklog(data); - } catch (error) { - console.error('Failed to save worklog:', error); - errorToast(t('time.entry.failedToSave')); - } - } - - function handleModalCancel() { - timeEntryStore.closeTimeLogModal(); - } - function openLogTimeModal() { - timeEntryStore.openTimeLogModal(); + timeLogStore.open(); } + // Reload the page list after the shared host saves or books an entry. + let lastTimeLogRevision = 0; + $effect(() => { + const revision = timeLogStore.revision; + if (revision !== lastTimeLogRevision) { + lastTimeLogRevision = revision; + timeEntryStore.loadWorklogs(); + } + }); + async function deleteWorklog(worklog) { const confirmed = await confirm({ title: t('common.delete'), @@ -162,7 +154,7 @@ icon={Plus} onclick={openLogTimeModal} keyboardHint="A" - hotkeyConfig={{ key: toHotkeyString('timeEntry', 'openLog'), guard: () => !showTimeLogModal }} + hotkeyConfig={{ key: toHotkeyString('timeEntry', 'openLog'), guard: () => !timeLogStore.show }} title={t('time.entry.addTimeEntry')} dataTestid="time-log-open" > @@ -301,15 +293,6 @@ {/if} - -{#if showTimeLogModal} - -{/if} + + + diff --git a/frontend/src/lib/features/time/TimeLogHost.svelte b/frontend/src/lib/features/time/TimeLogHost.svelte new file mode 100644 index 000000000..0336fbac4 --- /dev/null +++ b/frontend/src/lib/features/time/TimeLogHost.svelte @@ -0,0 +1,63 @@ + + +{#if timeLogStore.show} + timeLogStore.close()} + ondiscard={handleDiscard} + /> +{/if} diff --git a/frontend/src/lib/features/time/stopTimerAndReview.js b/frontend/src/lib/features/time/stopTimerAndReview.js new file mode 100644 index 000000000..6b44c731d --- /dev/null +++ b/frontend/src/lib/features/time/stopTimerAndReview.js @@ -0,0 +1,19 @@ +import { t } from '../../stores/i18n.svelte.js'; +import { successToast } from '../../stores/toasts.svelte.js'; + +/** + * Stop the active timer and route the result: a complete entry is booked + * silently, an incomplete one is persisted as a draft and opened in the shared + * time-log modal for completion. Shared by the floating timer, the palette + * stop command, and the mobile timer view. + */ +export async function stopTimerAndReview(timerStore, timeLogStore) { + const result = await timerStore.stop(); + if (!result) return null; + if (result.booked) { + successToast(t('time.timeBooked')); + } else if (result.draft_id) { + await timeLogStore.openDraft(result.draft_id); + } + return result; +} diff --git a/frontend/src/lib/layout/MainSidebar.svelte b/frontend/src/lib/layout/MainSidebar.svelte index 49c73fa28..3c23c113b 100644 --- a/frontend/src/lib/layout/MainSidebar.svelte +++ b/frontend/src/lib/layout/MainSidebar.svelte @@ -5,6 +5,7 @@ import { uiStore } from '../stores/ui.svelte.js'; import { workspacesStore } from '../stores/workspaces.svelte.js'; import { homepageStore } from '../stores/homepageStore.svelte.js'; + import { timeLogStore } from '../stores/timeLogStore.svelte.js'; import { t } from '../stores/i18n.svelte.js'; import { themeStore } from '../stores/theme.svelte.js'; import { brandStore, resolveBrandLockup } from '../stores/brand.svelte.js'; @@ -13,6 +14,7 @@ import { workspaceMenuItems } from '../navigation/workspaceMenu.js'; import { isTauri as getIsTauri } from '../utils/isTauri.js'; import DropdownMenu from './DropdownMenu.svelte'; + import TimeNavMenu from './TimeNavMenu.svelte'; import Tooltip from '../components/Tooltip.svelte'; import NavLink from './NavLink.svelte'; import UserAvatar from '../components/UserAvatar.svelte'; @@ -86,6 +88,7 @@ // recency order. onOpen still refreshes it so recent navigation is reflected. onMount(() => { void loadRecentWorkspaceOrder(); + void timeLogStore.refreshDrafts(); }); function onWorkspaceSearchInput(value) { @@ -220,15 +223,19 @@ {#each filteredMainNav as item (item.id)} - + {#if item.id === 'time'} + + {:else} + + {/if} {/each} + + + diff --git a/frontend/src/lib/mobile/TimerView.svelte b/frontend/src/lib/mobile/TimerView.svelte index 28fd43ee8..b6b069c2b 100644 --- a/frontend/src/lib/mobile/TimerView.svelte +++ b/frontend/src/lib/mobile/TimerView.svelte @@ -9,11 +9,13 @@ import CommandIcon from '@lucide/svelte/icons/command'; import { timerStore } from '../stores/timerStore.svelte.js'; import { timeEntryStore } from '../stores/timeEntryStore.svelte.js'; + import { timeLogStore } from '../stores/timeLogStore.svelte.js'; import { confirm } from '../composables/useConfirm.js'; import { t } from '../stores/i18n.svelte.js'; import { formatItemKey } from '../utils/itemKey.js'; import MobileHeader from './MobileHeader.svelte'; - import TimeLogModal from '../dialogs/TimeLogModal.svelte'; + import TimeDraftsCard from '../features/time/TimeDraftsCard.svelte'; + import { stopTimerAndReview } from '../features/time/stopTimerAndReview.js'; import { formatAuthenticatedInstant } from '../utils/authenticatedDateFormatter.js'; import { mobilePalette } from './mobilePalette.svelte.js'; @@ -31,7 +33,7 @@ async function stopTimer() { try { - await timerStore.stop(); + await stopTimerAndReview(timerStore, timeLogStore); await timeEntryStore.loadWorklogs(); } catch (err) { console.error('Failed to stop timer:', err); @@ -52,6 +54,7 @@ onMount(() => { timeEntryStore.init(); + void timeLogStore.refreshDrafts(); }); @@ -97,7 +100,7 @@

{t('mobile.timer.recentWorklogs')}

-
@@ -110,7 +113,7 @@
    {#each worklogs as w (w.id)}
  • -
{/if}
-
- -{#if timeEntryStore.showTimeLogModal} - timeEntryStore.saveWorklog(e.detail)} - oncancel={() => timeEntryStore.closeTimeLogModal()} - /> -{/if} + + +