diff --git a/README.md b/README.md index a835de1..3de0366 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,8 @@ Run the server with `go run ./cmd/server --static-dir web/dist`. Configure: - `PLATFORM_API_URL`, `PLATFORM_PROJECT_ID`, and the platform OIDC identity settings. - `TRACKER_DATABASE_URL` (or `DATABASE_URL`) for PostgreSQL. `TRACKER_DEV_SEED=1` enables - development seed data on an empty database. + development seed data on an empty database: 40 issues, three closed one-week sprints + with 18/21/24-point velocities, an active two-week sprint, and a planned sprint. - `TRACKER_PUBLIC_URL` for the HTTPS browser origin. - `TRACKER_DIRECTORY_URL` and `TRACKER_DIRECTORY_PUBLIC_URL` for optional Directory links. - `TRACKER_STATIC_DIR` or `--static-dir` to override `/srv/tracker`. @@ -67,6 +68,16 @@ and `/healthz` remains 200. Missing database configuration leaves the API return when the API is available. `/releasez` uses `TRACKER_RELEASE_VERSION` and `TRACKER_ARTIFACT_DIGEST` supplied by the catalog. +Sprint settings are workspace-wide: Admins can PATCH `sprintLengthWeeks` (1 or 2) +and an IANA `timezone` (default `Asia/Tokyo`). Any signed-in user can plan, start, +and close a sprint; only Admins can delete a planned sprint. Estimates are sizes +(`XS`, `S`, `M`, `L`, `XL`), worth 1/2/3/5/8 points. The server writes a +transactional ledger for burndown and velocity; closed ledgers never change. +On close, unfinished scope moves to the selected planned sprint or the backlog. +A lineage conflict in the destination sends that issue to the backlog. +Chart days follow the workspace timezone; ideal lines skip weekends, not holidays. +Sprint numbers are never reused after deletion. + A request whose bearer the server refuses (401 `unauthenticated`) writes one `tracker auth rejected:` log line: method, path, the edge `X-Request-Id`, a reason (`issuer`, `audience`, `expired_or_not_yet_valid`, `signature_or_keys`, @@ -102,14 +113,14 @@ a required BuildKit secret, never through build arguments or committed files. ## Catalog and release -The next app release is **0.1.9**, also recorded in `web/package.json`. +The next app release is **0.1.10**, also recorded in `web/package.json`. `catalog/entry.yaml` carries no committed version: the first tag (`v0.1.0`) created `versions[]` with `ghcr.io/appthrust/tracker@sha256:`, stream `0.1`; later tags append at publication time. Do not add a version with an unbuilt or placeholder image digest. OpenAPI's `info.version` describes the API schema, not the app release. This repository has no hand-maintained changelog. -After the release prerequisites are available, push the SemVer tag `v0.1.9`. +After the release prerequisites are available, push the SemVer tag `v0.1.10`. The tag workflow: 1. Performs one multi-platform build on `ubuntu-24.04` for Linux amd64 and arm64, @@ -129,8 +140,8 @@ The tag workflow: Publication commands used by the workflow: ```sh -bun hack/publish-entry.ts submit --version 0.1.9 --digest sha256: -bun hack/publish-entry.ts await --version 0.1.9 --digest sha256: +bun hack/publish-entry.ts submit --version 0.1.10 --digest sha256: +bun hack/publish-entry.ts await --version 0.1.10 --digest sha256: ``` Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to @@ -151,8 +162,8 @@ After publication, each estate's `AppCatalogSource` syncs the signed catalog. Install Issues from the Project Marketplace (Directory is an automatic dependency). Existing `follow` installations on stream `0.1` roll to the new version; `pinned` installations show `UpdateAvailable` and require an explicit -version update. Confirm the installation is Ready, `/releasez` reports `0.1.9`, -and a signed-in Tracker page lists the Epics page in the navigation. These are release steps, +version update. Confirm the installation is Ready, `/releasez` reports `0.1.10`, +and a signed-in Tracker page lists the Sprints page in the navigation. These are release steps, not actions performed by a source-only version bump. Migration authority: diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index 9e41bfb..6bad088 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -57,6 +57,15 @@ func New(database *store.Store, auth *identity.Authenticator, upstream *platform a.route("GET /projects/{id}", false, false, a.projectGet) a.route("PATCH /projects/{id}", true, true, a.projectPatch) a.route("DELETE /projects/{id}", true, true, a.projectDelete) + a.route("GET /sprints", false, false, a.sprintList) + a.route("POST /sprints", true, false, a.sprintCreate) + a.route("GET /sprints/{id}", false, false, a.sprintGet) + a.route("PATCH /sprints/{id}", true, false, a.sprintPatch) + a.route("POST /sprints/{id}/start", true, false, a.sprintStart) + a.route("POST /sprints/{id}/close", true, false, a.sprintClose) + a.route("DELETE /sprints/{id}", true, true, a.sprintDelete) + a.route("GET /sprints/{id}/burndown", false, false, a.sprintBurndown) + a.route("GET /velocity", false, false, a.velocity) a.route("GET /issues", false, false, a.issueList) a.route("POST /issues", true, false, a.issueCreate) a.route("GET /issues/{id}", false, false, a.issueGet) @@ -191,7 +200,11 @@ func decode(s *request, target any, nullable ...string) error { } decoder := json.NewDecoder(bytes.NewReader(body)) decoder.DisallowUnknownFields() - if decoder.Decode(target) != nil { + if err := decoder.Decode(target); err != nil { + var typed *json.UnmarshalTypeError + if errors.As(err, &typed) && (typed.Field == "estimate" || typed.Field == "sprintId") { + return &domain.FieldError{Path: typed.Field, Message: "Value must be a string or null"} + } return invalid("Request body contains invalid or unknown fields") } if decoder.Decode(new(any)) != io.EOF { diff --git a/cmd/server/internal/api/api_test.go b/cmd/server/internal/api/api_test.go index 9ddfa03..d0391ab 100644 --- a/cmd/server/internal/api/api_test.go +++ b/cmd/server/internal/api/api_test.go @@ -24,8 +24,9 @@ import ( ) type harness struct { - t *testing.T - server *httptest.Server + t *testing.T + server *httptest.Server + database *store.Store } func token(subject string) string { @@ -55,7 +56,7 @@ func newHarness(t *testing.T) *harness { require.NoError(t, err) server := httptest.NewServer(New(database, auth, platformclient.New(upstream.URL, "pj-test"), directory.New(nil, ""), "pj-test")) t.Cleanup(server.Close) - return &harness{t: t, server: server} + return &harness{t: t, server: server, database: database} } func call[T any](h *harness, subject, method, path string, body any, status int) T { h.t.Helper() @@ -197,7 +198,7 @@ func TestOpenAPIRouteInventory(t *testing.T) { } require.NoError(t, json.Unmarshal(openapiDocument, &document)) require.Equal(t, "3.1.0", document.OpenAPI) - for path, methods := range map[string][]string{"/me": {"get"}, "/workspace": {"get", "patch"}, "/statuses": {"get", "post"}, "/statuses/{id}": {"patch", "delete"}, "/statuses/order": {"put"}, "/labels": {"get", "post"}, "/labels/{id}": {"patch", "delete"}, "/issues": {"get", "post"}, "/issues/{id}": {"get", "patch", "delete"}, "/issues/{id}/timeline": {"get"}, "/issues/{id}/comments": {"post"}, "/comments/{id}": {"patch", "delete"}, "/issues/{id}/attachments": {"post"}, "/attachments/{id}": {"get", "delete"}, "/views": {"get", "post"}, "/views/{id}": {"patch", "delete"}, "/people": {"get"}, "/openapi.json": {"get"}} { + for path, methods := range map[string][]string{"/me": {"get"}, "/workspace": {"get", "patch"}, "/statuses": {"get", "post"}, "/statuses/{id}": {"patch", "delete"}, "/statuses/order": {"put"}, "/labels": {"get", "post"}, "/labels/{id}": {"patch", "delete"}, "/issues": {"get", "post"}, "/issues/{id}": {"get", "patch", "delete"}, "/issues/{id}/timeline": {"get"}, "/issues/{id}/comments": {"post"}, "/comments/{id}": {"patch", "delete"}, "/issues/{id}/attachments": {"post"}, "/attachments/{id}": {"get", "delete"}, "/views": {"get", "post"}, "/views/{id}": {"patch", "delete"}, "/people": {"get"}, "/openapi.json": {"get"}, "/sprints": {"get", "post"}, "/sprints/{id}": {"get", "patch", "delete"}, "/sprints/{id}/start": {"post"}, "/sprints/{id}/close": {"post"}, "/sprints/{id}/burndown": {"get"}, "/velocity": {"get"}} { for _, method := range methods { require.Contains(t, document.Paths[path], method, "%s %s", method, path) } @@ -247,9 +248,9 @@ func TestOpenAPIHierarchyContract(t *testing.T) { require.NoError(t, json.Unmarshal(openapiDocument, &document)) schemas := document.Components.Schemas require.Equal(t, domain.Types, schemas["IssueType"].Enum) - require.Equal(t, []string{"none", "epic", "story"}, schemas["GroupBy"].Enum) + require.Equal(t, []string{"none", "epic", "story", "sprint"}, schemas["GroupBy"].Enum) require.Equal(t, "none", schemas["GroupBy"].Default) - require.ElementsMatch(t, []string{"total", "completed"}, schemas["Progress"].Required) + require.ElementsMatch(t, []string{"total", "completed", "points"}, schemas["Progress"].Required) for _, field := range []string{"total", "completed"} { require.JSONEq(t, `{"type":"integer","minimum":0}`, string(schemas["Progress"].Properties[field])) } diff --git a/cmd/server/internal/api/issues.go b/cmd/server/internal/api/issues.go index 27bfc6c..90ae0ef 100644 --- a/cmd/server/internal/api/issues.go +++ b/cmd/server/internal/api/issues.go @@ -58,7 +58,7 @@ func (a *API) assignee(s *request, sub *string) (*domain.Person, error) { } func (a *API) issueCreate(s *request) (any, int, error) { var input store.IssueCreate - if err := decode(s, &input, "assigneeSub", "projectId", "parentId", "dueOn", "report"); err != nil { + if err := decode(s, &input, "assigneeSub", "projectId", "parentId", "dueOn", "report", "estimate", "sprintId"); err != nil { return nil, 0, err } assignee, err := a.assignee(s, input.AssigneeSub) @@ -70,7 +70,7 @@ func (a *API) issueCreate(s *request) (any, int, error) { } func (a *API) issuePatch(s *request) (any, int, error) { var input store.IssuePatch - if err := decode(s, &input, "assigneeSub", "projectId", "parentId", "dueOn", "report"); err != nil { + if err := decode(s, &input, "assigneeSub", "projectId", "parentId", "dueOn", "report", "estimate", "sprintId"); err != nil { return nil, 0, err } var assignee *domain.Person diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index 31898ce..dcde732 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -2,7 +2,7 @@ "openapi": "3.1.0", "info": { "title": "Tracker API", - "version": "0.2.0", + "version": "0.1.10", "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID." }, "servers": [ @@ -264,6 +264,19 @@ "type": "string", "maxLength": 100, "minLength": 1 + }, + "sprintLengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 + ], + "default": 1 + }, + "timezone": { + "type": "string", + "default": "Asia/Tokyo", + "description": "IANA timezone name" } }, "required": [], @@ -3325,36 +3338,126 @@ "in": "path", "required": true, "description": "Directory person id (not the OIDC subject).", - "schema": { "type": "string" } + "schema": { + "type": "string" + } }, { "name": "v", "in": "query", "description": "Directory avatarVersion, used as a cache key, not a historical-image selector.", - "schema": { "type": "string" } + "schema": { + "type": "string" + } } ], "responses": { "200": { "description": "Directory image bytes", "headers": { - "Cache-Control": { "schema": { "type": "string" }, "description": "private, max-age=86400 with v; private, no-cache otherwise. Not immutable." }, - "ETag": { "schema": { "type": "string" }, "description": "Validator keyed by version and image content." }, - "X-Content-Type-Options": { "schema": { "type": "string", "const": "nosniff" } } + "Cache-Control": { + "schema": { + "type": "string" + }, + "description": "private, max-age=86400 with v; private, no-cache otherwise. Not immutable." + }, + "ETag": { + "schema": { + "type": "string" + }, + "description": "Validator keyed by version and image content." + }, + "X-Content-Type-Options": { + "schema": { + "type": "string", + "const": "nosniff" + } + } }, "content": { - "image/png": { "schema": { "type": "string", "format": "binary" } }, - "image/jpeg": { "schema": { "type": "string", "format": "binary" } }, - "image/webp": { "schema": { "type": "string", "format": "binary" } } + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/webp": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "304": { + "description": "If-None-Match matches after authentication and upstream fetch." + }, + "400": { + "description": "Invalid person id", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Directory denied access", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Directory, person or avatar absent", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "502": { + "description": "directory_avatar_unavailable: invalid content, oversized response or upstream failure", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } } }, - "304": { "description": "If-None-Match matches after authentication and upstream fetch." }, - "400": { "description": "Invalid person id", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, - "401": { "description": "Unauthenticated", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, - "403": { "description": "Directory denied access", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, - "404": { "description": "Directory, person or avatar absent", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, - "502": { "description": "directory_avatar_unavailable: invalid content, oversized response or upstream failure", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }, - "503": { "description": "Identity or Tracker store unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } } + "503": { + "description": "Identity or Tracker store unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } } } }, @@ -3437,65 +3540,942 @@ }, "security": [] } - } - }, - "components": { - "securitySchemes": { - "bearerAuth": { - "type": "http", - "scheme": "bearer", - "bearerFormat": "JWT" - } }, - "schemas": { - "Person": { - "type": "object", - "properties": { - "sub": { - "type": "string" + "/sprints": { + "get": { + "operationId": "listSprints", + "summary": "listSprints", + "description": "Authorization: any authenticated user. Active first, planned by startsOn, then closed newest first.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Sprint" + } + } + }, + "required": [ + "items" + ], + "additionalProperties": false + } + } + } }, - "name": { - "type": "string" + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "avatarUrl": { - "type": "string", - "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "email": { - "type": "string" + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "profileUrl": { - "type": "string" + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } } }, - "required": [ - "sub", - "name" - ], - "additionalProperties": false + "parameters": [ + { + "name": "state", + "in": "query", + "schema": { + "$ref": "#/components/schemas/SprintState" + } + } + ] }, - "Me": { - "type": "object", - "properties": { - "sub": { - "type": "string" - }, - "name": { - "type": "string" - }, - "avatarUrl": { - "type": "string", - "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + "post": { + "operationId": "createSprint", + "summary": "createSprint", + "description": "Authorization: any authenticated user. Defaults lengthWeeks to workspace setting, startsOn to day after latest non-closed endsOn or coming Monday, name to Sprint . Overlap returns 409.", + "responses": { + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Sprint" + } + } + } }, - "email": { - "type": "string" + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "profileUrl": { - "type": "string" + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, - "role": { - "type": "string", - "enum": [ + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SprintCreate" + } + } + } + } + } + }, + "/sprints/{id}": { + "get": { + "operationId": "getSprint", + "summary": "getSprint", + "description": "Authorization: any authenticated user. ", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Sprint" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + } + ] + }, + "patch": { + "operationId": "patchSprint", + "summary": "patchSprint", + "description": "Authorization: any authenticated user. Only planned sprints may change dates; otherwise 409. Overlap returns 409.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Sprint" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SprintPatch" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + } + ] + }, + "delete": { + "operationId": "deleteSprint", + "summary": "deleteSprint", + "description": "Authorization: Admin. Only planned sprints; otherwise 409. Members return to backlog.", + "responses": { + "204": { + "description": "Success" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + } + ] + } + }, + "/sprints/{id}/start": { + "post": { + "operationId": "startSprint", + "summary": "startSprint", + "description": "Authorization: any authenticated user. 409 unless planned with no other active sprint. Future startsOn becomes today, keeping length; overlap returns 409.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Sprint" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + } + ] + } + }, + "/sprints/{id}/close": { + "post": { + "operationId": "closeSprint", + "summary": "closeSprint", + "description": "Authorization: any authenticated user. 409 unless active. Invalid destination returns 400 at moveIncompleteTo. Freeze ledger, then move unfinished scope to planned destination or backlog. Lineage conflicts go to backlog; done members stay.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Sprint" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SprintClose" + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + } + ] + } + }, + "/sprints/{id}/burndown": { + "get": { + "operationId": "getBurndown", + "summary": "getBurndown", + "description": "Authorization: any authenticated user. Workspace timezone day boundaries; project filters issues by current project. Pre-start ledger rows count on day one; final closed day includes close. Future days omit actuals.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Burndown" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + "description": "Sprint ULID." + }, + { + "name": "unit", + "in": "query", + "schema": { + "$ref": "#/components/schemas/Unit" + } + }, + { + "name": "project", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + } + ] + } + }, + "/velocity": { + "get": { + "operationId": "getVelocity", + "summary": "getVelocity", + "description": "Authorization: any authenticated user. Closed sprint done at close, scope at start. Project filters issues by current project.", + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Velocity" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Unauthenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Dependency unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "unit", + "in": "query", + "schema": { + "$ref": "#/components/schemas/Unit" + } + }, + { + "name": "project", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 26, + "default": 8 + } + } + ] + } + } + }, + "components": { + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT" + } + }, + "schemas": { + "Person": { + "type": "object", + "properties": { + "sub": { + "type": "string" + }, + "name": { + "type": "string" + }, + "avatarUrl": { + "type": "string", + "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + }, + "email": { + "type": "string" + }, + "profileUrl": { + "type": "string" + } + }, + "required": [ + "sub", + "name" + ], + "additionalProperties": false + }, + "Me": { + "type": "object", + "properties": { + "sub": { + "type": "string" + }, + "name": { + "type": "string" + }, + "avatarUrl": { + "type": "string", + "description": "Same-origin /api/tracker/v1/people/{id}/avatar?v=; omitted without an avatar." + }, + "email": { + "type": "string" + }, + "profileUrl": { + "type": "string" + }, + "role": { + "type": "string", + "enum": [ "Admin", "Editor", "Viewer" @@ -3538,6 +4518,19 @@ "updatedAt": { "type": "string", "format": "date-time" + }, + "sprintLengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 + ], + "default": 1 + }, + "timezone": { + "type": "string", + "default": "Asia/Tokyo", + "description": "IANA timezone name" } }, "required": [ @@ -3546,7 +4539,9 @@ "name", "issueCount", "createdAt", - "updatedAt" + "updatedAt", + "sprintLengthWeeks", + "timezone" ], "additionalProperties": false }, @@ -3769,7 +4764,8 @@ "updated", "created", "priority", - "number" + "number", + "estimate" ] }, "GroupBy": { @@ -3777,7 +4773,8 @@ "enum": [ "none", "epic", - "story" + "story", + "sprint" ], "default": "none" }, @@ -3792,11 +4789,30 @@ "completed": { "type": "integer", "minimum": 0 + }, + "points": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "minimum": 0 + }, + "completed": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "total", + "completed" + ], + "additionalProperties": false } }, "required": [ "total", - "completed" + "completed", + "points" ], "additionalProperties": false }, @@ -4008,6 +5024,26 @@ "type": "null" } ] + }, + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprint": { + "anyOf": [ + { + "$ref": "#/components/schemas/SprintRef" + }, + { + "type": "null" + } + ] } }, "required": [ @@ -4032,7 +5068,9 @@ "attachmentCount", "createdAt", "updatedAt", - "completedAt" + "completedAt", + "estimate", + "sprint" ], "additionalProperties": false }, @@ -4206,6 +5244,26 @@ "items": { "$ref": "#/components/schemas/IssueRef" } + }, + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprint": { + "anyOf": [ + { + "$ref": "#/components/schemas/SprintRef" + }, + { + "type": "null" + } + ] } }, "required": [ @@ -4234,7 +5292,9 @@ "description", "children", "blocks", - "blockedBy" + "blockedBy", + "estimate", + "sprint" ], "additionalProperties": false }, @@ -4367,7 +5427,9 @@ "due", "report", "attachment", - "deleted" + "deleted", + "estimate", + "sprint" ] }, "from": {}, @@ -4434,140 +5496,513 @@ "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" } }, - "category": { + "category": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StatusCategory" + } + }, + "assignee": { + "type": "array", + "items": { + "type": "string" + } + }, + "reporter": { + "type": "array", + "description": "Match reporter subjects; 'me' resolves to the caller. 'none' is not supported. Invalid values return 400 invalid with path filter.reporter.", + "maxItems": 20, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "not": { + "const": "none" + } + } + }, + "label": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + } + }, + "project": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "const": "none" + } + ] + } + }, + "epic": { + "type": "array", + "description": "Match the derived strict epic ancestor by ID; none matches issues without an epic.", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + }, + "story": { + "type": "array", + "description": "Match the derived strict story ancestor by ID; none matches issues without a story.", + "items": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "none" + } + ] + } + }, + "type": { "type": "array", "items": { - "$ref": "#/components/schemas/StatusCategory" + "$ref": "#/components/schemas/IssueType" } }, - "assignee": { + "priority": { "type": "array", "items": { - "type": "string" + "$ref": "#/components/schemas/Priority" } }, - "reporter": { + "q": { + "type": "string", + "maxLength": 4096 + }, + "createdAfter": { + "type": "string", + "format": "date-time" + }, + "environment": { "type": "array", - "description": "Match reporter subjects; 'me' resolves to the caller. 'none' is not supported. Invalid values return 400 invalid with path filter.reporter.", - "maxItems": 20, "items": { "type": "string", - "minLength": 1, "maxLength": 4096, - "not": { - "const": "none" - } + "minLength": 1 } }, - "label": { + "surface": { "type": "array", "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "$ref": "#/components/schemas/Surface" } }, - "project": { + "parent": { + "type": "string" + }, + "sprint": { "type": "array", "items": { "anyOf": [ { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "const": "active" }, { "const": "none" } ] } + } + }, + "required": [], + "additionalProperties": false + }, + "View": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "epic": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 + }, + "owner": { + "$ref": "#/components/schemas/Person" + }, + "shared": { + "type": "boolean" + }, + "layout": { + "type": "string", + "enum": [ + "list", + "board" + ] + }, + "groupBy": { + "$ref": "#/components/schemas/GroupBy" + }, + "filter": { + "$ref": "#/components/schemas/Filter" + }, + "sort": { + "$ref": "#/components/schemas/Sort" + }, + "position": { + "type": "integer" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "name", + "owner", + "shared", + "layout", + "groupBy", + "filter", + "sort", + "position", + "createdAt", + "updatedAt" + ], + "additionalProperties": false + }, + "Error": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "invalid", + "unauthenticated", + "forbidden", + "not_found", + "conflict", + "tracker_store_unavailable", + "identity_unavailable" + ] + }, + "message": { + "type": "string" + }, + "issues": { "type": "array", - "description": "Match the derived strict epic ancestor by ID; none matches issues without an epic.", "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + "type": "object", + "properties": { + "path": { + "type": "string" }, - { - "const": "none" + "message": { + "type": "string" } - ] + }, + "required": [ + "path", + "message" + ], + "additionalProperties": false + } + } + }, + "required": [ + "error", + "message" + ], + "additionalProperties": false + }, + "IssueCreate": { + "type": "object", + "properties": { + "title": { + "type": "string", + "maxLength": 200, + "minLength": 1 + }, + "description": { + "type": "string", + "description": "Markdown, at most 50 KiB UTF-8" + }, + "type": { + "$ref": "#/components/schemas/IssueType" + }, + "priority": { + "$ref": "#/components/schemas/Priority" + }, + "statusId": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "assigneeSub": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096, + "minLength": 1 + }, + { + "type": "null" + } + ] + }, + "labelIds": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" } }, - "story": { - "type": "array", - "description": "Match the derived strict story ancestor by ID; none matches issues without a story.", - "items": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" - }, - { - "const": "none" - } - ] - } + "projectId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } + ] + }, + "parentId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } + ] + }, + "dueOn": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ] + }, + "report": { + "anyOf": [ + { + "$ref": "#/components/schemas/Report" + }, + { + "type": "null" + } + ] + }, + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprintId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "title", + "type" + ], + "additionalProperties": false + }, + "IssuePatch": { + "type": "object", + "properties": { + "title": { + "type": "string", + "maxLength": 200, + "minLength": 1 + }, + "description": { + "type": "string", + "description": "Markdown, at most 50 KiB UTF-8" }, "type": { - "type": "array", - "items": { - "$ref": "#/components/schemas/IssueType" - } + "$ref": "#/components/schemas/IssueType" }, "priority": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Priority" - } + "$ref": "#/components/schemas/Priority" }, - "q": { + "statusId": { "type": "string", - "maxLength": 4096 + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" }, - "createdAfter": { - "type": "string", - "format": "date-time" + "assigneeSub": { + "anyOf": [ + { + "type": "string", + "maxLength": 4096, + "minLength": 1 + }, + { + "type": "null" + } + ] }, - "environment": { + "labelIds": { "type": "array", "items": { "type": "string", - "maxLength": 4096, - "minLength": 1 + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" } }, - "surface": { + "projectId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } + ] + }, + "parentId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + { + "type": "null" + } + ] + }, + "dueOn": { + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ] + }, + "report": { + "anyOf": [ + { + "$ref": "#/components/schemas/Report" + }, + { + "type": "null" + } + ] + }, + "blocks": { "type": "array", "items": { - "$ref": "#/components/schemas/Surface" + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" } }, - "parent": { - "type": "string" + "estimate": { + "anyOf": [ + { + "$ref": "#/components/schemas/Size" + }, + { + "type": "null" + } + ] + }, + "sprintId": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" + }, + { + "type": "null" + } + ] } }, "required": [], "additionalProperties": false }, - "View": { + "ViewCreate": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, "name": { "type": "string", "maxLength": 60, "minLength": 1 }, - "owner": { - "$ref": "#/components/schemas/Person" + "layout": { + "type": "string", + "enum": [ + "list", + "board" + ] + }, + "groupBy": { + "$ref": "#/components/schemas/GroupBy" + }, + "filter": { + "$ref": "#/components/schemas/Filter" + }, + "sort": { + "$ref": "#/components/schemas/Sort" }, "shared": { "type": "boolean" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "ViewPatch": { + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 60, + "minLength": 1 }, "layout": { "type": "string", @@ -4585,329 +6020,388 @@ "sort": { "$ref": "#/components/schemas/Sort" }, + "shared": { + "type": "boolean" + }, "position": { "type": "integer" + } + }, + "required": [], + "additionalProperties": false + }, + "Size": { + "type": "string", + "enum": [ + "XS", + "S", + "M", + "L", + "XL" + ], + "description": "Fixed points: XS=1, S=2, M=3, L=5, XL=8; null counts zero." + }, + "SprintState": { + "type": "string", + "enum": [ + "planned", + "active", + "closed" + ] + }, + "Unit": { + "type": "string", + "enum": [ + "points", + "issues" + ], + "default": "points" + }, + "Tally": { + "type": "object", + "properties": { + "scopePoints": { + "type": "integer", + "minimum": 0 }, - "createdAt": { - "type": "string", - "format": "date-time" + "scopeIssues": { + "type": "integer", + "minimum": 0 }, - "updatedAt": { - "type": "string", - "format": "date-time" + "donePoints": { + "type": "integer", + "minimum": 0 + }, + "doneIssues": { + "type": "integer", + "minimum": 0 } }, "required": [ - "id", - "name", - "owner", - "shared", - "layout", - "groupBy", - "filter", - "sort", - "position", - "createdAt", - "updatedAt" + "scopePoints", + "scopeIssues", + "donePoints", + "doneIssues" ], "additionalProperties": false }, - "Error": { + "SprintRef": { "type": "object", "properties": { - "error": { + "id": { "type": "string", - "enum": [ - "invalid", - "unauthenticated", - "forbidden", - "not_found", - "conflict", - "tracker_store_unavailable", - "identity_unavailable" - ] + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, - "message": { + "number": { + "type": "integer", + "minimum": 1 + }, + "name": { "type": "string" }, - "issues": { - "type": "array", - "items": { - "type": "object", - "properties": { - "path": { - "type": "string" - }, - "message": { - "type": "string" - } - }, - "required": [ - "path", - "message" - ], - "additionalProperties": false - } + "state": { + "$ref": "#/components/schemas/SprintState" } }, "required": [ - "error", - "message" + "id", + "number", + "name", + "state" ], "additionalProperties": false }, - "IssueCreate": { + "Sprint": { "type": "object", "properties": { - "title": { + "id": { "type": "string", - "maxLength": 200, - "minLength": 1 + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, - "description": { - "type": "string", - "description": "Markdown, at most 50 KiB UTF-8" + "number": { + "type": "integer", + "minimum": 1 }, - "type": { - "$ref": "#/components/schemas/IssueType" + "name": { + "type": "string" }, - "priority": { - "$ref": "#/components/schemas/Priority" + "state": { + "$ref": "#/components/schemas/SprintState" }, - "statusId": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "goal": { + "type": "string" }, - "assigneeSub": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096, - "minLength": 1 - }, - { - "type": "null" - } + "lengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 ] }, - "labelIds": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } + "startsOn": { + "type": "string", + "format": "date" }, - "projectId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] + "endsOn": { + "type": "string", + "format": "date" }, - "parentId": { + "startedAt": { "anyOf": [ { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "format": "date-time" }, { "type": "null" } ] }, - "dueOn": { + "closedAt": { "anyOf": [ { "type": "string", - "format": "date" + "format": "date-time" }, { "type": "null" } ] }, - "report": { + "current": { + "$ref": "#/components/schemas/Tally" + }, + "commitment": { "anyOf": [ { - "$ref": "#/components/schemas/Report" + "$ref": "#/components/schemas/Tally" }, { "type": "null" } ] + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" } }, "required": [ - "title", - "type" + "id", + "number", + "name", + "state", + "goal", + "lengthWeeks", + "startsOn", + "endsOn", + "startedAt", + "closedAt", + "current", + "commitment", + "createdAt", + "updatedAt" ], "additionalProperties": false }, - "IssuePatch": { + "SprintCreate": { "type": "object", "properties": { - "title": { + "name": { "type": "string", - "maxLength": 200, - "minLength": 1 + "minLength": 1, + "maxLength": 60 }, - "description": { + "goal": { "type": "string", - "description": "Markdown, at most 50 KiB UTF-8" - }, - "type": { - "$ref": "#/components/schemas/IssueType" - }, - "priority": { - "$ref": "#/components/schemas/Priority" + "description": "Valid UTF-8, at most 4096 bytes", + "maxLength": 4096 }, - "statusId": { + "startsOn": { "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + "format": "date" }, - "assigneeSub": { - "anyOf": [ - { - "type": "string", - "maxLength": 4096, - "minLength": 1 - }, - { - "type": "null" - } + "lengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 ] + } + }, + "required": [], + "additionalProperties": false + }, + "SprintPatch": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 60 }, - "labelIds": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } + "goal": { + "type": "string", + "description": "Valid UTF-8, at most 4096 bytes", + "maxLength": 4096 }, - "projectId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } - ] + "startsOn": { + "type": "string", + "format": "date" }, - "parentId": { - "anyOf": [ - { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - }, - { - "type": "null" - } + "lengthWeeks": { + "type": "integer", + "enum": [ + 1, + 2 ] - }, - "dueOn": { + } + }, + "required": [], + "additionalProperties": false + }, + "SprintClose": { + "type": "object", + "properties": { + "moveIncompleteTo": { "anyOf": [ { "type": "string", - "format": "date" - }, - { - "type": "null" - } - ] - }, - "report": { - "anyOf": [ - { - "$ref": "#/components/schemas/Report" + "pattern": "^[0-7][0-9A-HJKMNP-TV-Z]{25}$" }, { "type": "null" } ] - }, - "blocks": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" - } } }, - "required": [], + "required": [ + "moveIncompleteTo" + ], "additionalProperties": false }, - "ViewCreate": { + "BurndownPoint": { "type": "object", "properties": { - "name": { + "day": { "type": "string", - "maxLength": 60, - "minLength": 1 + "format": "date" }, - "layout": { - "type": "string", - "enum": [ - "list", - "board" - ] + "scope": { + "type": "integer", + "minimum": 0 }, - "groupBy": { - "$ref": "#/components/schemas/GroupBy" + "done": { + "type": "integer", + "minimum": 0 }, - "filter": { - "$ref": "#/components/schemas/Filter" + "remaining": { + "type": "integer", + "minimum": 0 }, - "sort": { - "$ref": "#/components/schemas/Sort" + "ideal": { + "type": "number" + } + }, + "required": [ + "day", + "ideal" + ], + "additionalProperties": false, + "description": "Future days omit scope, done, remaining. Ideal is rounded to two decimals and flat on weekends." + }, + "Burndown": { + "type": "object", + "properties": { + "sprint": { + "$ref": "#/components/schemas/SprintRef" }, - "shared": { - "type": "boolean" + "unit": { + "$ref": "#/components/schemas/Unit" + }, + "today": { + "type": "string", + "format": "date" + }, + "points": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BurndownPoint" + } } }, "required": [ - "name" + "sprint", + "unit", + "today", + "points" ], "additionalProperties": false }, - "ViewPatch": { + "VelocityEntry": { "type": "object", "properties": { - "name": { - "type": "string", - "maxLength": 60, - "minLength": 1 + "sprint": { + "$ref": "#/components/schemas/SprintRef" }, - "layout": { - "type": "string", + "lengthWeeks": { + "type": "integer", "enum": [ - "list", - "board" + 1, + 2 ] }, - "groupBy": { - "$ref": "#/components/schemas/GroupBy" - }, - "filter": { - "$ref": "#/components/schemas/Filter" + "committed": { + "type": "integer", + "minimum": 0 }, - "sort": { - "$ref": "#/components/schemas/Sort" + "completed": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "sprint", + "lengthWeeks", + "committed", + "completed" + ], + "additionalProperties": false + }, + "Velocity": { + "type": "object", + "properties": { + "unit": { + "$ref": "#/components/schemas/Unit" }, - "shared": { - "type": "boolean" + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VelocityEntry" + } }, - "position": { - "type": "integer" + "averagePerWeek": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] } }, - "required": [], - "additionalProperties": false + "required": [ + "unit", + "items", + "averagePerWeek" + ], + "additionalProperties": false, + "description": "Most recent limit closed sprints, oldest first. Average of completed/lengthWeeks over the last three closed sprints, rounded to two decimals, or null." } } } diff --git a/cmd/server/internal/api/settings.go b/cmd/server/internal/api/settings.go index 4ee32a7..160df90 100644 --- a/cmd/server/internal/api/settings.go +++ b/cmd/server/internal/api/settings.go @@ -23,13 +23,15 @@ func (a *API) workspacePatch(s *request) (any, int, error) { return nil, 0, err } var input struct { - Key *string `json:"key"` - Name *string `json:"name"` + Key *string `json:"key"` + Name *string `json:"name"` + SprintLengthWeeks *int `json:"sprintLengthWeeks"` + Timezone *string `json:"timezone"` } if err := decode(s, &input); err != nil { return nil, 0, err } - item, err := s.tx.PatchWorkspace(input.Key, input.Name) + item, err := s.tx.PatchWorkspace(input.Key, input.Name, input.SprintLengthWeeks, input.Timezone) return item, 200, err } func (a *API) statusList(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/sprints.go b/cmd/server/internal/api/sprints.go new file mode 100644 index 0000000..9ed9ca1 --- /dev/null +++ b/cmd/server/internal/api/sprints.go @@ -0,0 +1,74 @@ +package api + +import ( + "strconv" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" +) + +func (a *API) sprintList(s *request) (any, int, error) { + if s.r.URL.Query().Has("state") && s.r.URL.Query().Get("state") == "" { + return nil, 0, &domain.FieldError{Path: "state", Message: "State must be planned, active, or closed"} + } + list, err := s.tx.Sprints(s.r.URL.Query().Get("state")) + return items[domain.Sprint]{list}, 200, err +} +func (a *API) sprintGet(s *request) (any, int, error) { + item, err := s.tx.Sprint(s.r.PathValue("id")) + return item, 200, err +} +func (a *API) sprintCreate(s *request) (any, int, error) { + var input store.SprintCreate + if err := decode(s, &input); err != nil { + return nil, 0, err + } + item, err := s.tx.CreateSprint(input) + return item, 201, err +} +func (a *API) sprintPatch(s *request) (any, int, error) { + var input store.SprintPatch + if err := decode(s, &input); err != nil { + return nil, 0, err + } + item, err := s.tx.PatchSprint(s.r.PathValue("id"), input) + return item, 200, err +} +func (a *API) sprintStart(s *request) (any, int, error) { + item, err := s.tx.StartSprint(s.r.PathValue("id")) + return item, 200, err +} +func (a *API) sprintClose(s *request) (any, int, error) { + var input struct { + MoveIncompleteTo store.Field[string] `json:"moveIncompleteTo"` + } + if err := decode(s, &input, "moveIncompleteTo"); err != nil { + return nil, 0, err + } + if !input.MoveIncompleteTo.Present { + return nil, 0, &domain.FieldError{Path: "moveIncompleteTo", Message: "Specify a planned sprint ID or null"} + } + item, err := s.tx.CloseSprint(s.r.PathValue("id"), input.MoveIncompleteTo.Value, s.actor.Person) + return item, 200, err +} +func (a *API) sprintDelete(s *request) (any, int, error) { + return nil, 204, s.tx.DeleteSprint(s.r.PathValue("id"), s.actor) +} +func (a *API) sprintBurndown(s *request) (any, int, error) { + q := s.r.URL.Query() + item, err := s.tx.Burndown(s.r.PathValue("id"), q.Get("unit"), q.Get("project")) + return item, 200, err +} +func (a *API) velocity(s *request) (any, int, error) { + q := s.r.URL.Query() + limit := 8 + if q.Has("limit") { + n, err := strconv.Atoi(q.Get("limit")) + if err != nil || n < 1 || n > 26 { + return nil, 0, &domain.FieldError{Path: "limit", Message: "Limit must be between 1 and 26"} + } + limit = n + } + item, err := s.tx.Velocity(q.Get("unit"), q.Get("project"), limit) + return item, 200, err +} diff --git a/cmd/server/internal/api/sprints_test.go b/cmd/server/internal/api/sprints_test.go new file mode 100644 index 0000000..4103f91 --- /dev/null +++ b/cmd/server/internal/api/sprints_test.go @@ -0,0 +1,197 @@ +package api + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/appthrust/appserver-go/appserver/identity" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestSprintRoutesRequireAuthentication(t *testing.T) { + auth, err := identity.New(identity.Trust{}) + require.NoError(t, err) + handler := New(nil, auth, nil, nil, "test") + for _, route := range []string{"GET /sprints", "POST /sprints", "GET /sprints/id", "PATCH /sprints/id", "DELETE /sprints/id", "POST /sprints/id/start", "POST /sprints/id/close", "GET /sprints/id/burndown", "GET /velocity"} { + method, path, _ := strings.Cut(route, " ") + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest(method, "/api/tracker/v1"+path, nil)) + require.Equal(t, 401, w.Code, route) + } +} +func TestSprintRequestValidationWithoutDatabase(t *testing.T) { + a := &API{} + for _, tc := range []struct { + name, body string + handler endpoint + }{ + {"unknown", `{"extra":true}`, a.sprintCreate}, {"null name", `{"name":null}`, a.sprintCreate}, {"numeric date", `{"startsOn":3}`, a.sprintCreate}, {"string weeks", `{"lengthWeeks":"2"}`, a.sprintPatch}, + {"missing close destination", `{}`, a.sprintClose}, {"bad close type", `{"moveIncompleteTo":3}`, a.sprintClose}, + } { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest("POST", "/", strings.NewReader(tc.body)) + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + _, _, err := tc.handler(&request{r: r, w: w}) + require.Error(t, err) + writeStoreError(w, err) + require.Equal(t, 400, w.Code) + }) + } + for _, limit := range []string{"0", "27", "x", ""} { + r := httptest.NewRequest("GET", "/?limit="+limit, nil) + w := httptest.NewRecorder() + _, _, err := a.velocity(&request{r: r, w: w}) + require.Error(t, err) + writeStoreError(w, err) + require.Equal(t, 400, w.Code) + } +} +func TestOpenAPISprintContract(t *testing.T) { + var doc struct { + Components struct { + Schemas map[string]struct { + Properties map[string]json.RawMessage `json:"properties"` + Required []string `json:"required"` + Enum []string `json:"enum"` + } `json:"schemas"` + } `json:"components"` + } + require.NoError(t, json.Unmarshal(openapiDocument, &doc)) + s := doc.Components.Schemas + for _, name := range []string{"Sprint", "SprintRef", "Tally", "Burndown", "BurndownPoint", "Velocity", "VelocityEntry", "SprintCreate", "SprintPatch", "SprintClose"} { + require.Contains(t, s, name) + } + require.Equal(t, []string{"XS", "S", "M", "L", "XL"}, s["Size"].Enum) + for _, name := range []string{"Issue", "IssueSummary"} { + require.Contains(t, s[name].Required, "estimate") + require.Contains(t, s[name].Required, "sprint") + } + for _, name := range []string{"IssueCreate", "IssuePatch"} { + require.Contains(t, s[name].Properties, "estimate") + require.Contains(t, s[name].Properties, "sprintId") + } + require.ElementsMatch(t, []string{"day", "ideal"}, s["BurndownPoint"].Required) + require.Contains(t, s["Workspace"].Required, "timezone") + require.Contains(t, s["Workspace"].Required, "sprintLengthWeeks") + require.Contains(t, s["Sort"].Enum, "estimate") + require.Contains(t, s["Activity"].Properties, "field") +} +func TestSprintHTTPFlow(t *testing.T) { + h := newHarness(t) + now := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC) + h.database.Now = func() time.Time { return now } + call[any](h, "viewer", "PATCH", "/workspace", map[string]any{"sprintLengthWeeks": 2}, 403) + for _, body := range []map[string]any{{"sprintLengthWeeks": 3}, {"timezone": "Invalid/Zone"}, {"timezone": ""}, {"timezone": "Local"}} { + call[any](h, "admin", "PATCH", "/workspace", body, 400) + } + workspace := call[domain.Workspace](h, "admin", "PATCH", "/workspace", map[string]any{"sprintLengthWeeks": 2, "timezone": "Asia/Tokyo"}, 200) + require.Equal(t, 2, workspace.SprintLengthWeeks) + list := call[items[domain.Sprint]](h, "viewer", "GET", "/sprints", nil, 200) + require.Empty(t, list.Items) + require.NotNil(t, list.Items) + velocity := call[domain.Velocity](h, "viewer", "GET", "/velocity", nil, 200) + require.Nil(t, velocity.AveragePerWeek) + require.NotNil(t, velocity.Items) + s := call[domain.Sprint](h, "viewer", "POST", "/sprints", map[string]any{"startsOn": "2026-11-02", "lengthWeeks": 1, "goal": "Ship charts"}, 201) + require.Equal(t, "Sprint 1", s.Name) + require.Equal(t, "2026-11-08", s.EndsOn) + require.Nil(t, s.Commitment) + s = call[domain.Sprint](h, "viewer", "PATCH", "/sprints/"+s.ID, map[string]any{"name": "Iteration", "goal": "A goal"}, 200) + next := call[domain.Sprint](h, "viewer", "POST", "/sprints", map[string]any{}, 201) + require.Equal(t, "2026-11-09", next.StartsOn) + require.Equal(t, 2, next.LengthWeeks) + call[any](h, "viewer", "POST", "/sprints", map[string]any{"startsOn": "2026-11-08"}, 409) + call[any](h, "viewer", "POST", "/sprints/"+s.ID+"/close", map[string]any{"moveIncompleteTo": nil}, 409) + a := call[domain.Issue](h, "viewer", "POST", "/issues", map[string]any{"title": "Sized", "type": "task", "estimate": "M", "sprintId": s.ID}, 201) + b := call[domain.Issue](h, "viewer", "POST", "/issues", map[string]any{"title": "Unfinished", "type": "task", "estimate": "L", "sprintId": s.ID}, 201) + now = now.Add(time.Minute) + s = call[domain.Sprint](h, "viewer", "POST", "/sprints/"+s.ID+"/start", nil, 200) + require.Equal(t, 8, s.Commitment.ScopePoints) + call[any](h, "viewer", "POST", "/sprints/"+s.ID+"/start", nil, 409) + call[any](h, "viewer", "POST", "/sprints/"+next.ID+"/start", nil, 409) + call[any](h, "viewer", "PATCH", "/sprints/"+s.ID, map[string]any{"lengthWeeks": 2}, 409) + call[any](h, "admin", "DELETE", "/sprints/"+s.ID, nil, 409) + for _, target := range []string{s.ID, "01ARZ3NDEKTSV4RRFFQ69G5FAV", ""} { + call[any](h, "viewer", "POST", "/sprints/"+s.ID+"/close", map[string]any{"moveIncompleteTo": target}, 400) + } + before := call[domain.BurndownResponse](h, "viewer", "GET", "/sprints/"+s.ID+"/burndown", nil, 200) + require.Equal(t, 8, *before.Points[0].Remaining) + statuses := call[items[domain.Status]](h, "viewer", "GET", "/statuses", nil, 200) + var done string + for _, status := range statuses.Items { + if status.Category == "completed" { + done = status.ID + } + } + now = now.Add(time.Hour) + call[domain.Issue](h, "viewer", "PATCH", "/issues/"+a.ID, map[string]any{"statusId": done}, 200) + chart := call[domain.BurndownResponse](h, "viewer", "GET", "/sprints/"+s.ID+"/burndown?unit=points", nil, 200) + require.Equal(t, 5, *chart.Points[0].Remaining) + require.Nil(t, chart.Points[1].Scope) + now = now.Add(time.Hour) + s = call[domain.Sprint](h, "viewer", "POST", "/sprints/"+s.ID+"/close", map[string]any{"moveIncompleteTo": next.ID}, 200) + require.Equal(t, "closed", s.State) + require.Equal(t, 3, s.Current.DonePoints) + b = call[domain.Issue](h, "viewer", "GET", "/issues/"+b.ID, nil, 200) + require.Equal(t, next.ID, b.Sprint.ID) + a = call[domain.Issue](h, "viewer", "GET", "/issues/"+a.ID, nil, 200) + require.Equal(t, s.ID, a.Sprint.ID) + call[any](h, "viewer", "PATCH", "/issues/"+a.ID, map[string]any{"sprintId": nil}, 400) + call[any](h, "viewer", "PATCH", "/issues/"+a.ID, map[string]any{"sprintId": s.ID}, 400) + velocity = call[domain.Velocity](h, "viewer", "GET", "/velocity?unit=points&limit=1", nil, 200) + require.Len(t, velocity.Items, 1) + require.Equal(t, 3.0, *velocity.AveragePerWeek) + got := call[domain.Sprint](h, "viewer", "GET", "/sprints/"+s.ID, nil, 200) + require.Equal(t, s, got) + call[any](h, "viewer", "DELETE", "/sprints/"+next.ID, nil, 403) + call[any](h, "admin", "DELETE", "/sprints/"+next.ID, nil, 204) + b = call[domain.Issue](h, "viewer", "GET", "/issues/"+b.ID, nil, 200) + require.Nil(t, b.Sprint) + call[any](h, "viewer", "GET", "/sprints/"+next.ID, nil, 404) + for name, v := range map[string]any{"Sprint": s, "Burndown": chart, "Velocity": velocity} { + data, err := json.Marshal(v) + require.NoError(t, err) + t.Logf("%s JSON: %s", name, data) + } +} +func TestSprintHTTPValidation(t *testing.T) { + h := newHarness(t) + for _, body := range []map[string]any{{"name": ""}, {"goal": strings.Repeat("a", 4097)}, {"lengthWeeks": 0}, {"lengthWeeks": 3}, {"startsOn": "2026-02-30"}} { + call[any](h, "viewer", "POST", "/sprints", body, 400) + } + for _, path := range []string{"/sprints?state=bad", "/velocity?unit=bad", "/velocity?project=bad", "/velocity?limit=0", "/velocity?limit=27"} { + call[any](h, "viewer", "GET", path, nil, 400) + } + s := call[domain.Sprint](h, "viewer", "POST", "/sprints", map[string]any{}, 201) + call[any](h, "viewer", "GET", "/sprints/"+s.ID+"/burndown?unit=bad", nil, 400) + call[any](h, "viewer", "GET", "/sprints/"+s.ID+"/burndown?project=bad", nil, 400) + for _, body := range []map[string]any{{"estimate": "XXL"}, {"estimate": 3}, {"sprintId": "missing"}, {"type": "epic", "estimate": "M"}, {"type": "epic", "sprintId": s.ID}} { + body["title"] = "Invalid" + if _, ok := body["type"]; !ok { + body["type"] = "task" + } + call[any](h, "viewer", "POST", "/issues", body, 400) + } + issue := call[domain.Issue](h, "viewer", "POST", "/issues", map[string]any{"title": "Size", "type": "task", "estimate": "XS", "sprintId": s.ID}, 201) + require.Equal(t, "XS", *issue.Estimate) + issue = call[domain.Issue](h, "viewer", "PATCH", "/issues/"+issue.ID, map[string]any{"estimate": nil, "sprintId": nil}, 200) + require.Nil(t, issue.Estimate) + require.Nil(t, issue.Sprint) + timeline := call[items[domain.TimelineItem]](h, "viewer", "GET", "/issues/"+issue.ID+"/timeline", nil, 200) + fields := map[string]bool{} + for _, item := range timeline.Items { + if item.Activity != nil { + fields[item.Activity.Field] = true + } + } + require.True(t, fields["estimate"]) + require.True(t, fields["sprint"]) + view := call[domain.View](h, "viewer", "POST", "/views", map[string]any{"name": "Sprint", "groupBy": "sprint", "sort": "estimate", "filter": domain.Filter{Sprint: []string{"active", "none", s.ID}}}, 201) + require.Equal(t, "sprint", view.GroupBy) + require.Equal(t, domain.SortEstimate, view.Sort) +} diff --git a/cmd/server/internal/domain/rules.go b/cmd/server/internal/domain/rules.go index 9450036..a395929 100644 --- a/cmd/server/internal/domain/rules.go +++ b/cmd/server/internal/domain/rules.go @@ -178,6 +178,9 @@ func ValidateIssue(issue Issue) error { return errors.New("Due date must be YYYY-MM-DD") } } + if issue.Estimate != nil && (SizePoints(*issue.Estimate) == 0 || issue.Type == "epic") { + return &FieldError{Path: "estimate", Message: "Estimate must be XS, S, M, L, or XL and is not allowed on epics"} + } return ValidateReport(issue.Type, issue.Report) } @@ -226,6 +229,11 @@ func ValidateFilter(filter Filter) error { return errors.New("Invalid project filter") } } + for _, id := range filter.Sprint { + if id != "none" && id != "active" && !ValidID(id) { + return &FieldError{Path: "filter.sprint", Message: "Sprint filter must contain sprint IDs, active, or none"} + } + } for _, field := range []struct { name string ids []string @@ -268,7 +276,7 @@ func ValidateFilter(filter Filter) error { return nil } func ValidSort(sort Sort) bool { - return sort == SortUpdated || sort == SortCreated || sort == SortPriority || sort == SortNumber + return sort == SortUpdated || sort == SortCreated || sort == SortPriority || sort == SortNumber || sort == SortEstimate } func ValidateView(view View) error { if !Text(view.Name, 1, 60) { @@ -277,8 +285,8 @@ func ValidateView(view View) error { if view.Layout != "list" && view.Layout != "board" { return errors.New("Layout must be list or board") } - if view.GroupBy != "none" && view.GroupBy != "epic" && view.GroupBy != "story" { - return &FieldError{Path: "groupBy", Message: "Group by must be none, epic, or story"} + if view.GroupBy != "none" && view.GroupBy != "epic" && view.GroupBy != "story" && view.GroupBy != "sprint" { + return &FieldError{Path: "groupBy", Message: "Group by must be none, epic, story, or sprint"} } if !ValidSort(view.Sort) { return errors.New("Invalid sort") diff --git a/cmd/server/internal/domain/sprint.go b/cmd/server/internal/domain/sprint.go new file mode 100644 index 0000000..f10fd2d --- /dev/null +++ b/cmd/server/internal/domain/sprint.go @@ -0,0 +1,157 @@ +package domain + +import ( + "errors" + "math" + "time" +) + +// SizePoints is a fixed scale: changing it would invalidate ledger history. +func SizePoints(size string) int { + switch size { + case "XS": + return 1 + case "S": + return 2 + case "M": + return 3 + case "L": + return 5 + case "XL": + return 8 + default: + return 0 + } +} + +type SprintStanding struct { + SprintID string + Size string + Category string + Deleted bool +} +type SprintTally = Tally + +type SprintEvent struct { + At time.Time + SprintTally +} +type Date = time.Time +type SprintSpan struct{ StartsOn, EndsOn Date } + +// Day supplies all clock, timezone and unit decisions to the pure calculation. +// Until is exclusive. Events must be ordered by At and days by Date. +type Day struct { + Date Date + Until time.Time + Future bool + Unit string +} + +func Contribution(s SprintStanding) SprintTally { + if s.SprintID == "" || s.Deleted || s.Category == "canceled" { + return SprintTally{} + } + tally := SprintTally{ScopePoints: SizePoints(s.Size), ScopeIssues: 1} + if s.Category == "completed" { + tally.DonePoints, tally.DoneIssues = tally.ScopePoints, 1 + } + return tally +} +func SprintDeltas(before, after SprintStanding) map[string]SprintTally { + old, next := Contribution(before), Contribution(after) + deltas := make(map[string]SprintTally, 2) + if before.SprintID != "" { + deltas[before.SprintID] = SprintTally{-old.ScopePoints, -old.ScopeIssues, -old.DonePoints, -old.DoneIssues} + } + if after.SprintID != "" { + d := deltas[after.SprintID] + d.ScopePoints += next.ScopePoints + d.ScopeIssues += next.ScopeIssues + d.DonePoints += next.DonePoints + d.DoneIssues += next.DoneIssues + deltas[after.SprintID] = d + } + for id, d := range deltas { + if d == (SprintTally{}) { + delete(deltas, id) + } + } + return deltas +} + +func Burndown(baseline SprintTally, events []SprintEvent, days []Day) []BurndownPoint { + points := make([]BurndownPoint, 0, len(days)) + steps := 0 + for i, day := range days { + if i > 0 && weekday(day.Date) { + steps++ + } + } + elapsed, event := 0, 0 + var tally SprintTally + for i, day := range days { + if i > 0 && weekday(day.Date) { + elapsed++ + } + remaining := baseline.ScopePoints - baseline.DonePoints + if day.Unit == "issues" { + remaining = baseline.ScopeIssues - baseline.DoneIssues + } + ideal := float64(remaining) + if steps > 0 { + ideal *= float64(steps-elapsed) / float64(steps) + } + ideal = math.Round(ideal*100) / 100 + point := BurndownPoint{Day: day.Date.Format("2006-01-02"), Ideal: ideal} + if !day.Future { + for event < len(events) && events[event].At.Before(day.Until) { + d := events[event].SprintTally + tally.ScopePoints += d.ScopePoints + tally.ScopeIssues += d.ScopeIssues + tally.DonePoints += d.DonePoints + tally.DoneIssues += d.DoneIssues + event++ + } + scope, done := tally.ScopePoints, tally.DonePoints + if day.Unit == "issues" { + scope, done = tally.ScopeIssues, tally.DoneIssues + } + rest := scope - done + point.Scope, point.Done, point.Remaining = &scope, &done, &rest + } + points = append(points, point) + } + return points +} +func weekday(date Date) bool { return date.Weekday() != time.Saturday && date.Weekday() != time.Sunday } + +var ErrSprintOverlap = errors.New("Sprint dates overlap another non-closed sprint") + +func ValidateSprintDates(startsOn Date, lengthWeeks int, others []SprintSpan) error { + if startsOn.IsZero() { + return &FieldError{Path: "startsOn", Message: "Start date must be YYYY-MM-DD"} + } + if lengthWeeks != 1 && lengthWeeks != 2 { + return &FieldError{Path: "lengthWeeks", Message: "Sprint length must be 1 or 2 weeks"} + } + endsOn := startsOn.AddDate(0, 0, 7*lengthWeeks-1) + for _, other := range others { + if !startsOn.After(other.EndsOn) && !endsOn.Before(other.StartsOn) { + return ErrSprintOverlap + } + } + return nil +} +func ValidateMembership(issueType string, sprintState string, lineageMembers int) error { + if issueType == "epic" { + return &FieldError{Path: "sprintId", Message: "Epics cannot belong to a sprint"} + } + if sprintState != "planned" && sprintState != "active" { + return &FieldError{Path: "sprintId", Message: "Sprint must be planned or active in this workspace"} + } + if lineageMembers != 0 { + return &FieldError{Path: "sprintId", Message: "An ancestor or descendant already belongs to this sprint"} + } + return nil +} diff --git a/cmd/server/internal/domain/sprint_test.go b/cmd/server/internal/domain/sprint_test.go new file mode 100644 index 0000000..6e4d4ed --- /dev/null +++ b/cmd/server/internal/domain/sprint_test.go @@ -0,0 +1,194 @@ +package domain + +import ( + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestSizePoints(t *testing.T) { + for _, tc := range []struct { + size string + points int + }{{"XS", 1}, {"S", 2}, {"M", 3}, {"L", 5}, {"XL", 8}, {"", 0}, {"3", 0}, {"xxl", 0}} { + t.Run(tc.size, func(t *testing.T) { require.Equal(t, tc.points, SizePoints(tc.size)) }) + } +} +func TestContribution(t *testing.T) { + for _, tc := range []struct { + name string + standing SprintStanding + want SprintTally + }{ + {"unassigned", SprintStanding{Size: "XL", Category: "completed"}, SprintTally{}}, + {"unestimated", SprintStanding{SprintID: "s", Category: "backlog"}, SprintTally{ScopeIssues: 1}}, + {"open", SprintStanding{SprintID: "s", Size: "M", Category: "started"}, SprintTally{ScopePoints: 3, ScopeIssues: 1}}, + {"done", SprintStanding{SprintID: "s", Size: "L", Category: "completed"}, SprintTally{5, 1, 5, 1}}, + {"canceled", SprintStanding{SprintID: "s", Size: "XL", Category: "canceled"}, SprintTally{}}, + {"deleted", SprintStanding{SprintID: "s", Size: "M", Category: "completed", Deleted: true}, SprintTally{}}, + } { + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.want, Contribution(tc.standing)) }) + } +} +func TestSprintDeltas(t *testing.T) { + open := SprintStanding{SprintID: "a", Size: "M", Category: "started"} + done := open + done.Category = "completed" + cancel := open + cancel.Category = "canceled" + deleted := done + deleted.Deleted = true + bigger := open + bigger.Size = "XL" + moved := open + moved.SprintID = "b" + for _, tc := range []struct { + name string + before, after SprintStanding + want map[string]SprintTally + }{ + {"join", SprintStanding{}, open, map[string]SprintTally{"a": {3, 1, 0, 0}}}, + {"move", open, moved, map[string]SprintTally{"a": {-3, -1, 0, 0}, "b": {3, 1, 0, 0}}}, + {"estimate", open, bigger, map[string]SprintTally{"a": {5, 0, 0, 0}}}, + {"complete", open, done, map[string]SprintTally{"a": {0, 0, 3, 1}}}, + {"reopen", done, open, map[string]SprintTally{"a": {0, 0, -3, -1}}}, + {"cancel", open, cancel, map[string]SprintTally{"a": {-3, -1, 0, 0}}}, + {"uncancel", cancel, open, map[string]SprintTally{"a": {3, 1, 0, 0}}}, + {"delete", done, deleted, map[string]SprintTally{"a": {-3, -1, -3, -1}}}, + {"clear", open, SprintStanding{}, map[string]SprintTally{"a": {-3, -1, 0, 0}}}, + {"unchanged", open, open, map[string]SprintTally{}}, + {"empty", SprintStanding{}, SprintStanding{}, map[string]SprintTally{}}, + } { + t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.want, SprintDeltas(tc.before, tc.after)) }) + } +} +func sprintDate(s string) time.Time { + v, err := time.Parse("2006-01-02", s) + if err != nil { + panic(err) + } + return v +} +func TestValidateSprintDates(t *testing.T) { + for _, tc := range []struct { + name, start string + weeks int + others []SprintSpan + valid bool + }{ + {"one week", "2026-11-02", 1, nil, true}, + {"two weeks", "2026-11-02", 2, nil, true}, + {"invalid length", "2026-11-02", 3, nil, false}, + {"zero length", "2026-11-02", 0, nil, false}, + {"adjacent one week", "2026-11-02", 1, []SprintSpan{{sprintDate("2026-11-09"), sprintDate("2026-11-15")}}, true}, + {"inclusive overlap", "2026-11-02", 1, []SprintSpan{{sprintDate("2026-11-08"), sprintDate("2026-11-14")}}, false}, + {"two week overlap", "2026-11-02", 2, []SprintSpan{{sprintDate("2026-11-09"), sprintDate("2026-11-15")}}, false}, + {"adjacent two weeks", "2026-11-02", 2, []SprintSpan{{sprintDate("2026-11-16"), sprintDate("2026-11-22")}}, true}, + {"contained", "2026-11-02", 1, []SprintSpan{{sprintDate("2026-11-01"), sprintDate("2026-11-15")}}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.valid, ValidateSprintDates(sprintDate(tc.start), tc.weeks, tc.others) == nil) + }) + } + require.Error(t, ValidateSprintDates(time.Time{}, 1, nil)) +} +func TestValidateMembership(t *testing.T) { + for _, tc := range []struct { + kind, state string + lineage int + valid bool + }{ + {"story", "planned", 0, true}, {"task", "active", 0, true}, {"bug", "planned", 0, true}, + {"epic", "active", 0, false}, {"task", "closed", 0, false}, {"task", "", 0, false}, + {"story", "active", 1, false}, {"task", "planned", 2, false}, + } { + err := ValidateMembership(tc.kind, tc.state, tc.lineage) + require.Equal(t, tc.valid, err == nil) + if err != nil { + require.Equal(t, "sprintId", err.(*FieldError).Path) + } + } +} +func TestBurndown(t *testing.T) { + start := sprintDate("2026-11-06") // Friday + events := []SprintEvent{ + {start.Add(-time.Hour), SprintTally{10, 3, 0, 0}}, + {start.AddDate(0, 0, 1).Add(time.Hour), SprintTally{0, 0, 3, 1}}, + {start.AddDate(0, 0, 2).Add(time.Hour), SprintTally{5, 1, 0, 0}}, + {start.AddDate(0, 0, 3).Add(time.Hour), SprintTally{-2, -1, 0, 0}}, + } + for _, unit := range []string{"points", "issues"} { + t.Run(unit, func(t *testing.T) { + days := make([]Day, 7) + for i := range days { + date := start.AddDate(0, 0, i) + days[i] = Day{Date: date, Until: date.AddDate(0, 0, 1), Future: i > 3, Unit: unit} + } + points := Burndown(SprintTally{10, 3, 0, 0}, events, days) + require.Len(t, points, 7) + if unit == "points" { + require.Equal(t, 10, *points[0].Remaining) + require.Equal(t, 7, *points[1].Remaining) + require.Equal(t, 15, *points[2].Scope) + require.Equal(t, 10, *points[3].Remaining) + require.Equal(t, 10.0, points[0].Ideal) + require.Equal(t, 10.0, points[1].Ideal) + require.Equal(t, 10.0, points[2].Ideal) + require.Equal(t, 7.5, points[3].Ideal) + } else { + require.Equal(t, 3, *points[0].Scope) + require.Equal(t, 1, *points[1].Done) + require.Equal(t, 2, *points[3].Remaining) + } + require.Zero(t, points[6].Ideal) + for _, p := range points[4:] { + require.Nil(t, p.Scope) + require.Nil(t, p.Done) + require.Nil(t, p.Remaining) + raw, err := json.Marshal(p) + require.NoError(t, err) + require.NotContains(t, string(raw), "remaining") + } + }) + } + require.Empty(t, Burndown(SprintTally{}, nil, nil)) +} +func TestBurndownTwoWeeksRounding(t *testing.T) { + start := sprintDate("2026-11-02") + days := make([]Day, 14) + for i := range days { + d := start.AddDate(0, 0, i) + days[i] = Day{Date: d, Until: d.AddDate(0, 0, 1)} + } + points := Burndown(SprintTally{ScopePoints: 10}, nil, days) + require.Equal(t, 8.89, points[1].Ideal) + require.Equal(t, points[4].Ideal, points[5].Ideal) + require.Equal(t, points[5].Ideal, points[6].Ideal) + require.Zero(t, points[11].Ideal) + require.Zero(t, points[12].Ideal) + require.Zero(t, points[13].Ideal) +} +func TestSprintFilterAndEstimateValidation(t *testing.T) { + for _, value := range []string{"active", "none", "01ARZ3NDEKTSV4RRFFQ69G5FAV"} { + require.NoError(t, ValidateFilter(Filter{Sprint: []string{value}})) + } + for _, value := range []string{"", "me", "bad"} { + err := ValidateFilter(Filter{Sprint: []string{value}}) + require.Error(t, err) + require.Equal(t, "filter.sprint", err.(*FieldError).Path) + } + require.True(t, ValidSort(SortEstimate)) + require.NoError(t, ValidateView(View{Name: "Sprint", Layout: "board", GroupBy: "sprint", Sort: SortEstimate})) + for _, tc := range []struct { + kind, size string + valid bool + }{{"task", "XS", true}, {"story", "XL", true}, {"epic", "M", false}, {"task", "3", false}, {"task", "", false}} { + err := ValidateIssue(Issue{IssueSummary: IssueSummary{Title: "Work", Type: tc.kind, Priority: "none", Estimate: &tc.size}}) + require.Equal(t, tc.valid, err == nil) + if err != nil { + require.Equal(t, "estimate", err.(*FieldError).Path) + } + } +} diff --git a/cmd/server/internal/domain/types.go b/cmd/server/internal/domain/types.go index 8b6ecd0..2bde4de 100644 --- a/cmd/server/internal/domain/types.go +++ b/cmd/server/internal/domain/types.go @@ -15,12 +15,14 @@ type Actor struct { Role string } type Workspace struct { - ID string `json:"id"` - Key string `json:"key"` - Name string `json:"name"` - IssueCount int `json:"issueCount"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` + ID string `json:"id"` + Key string `json:"key"` + Name string `json:"name"` + IssueCount int `json:"issueCount"` + SprintLengthWeeks int `json:"sprintLengthWeeks"` + Timezone string `json:"timezone"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` } type Status struct { ID string `json:"id"` @@ -60,6 +62,11 @@ type IssueRef struct { StatusID string `json:"statusId"` } type Progress struct { + Total int `json:"total"` + Completed int `json:"completed"` + Points ProgressPoints `json:"points"` +} +type ProgressPoints struct { Total int `json:"total"` Completed int `json:"completed"` } @@ -75,6 +82,8 @@ type IssueSummary struct { Reporter Person `json:"reporter"` LabelIDs []string `json:"labelIds"` ProjectID *string `json:"projectId"` + Estimate *string `json:"estimate"` + Sprint *SprintRef `json:"sprint"` Parent *IssueRef `json:"parent"` Epic *IssueRef `json:"epic"` Story *IssueRef `json:"story"` @@ -133,6 +142,7 @@ type Filter struct { Reporter []string `json:"reporter,omitempty"` Label []string `json:"label,omitempty"` Project []string `json:"project,omitempty"` + Sprint []string `json:"sprint,omitempty"` Epic []string `json:"epic,omitempty"` Story []string `json:"story,omitempty"` Type []string `json:"type,omitempty"` @@ -150,6 +160,7 @@ const ( SortCreated Sort = "created" SortPriority Sort = "priority" SortNumber Sort = "number" + SortEstimate Sort = "estimate" ) type View struct { @@ -165,3 +176,55 @@ type View struct { CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } + +type Tally struct { + ScopePoints int `json:"scopePoints"` + ScopeIssues int `json:"scopeIssues"` + DonePoints int `json:"donePoints"` + DoneIssues int `json:"doneIssues"` +} +type SprintRef struct { + ID string `json:"id"` + Number int64 `json:"number"` + Name string `json:"name"` + State string `json:"state"` +} +type Sprint struct { + SprintRef + Goal string `json:"goal"` + LengthWeeks int `json:"lengthWeeks"` + StartsOn string `json:"startsOn"` + EndsOn string `json:"endsOn"` + StartedAt *time.Time `json:"startedAt"` + ClosedAt *time.Time `json:"closedAt"` + Current Tally `json:"current"` + Commitment *Tally `json:"commitment"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} +type BurndownPoint struct { + Day string `json:"day"` + Scope *int `json:"scope,omitempty"` + Done *int `json:"done,omitempty"` + Remaining *int `json:"remaining,omitempty"` + Ideal float64 `json:"ideal"` +} + +// BurndownResponse is the wire shape; Burndown is the pure calculation. +type BurndownResponse struct { + Sprint SprintRef `json:"sprint"` + Unit string `json:"unit"` + Today string `json:"today"` + Points []BurndownPoint `json:"points"` +} +type VelocityEntry struct { + Sprint SprintRef `json:"sprint"` + LengthWeeks int `json:"lengthWeeks"` + Committed int `json:"committed"` + Completed int `json:"completed"` +} +type Velocity struct { + Unit string `json:"unit"` + Items []VelocityEntry `json:"items"` + AveragePerWeek *float64 `json:"averagePerWeek"` +} diff --git a/cmd/server/internal/store/hierarchy_test.go b/cmd/server/internal/store/hierarchy_test.go index acabfc0..36abbad 100644 --- a/cmd/server/internal/store/hierarchy_test.go +++ b/cmd/server/internal/store/hierarchy_test.go @@ -243,13 +243,13 @@ func TestHierarchySeed(t *testing.T) { require.NoError(t, database.InWorkspace(t.Context(), "seed", false, func(tx *Tx) error { page, err := tx.ListIssues(ListOptions{Sort: domain.SortNumber}) require.NoError(t, err) - require.Len(t, page.Items, 36) + require.Len(t, page.Items, 40) epics, stories := page.Items[30:32], page.Items[32:36] require.Equal(t, "Reliable bug intake", epics[0].Title) require.Equal(t, "Faster triage", epics[1].Title) statuses, err := tx.Statuses() require.NoError(t, err) - for _, item := range page.Items[30:] { + for _, item := range page.Items[30:36] { require.Equal(t, statuses[2].ID, item.StatusID) require.Nil(t, item.Report) require.NotNil(t, item.Progress) diff --git a/cmd/server/internal/store/issues_read.go b/cmd/server/internal/store/issues_read.go index 4a53973..ae949f5 100644 --- a/cmd/server/internal/store/issues_read.go +++ b/cmd/server/internal/store/issues_read.go @@ -19,7 +19,8 @@ const issueColumns = `i.id,w.key,i.number,i.title,i.type,i.priority,i.status_id, to_char(i.due_on,'YYYY-MM-DD'),i.report, (SELECT count(*) FROM tracker_comment c WHERE c.issue_id=i.id AND c.deleted_at IS NULL), (SELECT count(*) FROM tracker_attachment a WHERE a.issue_id=i.id),i.created_at,i.updated_at,i.completed_at,i.project_id, - lineage.epic,lineage.story,rollup.progress` + lineage.epic,lineage.story,rollup.progress,i.estimate, + (SELECT jsonb_build_object('id',sp.id,'number',sp.number,'name',sp.name,'state',CASE WHEN sp.closed_at IS NOT NULL THEN 'closed' WHEN sp.started_at IS NOT NULL THEN 'active' ELSE 'planned' END) FROM tracker_sprint sp WHERE sp.id=i.sprint_id)` const issueFrom = ` FROM tracker_issue i JOIN tracker_workspace w ON w.id=i.workspace_id JOIN tracker_status s ON s.id=i.status_id ` // Lateral recursive queries keep detail and list projections identical without @@ -44,19 +45,23 @@ const issueHierarchy = ` ) lineage ON true LEFT JOIN LATERAL ( WITH RECURSIVE descendants AS ( - SELECT c.id,c.type,c.status_id FROM tracker_issue c + SELECT c.id,c.type,c.status_id,c.estimate FROM tracker_issue c WHERE i.type IN ('epic','story') AND c.workspace_id=i.workspace_id AND c.parent_id=i.id AND c.deleted_at IS NULL UNION - SELECT c.id,c.type,c.status_id FROM tracker_issue c JOIN descendants d ON c.parent_id=d.id + SELECT c.id,c.type,c.status_id,c.estimate FROM tracker_issue c JOIN descendants d ON c.parent_id=d.id WHERE c.workspace_id=i.workspace_id AND c.deleted_at IS NULL ) SELECT CASE WHEN i.type IN ('epic','story') THEN jsonb_build_object( 'total',count(*) FILTER (WHERE s.category<>'canceled'), - 'completed',count(*) FILTER (WHERE s.category='completed')) END AS progress + 'completed',count(*) FILTER (WHERE s.category='completed'), + 'points',jsonb_build_object( + 'total',coalesce(sum(CASE d.estimate WHEN 'XS' THEN 1 WHEN 'S' THEN 2 WHEN 'M' THEN 3 WHEN 'L' THEN 5 WHEN 'XL' THEN 8 ELSE 0 END) FILTER (WHERE s.category<>'canceled'),0), + 'completed',coalesce(sum(CASE d.estimate WHEN 'XS' THEN 1 WHEN 'S' THEN 2 WHEN 'M' THEN 3 WHEN 'L' THEN 5 WHEN 'XL' THEN 8 ELSE 0 END) FILTER (WHERE s.category='completed'),0))) END AS progress FROM descendants d JOIN tracker_status s ON s.id=d.status_id WHERE d.type NOT IN ('epic','story') ) rollup ON true ` const prioritySQL = `(CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END)` +const estimateSQL = `(CASE i.estimate WHEN 'XL' THEN 0 WHEN 'L' THEN 1 WHEN 'M' THEN 2 WHEN 'S' THEN 3 WHEN 'XS' THEN 4 ELSE 5 END)` type scanner interface{ Scan(...any) error } @@ -64,12 +69,12 @@ func scanIssue(row scanner) (domain.Issue, error) { var item domain.Issue var key string var sub, name, due sql.NullString - var parent, report, epic, story, progress []byte + var parent, report, epic, story, progress, sprint []byte item.LabelIDs = []string{} item.Children = []domain.IssueRef{} item.Blocks = []domain.IssueRef{} item.BlockedBy = []domain.IssueRef{} - err := row.Scan(&item.ID, &key, &item.Number, &item.Title, &item.Type, &item.Priority, &item.StatusID, &sub, &name, &item.Reporter.Sub, &item.Reporter.Name, pq.Array(&item.LabelIDs), &parent, &due, &report, &item.CommentCount, &item.AttachmentCount, &item.CreatedAt, &item.UpdatedAt, &item.CompletedAt, &item.ProjectID, &epic, &story, &progress, &item.Description) + err := row.Scan(&item.ID, &key, &item.Number, &item.Title, &item.Type, &item.Priority, &item.StatusID, &sub, &name, &item.Reporter.Sub, &item.Reporter.Name, pq.Array(&item.LabelIDs), &parent, &due, &report, &item.CommentCount, &item.AttachmentCount, &item.CreatedAt, &item.UpdatedAt, &item.CompletedAt, &item.ProjectID, &epic, &story, &progress, &item.Estimate, &sprint, &item.Description) if err != nil { return item, err } @@ -83,7 +88,7 @@ func scanIssue(row scanner) (domain.Issue, error) { for _, field := range []struct { data []byte target any - }{{parent, &item.Parent}, {report, &item.Report}, {epic, &item.Epic}, {story, &item.Story}, {progress, &item.Progress}} { + }{{parent, &item.Parent}, {report, &item.Report}, {epic, &item.Epic}, {story, &item.Story}, {progress, &item.Progress}, {sprint, &item.Sprint}} { if len(field.data) > 0 { if err := json.Unmarshal(field.data, field.target); err != nil { return item, err @@ -165,12 +170,13 @@ type issueCursor struct { At time.Time `json:"at"` Number int64 `json:"number"` Priority int `json:"priority"` + Estimate int `json:"estimate"` } func parseCursor(raw string, sort domain.Sort) (issueCursor, error) { var cursor issueCursor data, err := base64.RawURLEncoding.DecodeString(raw) - if err != nil || json.Unmarshal(data, &cursor) != nil || cursor.Sort != sort || !domain.ValidID(cursor.ID) || cursor.At.IsZero() || cursor.Number < 1 || cursor.Priority < 0 || cursor.Priority > 4 { + if err != nil || json.Unmarshal(data, &cursor) != nil || cursor.Sort != sort || !domain.ValidID(cursor.ID) || cursor.At.IsZero() || cursor.Number < 1 || cursor.Priority < 0 || cursor.Priority > 4 || cursor.Estimate < 0 || cursor.Estimate > 5 { return cursor, invalid("Invalid cursor") } return cursor, nil @@ -246,6 +252,16 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { } clauses = append(clauses, "("+condition+")") } + if len(f.Sprint) > 0 { + condition := "i.sprint_id=ANY(" + bind(pq.Array(f.Sprint)) + ")" + if slices.Contains(f.Sprint, "none") { + condition += " OR i.sprint_id IS NULL" + } + if slices.Contains(f.Sprint, "active") { + condition += " OR i.sprint_id IN (SELECT id FROM tracker_sprint WHERE workspace_id=i.workspace_id AND started_at IS NOT NULL AND closed_at IS NULL)" + } + clauses = append(clauses, "("+condition+")") + } for _, field := range []struct { column string values []string @@ -278,6 +294,8 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { order = prioritySQL + " ASC,i.updated_at DESC,i.id DESC" case domain.SortNumber: order = "i.number ASC,i.id ASC" + case domain.SortEstimate: + order = estimateSQL + " ASC,i.updated_at DESC,i.id DESC" } if options.Cursor != "" { c, err := parseCursor(options.Cursor, options.Sort) @@ -290,6 +308,9 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { case domain.SortPriority: p, at, id := bind(c.Priority), bind(c.At), bind(c.ID) clauses = append(clauses, "("+prioritySQL+">"+p+" OR ("+prioritySQL+"="+p+" AND (i.updated_at,i.id)<("+at+","+id+")))") + case domain.SortEstimate: + size, at, id := bind(c.Estimate), bind(c.At), bind(c.ID) + clauses = append(clauses, "("+estimateSQL+">"+size+" OR ("+estimateSQL+"="+size+" AND (i.updated_at,i.id)<("+at+","+id+")))") default: column := "i.updated_at" if options.Sort == domain.SortCreated { @@ -328,7 +349,11 @@ func (t *Tx) ListIssues(options ListOptions) (Page, error) { break } } - data, err := json.Marshal(issueCursor{Sort: options.Sort, ID: last.ID, At: at, Number: last.Number, Priority: priority}) + estimate := 5 + if last.Estimate != nil { + estimate = slices.Index([]string{"XL", "L", "M", "S", "XS"}, *last.Estimate) + } + data, err := json.Marshal(issueCursor{Sort: options.Sort, ID: last.ID, At: at, Number: last.Number, Priority: priority, Estimate: estimate}) if err != nil { return page, err } diff --git a/cmd/server/internal/store/issues_write.go b/cmd/server/internal/store/issues_write.go index 12a8edb..db43606 100644 --- a/cmd/server/internal/store/issues_write.go +++ b/cmd/server/internal/store/issues_write.go @@ -6,7 +6,6 @@ import ( "reflect" "slices" "strings" - "time" "github.com/appthrust/appserver-go/appserver/httpx" "github.com/appthrust/tracker/cmd/server/internal/domain" @@ -35,6 +34,8 @@ type IssueCreate struct { AssigneeSub *string `json:"assigneeSub"` LabelIDs []string `json:"labelIds"` ProjectID *string `json:"projectId"` + Estimate *string `json:"estimate"` + SprintID *string `json:"sprintId"` ParentID *string `json:"parentId"` DueOn *string `json:"dueOn"` Report *domain.Report `json:"report"` @@ -48,6 +49,8 @@ type IssuePatch struct { AssigneeSub Field[string] `json:"assigneeSub"` LabelIDs Field[[]string] `json:"labelIds"` ProjectID Field[string] `json:"projectId"` + Estimate Field[string] `json:"estimate"` + SprintID Field[string] `json:"sprintId"` ParentID Field[string] `json:"parentId"` Blocks Field[[]string] `json:"blocks"` DueOn Field[string] `json:"dueOn"` @@ -183,11 +186,14 @@ func (t *Tx) replaceBlocks(id string, ids []string) ([]domain.IssueRef, error) { return items, nil } func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domain.Person) (domain.Issue, error) { - item := domain.Issue{IssueSummary: domain.IssueSummary{ID: ulid.Make().String(), Title: strings.TrimSpace(input.Title), Type: input.Type, Priority: input.Priority, StatusID: input.StatusID, Assignee: assignee, Reporter: actor, ProjectID: input.ProjectID, DueOn: input.DueOn, Report: input.Report}, Description: input.Description} + item := domain.Issue{IssueSummary: domain.IssueSummary{ID: ulid.Make().String(), Title: strings.TrimSpace(input.Title), Type: input.Type, Priority: input.Priority, StatusID: input.StatusID, Assignee: assignee, Reporter: actor, ProjectID: input.ProjectID, Estimate: input.Estimate, DueOn: input.DueOn, Report: input.Report}, Description: input.Description} if item.Priority == "" { item.Priority = "none" } if err := domain.ValidateIssue(item); err != nil { + if _, ok := err.(*domain.FieldError); ok { + return item, err + } return item, invalid(err.Error()) } if err := t.validateProjectAssignment(item.ProjectID); err != nil { @@ -202,13 +208,20 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if err != nil { return item, invalid("Status must belong to this workspace") } - item.CompletedAt = domain.TransitionCompletedAt(status.Category, time.Now()) + item.CompletedAt = domain.TransitionCompletedAt(status.Category, t.now()) if input.ParentID != nil { item.Parent, err = t.parent(item.ID, *input.ParentID, item.Type, "parentId") if err != nil { return item, err } } + item.Sprint, err = t.sprintRef(input.SprintID) + if err != nil { + return item, err + } + if err := t.validateSprintMembership(item); err != nil { + return item, err + } if err := t.SQL.QueryRowContext(t.Context, `UPDATE tracker_workspace SET issue_seq=issue_seq+1,updated_at=now() WHERE id=$1 RETURNING issue_seq`, t.WorkspaceID).Scan(&item.Number); err != nil { return item, err } @@ -223,7 +236,7 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if item.Parent != nil { parent = item.Parent.ID } - if err := t.Exec(`INSERT INTO tracker_issue (id,workspace_id,number,title,description,type,priority,status_id,assignee_sub,assignee_name,reporter_sub,reporter_name,parent_id,due_on,report,completed_at,project_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)`, item.ID, t.WorkspaceID, item.Number, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, actor.Sub, actor.Name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID); err != nil { + if err := t.Exec(`INSERT INTO tracker_issue (id,workspace_id,number,title,description,type,priority,status_id,assignee_sub,assignee_name,reporter_sub,reporter_name,parent_id,due_on,report,completed_at,project_id,estimate,sprint_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, item.ID, t.WorkspaceID, item.Number, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, actor.Sub, actor.Name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID, item.Estimate, sprintID(item.Sprint)); err != nil { return item, err } if _, err := t.replaceLabels(item.ID, input.LabelIDs); err != nil { @@ -232,6 +245,13 @@ func (t *Tx) CreateIssue(input IssueCreate, actor domain.Person, assignee *domai if err := t.activity(item.ID, actor, "created", nil, nil); err != nil { return item, err } + after, err := t.standing(item) + if err != nil { + return item, err + } + if err := t.sprintEvents(item.ID, domain.SprintStanding{}, after); err != nil { + return item, err + } return t.Issue(item.ID) } func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assignee *domain.Person) (domain.Issue, error) { @@ -266,6 +286,19 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign } } } + if input.Estimate.Present { + item.Estimate = input.Estimate.Value + } + if input.SprintID.Present { + next, err := t.sprintRef(input.SprintID.Value) + if err != nil { + return item, err + } + if old.Sprint != nil && old.Sprint.State == "closed" { + return item, &domain.FieldError{Path: "sprintId", Message: "Membership of a closed sprint is frozen"} + } + item.Sprint = next + } if input.DueOn.Present { item.DueOn = input.DueOn.Value } @@ -276,6 +309,9 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign item.Report = nil } if err := domain.ValidateIssue(item); err != nil { + if _, ok := err.(*domain.FieldError); ok { + return item, err + } return item, invalid(err.Error()) } if input.ParentID.Present || item.Type != old.Type { @@ -302,12 +338,17 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign return item, err } } + if input.SprintID.Present || input.ParentID.Present || item.Type != old.Type { + if err := t.validateSprintMembership(item); err != nil { + return item, err + } + } if item.StatusID != old.StatusID { after, err := t.Status(item.StatusID) if err != nil { return item, invalid("Status must belong to this workspace") } - item.CompletedAt = domain.TransitionCompletedAt(after.Category, time.Now()) + item.CompletedAt = domain.TransitionCompletedAt(after.Category, t.now()) } if input.LabelIDs.Present { if input.LabelIDs.Value == nil { @@ -335,6 +376,7 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign }{ {"title", old.Title, item.Title}, {"description", old.Description, item.Description}, {"type", old.Type, item.Type}, {"priority", old.Priority, item.Priority}, {"status", old.StatusID, item.StatusID}, {"assignee", old.Assignee, item.Assignee}, {"labels", old.LabelIDs, item.LabelIDs}, {"parent", old.Parent, item.Parent}, {"blocks", old.Blocks, item.Blocks}, {"due", old.DueOn, item.DueOn}, {"report", old.Report, item.Report}, {"project", old.ProjectID, item.ProjectID}, + {"estimate", old.Estimate, item.Estimate}, {"sprint", old.Sprint, item.Sprint}, } { if !reflect.DeepEqual(field.from, field.to) { changed = true @@ -357,7 +399,18 @@ func (t *Tx) PatchIssue(id string, input IssuePatch, actor domain.Person, assign if err != nil { return item, err } - if err := t.Exec(`UPDATE tracker_issue SET title=$3,description=$4,type=$5,priority=$6,status_id=$7,assignee_sub=$8,assignee_name=$9,parent_id=$10,due_on=$11,report=$12,completed_at=$13,project_id=$14,updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID); err != nil { + if err := t.Exec(`UPDATE tracker_issue SET title=$3,description=$4,type=$5,priority=$6,status_id=$7,assignee_sub=$8,assignee_name=$9,parent_id=$10,due_on=$11,report=$12,completed_at=$13,project_id=$14,estimate=$15,sprint_id=$16,updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID, item.Title, item.Description, item.Type, item.Priority, item.StatusID, sub, name, parent, item.DueOn, report, item.CompletedAt, item.ProjectID, item.Estimate, sprintID(item.Sprint)); err != nil { + return item, err + } + before, err := t.standing(old) + if err != nil { + return item, err + } + after, err := t.standing(item) + if err != nil { + return item, err + } + if err := t.sprintEvents(item.ID, before, after); err != nil { return item, err } return t.Issue(item.ID) @@ -373,5 +426,14 @@ func (t *Tx) DeleteIssue(id string, actor domain.Actor) error { if err := t.Exec(`UPDATE tracker_issue SET deleted_at=now(),updated_at=now() WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID); err != nil { return err } + before, err := t.standing(item) + if err != nil { + return err + } + after := before + after.Deleted = true + if err := t.sprintEvents(item.ID, before, after); err != nil { + return err + } return t.activity(item.ID, actor.Person, "deleted", nil, nil) } diff --git a/cmd/server/internal/store/migrations/011_sprints.sql b/cmd/server/internal/store/migrations/011_sprints.sql new file mode 100644 index 0000000..99d028a --- /dev/null +++ b/cmd/server/internal/store/migrations/011_sprints.sql @@ -0,0 +1,27 @@ +-- Sprints, T-shirt-size estimates, and the sprint ledger (design/API.md "Sprints, estimates, burndown and velocity"). +ALTER TABLE tracker_workspace ADD sprint_length_weeks int NOT NULL DEFAULT 1 CHECK (sprint_length_weeks IN (1,2)), + ADD timezone text NOT NULL DEFAULT 'Asia/Tokyo', + ADD sprint_seq bigint NOT NULL DEFAULT 0; -- sprint numbers stay monotonic when a planned sprint is deleted +CREATE TABLE tracker_sprint ( + id text PRIMARY KEY, workspace_id text NOT NULL REFERENCES tracker_workspace(id), + number bigint NOT NULL, name text NOT NULL, goal text NOT NULL DEFAULT '', + length_weeks int NOT NULL CHECK (length_weeks IN (1,2)), starts_on date NOT NULL, ends_on date NOT NULL, + started_at timestamptz, closed_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (workspace_id, number), + CHECK (ends_on = starts_on + 7 * length_weeks - 1), + CHECK (closed_at IS NULL OR started_at IS NOT NULL) +); +CREATE UNIQUE INDEX tracker_sprint_one_active ON tracker_sprint (workspace_id) WHERE started_at IS NOT NULL AND closed_at IS NULL; +ALTER TABLE tracker_issue ADD estimate text CHECK (estimate IN ('XS','S','M','L','XL')), + ADD sprint_id text REFERENCES tracker_sprint(id), + ADD CHECK (type <> 'epic' OR (estimate IS NULL AND sprint_id IS NULL)); +CREATE INDEX tracker_issue_sprint ON tracker_issue (sprint_id) WHERE sprint_id IS NOT NULL; +CREATE TABLE tracker_sprint_event ( + id text PRIMARY KEY, sprint_id text NOT NULL REFERENCES tracker_sprint(id) ON DELETE CASCADE, + issue_id text NOT NULL REFERENCES tracker_issue(id) ON DELETE CASCADE, at timestamptz NOT NULL DEFAULT now(), + scope_points int NOT NULL, scope_issues int NOT NULL, done_points int NOT NULL, done_issues int NOT NULL +); +CREATE INDEX tracker_sprint_event_sprint ON tracker_sprint_event (sprint_id, at); +ALTER TABLE tracker_view DROP CONSTRAINT tracker_view_group_by_check; +ALTER TABLE tracker_view ADD CONSTRAINT tracker_view_group_by_check CHECK (group_by IN ('none','epic','story','sprint')); diff --git a/cmd/server/internal/store/projects_test.go b/cmd/server/internal/store/projects_test.go index ef20bd1..7301bd6 100644 --- a/cmd/server/internal/store/projects_test.go +++ b/cmd/server/internal/store/projects_test.go @@ -178,7 +178,7 @@ func TestProjectSeedAssignment(t *testing.T) { } page, err := tx.ListIssues(ListOptions{Sort: domain.SortNumber}) require.NoError(t, err) - require.Len(t, page.Items, 36) + require.Len(t, page.Items, 40) names := []string{"Dashboard", "Platform API", "Builder Console"} for _, issue := range page.Items { n := issue.Number @@ -246,7 +246,7 @@ func TestProjectsMigrationFromV010(t *testing.T) { } var versions int require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT count(*) FROM tracker_schema_migrations`).Scan(&versions)) - require.Equal(t, 10, versions) + require.Equal(t, 11, versions) var reporterIndex string require.NoError(t, tx.SQL.QueryRowContext(t.Context(), `SELECT indexdef FROM pg_indexes WHERE schemaname=current_schema() AND indexname='tracker_issue_reporter'`).Scan(&reporterIndex)) require.Contains(t, reporterIndex, "USING btree (workspace_id, reporter_sub) WHERE (deleted_at IS NULL)") diff --git a/cmd/server/internal/store/seed.go b/cmd/server/internal/store/seed.go index db4c40e..6122ef5 100644 --- a/cmd/server/internal/store/seed.go +++ b/cmd/server/internal/store/seed.go @@ -3,8 +3,10 @@ package store import ( "context" "fmt" + "time" "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" ) // SeedDev only fills an installation with no allocated issues, including deleted @@ -94,6 +96,127 @@ func (s *Store) SeedDev(ctx context.Context, workspace string) error { return err } } - return nil + return tx.seedSprints(admin.Person, statuses) }) } + +// seedSprints mirrors the sprint fixture shared with the SPA mock. Historical +// ledger entries are intentionally inserted at their event instants, not now. +func (t *Tx) seedSprints(actor domain.Person, statuses []domain.Status) error { + var completed string + for _, status := range statuses { + if status.Category == "completed" { + completed = status.ID + } + } + for _, input := range []IssueCreate{ + {Title: "Speed up issue search", Type: "task"}, + {Title: "Add bulk status change", Type: "feature"}, + {Title: "Tidy up the settings layout", Type: "task"}, + {Title: "Show issue counts per project", Type: "feature"}, + } { + input.Priority = "medium" + input.StatusID = completed + if _, err := t.CreateIssue(input, actor, nil); err != nil { + return err + } + } + // Match the original mock's issue timestamps without moving issue numbers. + if err := t.Exec(`UPDATE tracker_issue SET created_at='2026-10-20T00:00:00Z'::timestamptz+number*interval '1 hour', updated_at='2026-10-20T00:00:00Z'::timestamptz+number*interval '1 hour', completed_at=CASE WHEN completed_at IS NOT NULL THEN '2026-10-20T00:00:00Z'::timestamptz+number*interval '1 hour' END WHERE workspace_id=$1`, t.WorkspaceID); err != nil { + return err + } + sizes := map[int]string{8: "XS", 16: "XS", 3: "S", 10: "S", 30: "S", 2: "M", 4: "M", 14: "M", 11: "L", 17: "L", 37: "L", 5: "XL", 23: "XL", 29: "XL", 38: "XL", 39: "XL", 40: "XL"} + for number, size := range sizes { + if err := t.Exec(`UPDATE tracker_issue SET estimate=$3 WHERE workspace_id=$1 AND number=$2`, t.WorkspaceID, number, size); err != nil { + return err + } + } + loc, err := time.LoadLocation("Asia/Tokyo") + if err != nil { + return err + } + now := t.now().In(loc) + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc) + at := func(offset, hour int) time.Time { + return today.AddDate(0, 0, offset).Add(time.Duration(hour) * time.Hour).UTC() + } + fixtures := []struct { + start, weeks int + goal string + members []int + }{ + {-24, 1, "Bug intake basics", []int{5, 11, 17}}, + {-17, 1, "Triage flow", []int{23, 29, 37}}, + {-10, 1, "Board polish", []int{38, 39, 40}}, + {-3, 2, "Sprint planning and burndown", []int{2, 3, 4, 10, 15, 30, 34}}, + {11, 1, "", []int{8, 14, 26}}, + } + ids := make([]string, len(fixtures)) + for i, f := range fixtures { + id := ulid.Make().String() + ids[i] = id + start := today.AddDate(0, 0, f.start) + end := start.AddDate(0, 0, 7*f.weeks-1) + created := at(f.start-1, 15) + updated := created + var started, closed *time.Time + if i < 4 { + v := at(f.start, 9) + started = &v + updated = v + } + if i < 3 { + v := at(f.start+6, 18) + closed = &v + updated = v + } + if i == 4 { + created = at(-1, 10) + updated = created + } + if err := t.Exec(`INSERT INTO tracker_sprint (id,workspace_id,number,name,goal,length_weeks,starts_on,ends_on,started_at,closed_at,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`, id, t.WorkspaceID, i+1, fmt.Sprintf("Sprint %d", i+1), f.goal, f.weeks, start.Format("2006-01-02"), end.Format("2006-01-02"), started, closed, created, updated); err != nil { + return err + } + for _, number := range f.members { + if err := t.Exec(`UPDATE tracker_issue SET sprint_id=$3 WHERE workspace_id=$1 AND number=$2`, t.WorkspaceID, number, id); err != nil { + return err + } + } + } + rows := []struct { + sprint int + kind string + numbers []int + day, hour int + }{ + {1, "join", []int{5, 11, 17, 2}, -25, 15}, + {1, "done", []int{5}, -22, 16}, {1, "done", []int{11}, -20, 11}, {1, "done", []int{17}, -18, 17}, + {2, "join", []int{23, 29, 37}, -18, 15}, {2, "join", []int{2}, -18, 18}, + {2, "done", []int{23}, -16, 16}, {2, "done", []int{37}, -14, 11}, {2, "done", []int{29}, -12, 17}, + {3, "join", []int{38, 39, 40}, -11, 15}, {3, "join", []int{2}, -11, 18}, + {3, "done", []int{38}, -9, 16}, {3, "done", []int{39}, -7, 11}, {3, "done", []int{40}, -4, 10}, + {4, "join", []int{3, 4, 15, 30, 34}, -4, 14}, {4, "join", []int{2}, -4, 18}, + {4, "join", []int{10}, -2, 11}, {4, "cancel", []int{30}, -1, 15}, + {5, "join", []int{8, 14, 26}, -1, 10}, + } + for _, row := range rows { + for _, number := range row.numbers { + after := domain.SprintStanding{SprintID: ids[row.sprint-1], Size: sizes[number], Category: "started"} + before := domain.SprintStanding{} + if row.kind != "join" { + before = after + if row.kind == "done" { + after.Category = "completed" + } else { + after.Category = "canceled" + } + } + for sprint, d := range domain.SprintDeltas(before, after) { + if err := t.Exec(`INSERT INTO tracker_sprint_event (id,sprint_id,issue_id,at,scope_points,scope_issues,done_points,done_issues) SELECT $1,$2,id,$4,$5,$6,$7,$8 FROM tracker_issue WHERE workspace_id=$9 AND number=$3`, ulid.Make().String(), sprint, number, at(row.day, row.hour), d.ScopePoints, d.ScopeIssues, d.DonePoints, d.DoneIssues, t.WorkspaceID); err != nil { + return err + } + } + } + } + return t.Exec(`UPDATE tracker_workspace SET sprint_seq=5 WHERE id=$1`, t.WorkspaceID) +} diff --git a/cmd/server/internal/store/sprint_charts.go b/cmd/server/internal/store/sprint_charts.go new file mode 100644 index 0000000..dd989a9 --- /dev/null +++ b/cmd/server/internal/store/sprint_charts.go @@ -0,0 +1,146 @@ +package store + +import ( + "math" + "time" + + "github.com/appthrust/tracker/cmd/server/internal/domain" +) + +func chartOptions(unit, project string) (string, error) { + if unit == "" { + unit = "points" + } + if unit != "points" && unit != "issues" { + return "", &domain.FieldError{Path: "unit", Message: "Unit must be points or issues"} + } + if project != "" && project != "none" && !domain.ValidID(project) { + return "", &domain.FieldError{Path: "project", Message: "Project must be an ID or none"} + } + return unit, nil +} +func (t *Tx) Burndown(id, unit, project string) (domain.BurndownResponse, error) { + var result domain.BurndownResponse + unit, err := chartOptions(unit, project) + if err != nil { + return result, err + } + s, err := t.Sprint(id) + if err != nil { + return result, err + } + w, err := t.Workspace() + if err != nil { + return result, err + } + loc, err := time.LoadLocation(w.Timezone) + if err != nil { + return result, err + } + now := t.now() + today := now.In(loc).Format("2006-01-02") + start, err := time.ParseInLocation("2006-01-02", s.StartsOn, loc) + if err != nil { + return result, err + } + end, err := time.ParseInLocation("2006-01-02", s.EndsOn, loc) + if err != nil { + return result, err + } + days := make([]domain.Day, 0, 7*s.LengthWeeks) + for date := start; !date.After(end); date = date.AddDate(0, 0, 1) { + until := date.AddDate(0, 0, 1) + if date.Format("2006-01-02") == today { + until = now.Add(time.Nanosecond) + } + // An overdue sprint's final point includes its eventual close, not just + // the scheduled last midnight. Earlier points keep their day boundaries. + if s.ClosedAt != nil && (until.After(*s.ClosedAt) || date.Equal(end)) { + until = s.ClosedAt.Add(time.Nanosecond) + } + days = append(days, domain.Day{Date: date, Until: until, Future: date.Format("2006-01-02") > today, Unit: unit}) + } + baseline, err := t.sprintTally(id, s.StartedAt, project) + if err != nil { + return result, err + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT e.at,e.scope_points,e.scope_issues,e.done_points,e.done_issues FROM tracker_sprint_event e JOIN tracker_issue i ON i.id=e.issue_id WHERE e.sprint_id=$1 AND i.workspace_id=$2 AND ($3='' OR ($3='none' AND i.project_id IS NULL) OR i.project_id=$3) AND e.at<=$4 AND ($5::timestamptz IS NULL OR e.at<=$5) ORDER BY e.at,e.id`, id, t.WorkspaceID, project, now, s.ClosedAt) + if err != nil { + return result, err + } + defer rows.Close() + events := []domain.SprintEvent{} + for rows.Next() { + var e domain.SprintEvent + if err := rows.Scan(&e.At, &e.ScopePoints, &e.ScopeIssues, &e.DonePoints, &e.DoneIssues); err != nil { + return result, err + } + events = append(events, e) + } + if err := rows.Err(); err != nil { + return result, err + } + return domain.BurndownResponse{Sprint: s.SprintRef, Unit: unit, Today: today, Points: domain.Burndown(baseline, events, days)}, nil +} +func (t *Tx) Velocity(unit, project string, limit int) (domain.Velocity, error) { + result := domain.Velocity{Items: []domain.VelocityEntry{}} + unit, err := chartOptions(unit, project) + if err != nil { + return result, err + } + result.Unit = unit + if limit == 0 { + limit = 8 + } + if limit < 1 || limit > 26 { + return result, &domain.FieldError{Path: "limit", Message: "Limit must be between 1 and 26"} + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+sprintColumns+` FROM tracker_sprint s WHERE s.workspace_id=$1 AND s.closed_at IS NOT NULL ORDER BY s.closed_at DESC,s.number DESC LIMIT $2`, t.WorkspaceID, max(limit, 3)) + if err != nil { + return result, err + } + sprints := []domain.Sprint{} + for rows.Next() { + s, err := scanSprint(rows) + if err != nil { + rows.Close() + return result, err + } + sprints = append(sprints, s) + } + err = rows.Err() + rows.Close() + if err != nil { + return result, err + } + average := 0.0 + for i, s := range sprints { + committed, err := t.sprintTally(s.ID, s.StartedAt, project) + if err != nil { + return result, err + } + completed, err := t.sprintTally(s.ID, s.ClosedAt, project) + if err != nil { + return result, err + } + entry := domain.VelocityEntry{Sprint: s.SprintRef, LengthWeeks: s.LengthWeeks, Committed: committed.ScopePoints, Completed: completed.DonePoints} + if unit == "issues" { + entry.Committed = committed.ScopeIssues + entry.Completed = completed.DoneIssues + } + if i < 3 { + average += float64(entry.Completed) / float64(s.LengthWeeks) + } + if i < limit { + result.Items = append(result.Items, entry) + } + } + if len(sprints) > 0 { + average = math.Round(average/float64(min(3, len(sprints)))*100) / 100 + result.AveragePerWeek = &average + } + for i, j := 0, len(result.Items)-1; i < j; i, j = i+1, j-1 { + result.Items[i], result.Items[j] = result.Items[j], result.Items[i] + } + return result, nil +} diff --git a/cmd/server/internal/store/sprint_issues.go b/cmd/server/internal/store/sprint_issues.go new file mode 100644 index 0000000..8b8b942 --- /dev/null +++ b/cmd/server/internal/store/sprint_issues.go @@ -0,0 +1,80 @@ +package store + +import ( + "database/sql" + "errors" + + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +func (t *Tx) sprintRef(id *string) (*domain.SprintRef, error) { + if id == nil { + return nil, nil + } + var s domain.SprintRef + err := t.SQL.QueryRowContext(t.Context, `SELECT s.id,s.number,s.name,`+sprintStateSQL+` FROM tracker_sprint s WHERE s.workspace_id=$1 AND s.id=$2`, t.WorkspaceID, *id).Scan(&s.ID, &s.Number, &s.Name, &s.State) + if errors.Is(err, sql.ErrNoRows) { + return nil, &domain.FieldError{Path: "sprintId", Message: "Sprint must be planned or active in this workspace"} + } + if err != nil { + return nil, err + } + return &s, nil +} +func (t *Tx) validateSprintMembership(item domain.Issue) error { + parent, sprint := "", "" + if item.Parent != nil { + parent = item.Parent.ID + } + if item.Sprint != nil { + sprint = item.Sprint.ID + if err := domain.ValidateMembership(item.Type, item.Sprint.State, 0); err != nil { + return err + } + } + // Include the proposed root in the descendant set: reparenting an unassigned + // intermediate node must not bring two existing members into one lineage. + var conflicts int + err := t.SQL.QueryRowContext(t.Context, `WITH RECURSIVE ancestors AS ( + SELECT id,parent_id,sprint_id FROM tracker_issue WHERE workspace_id=$1 AND id=$3 AND deleted_at IS NULL + UNION SELECT i.id,i.parent_id,i.sprint_id FROM tracker_issue i JOIN ancestors a ON i.id=a.parent_id WHERE i.workspace_id=$1 AND i.deleted_at IS NULL + ), descendants AS ( + SELECT $2::text AS id,nullif($4::text,'') AS sprint_id + UNION SELECT i.id,i.sprint_id FROM tracker_issue i JOIN descendants d ON i.parent_id=d.id WHERE i.workspace_id=$1 AND i.deleted_at IS NULL + ) SELECT (SELECT count(*) FROM ancestors a JOIN descendants d ON a.sprint_id=d.sprint_id) + (SELECT count(*) FROM descendants d WHERE d.id<>$2 AND d.sprint_id=nullif($4,''))`, t.WorkspaceID, item.ID, parent, sprint).Scan(&conflicts) + if err != nil { + return err + } + if conflicts != 0 { + return &domain.FieldError{Path: "sprintId", Message: "An ancestor or descendant already belongs to this sprint"} + } + return nil +} +func (t *Tx) standing(item domain.Issue) (domain.SprintStanding, error) { + var s domain.SprintStanding + if item.Sprint == nil { + return s, nil + } + s.SprintID = item.Sprint.ID + if item.Estimate != nil { + s.Size = *item.Estimate + } + status, err := t.Status(item.StatusID) + s.Category = status.Category + return s, err +} +func (t *Tx) sprintEvents(issueID string, before, after domain.SprintStanding) error { + for id, d := range domain.SprintDeltas(before, after) { + if err := t.Exec(`INSERT INTO tracker_sprint_event (id,sprint_id,issue_id,at,scope_points,scope_issues,done_points,done_issues) SELECT $1,s.id,$3,$4,$5,$6,$7,$8 FROM tracker_sprint s WHERE s.workspace_id=$9 AND s.id=$2 AND s.closed_at IS NULL`, ulid.Make().String(), id, issueID, t.now(), d.ScopePoints, d.ScopeIssues, d.DonePoints, d.DoneIssues, t.WorkspaceID); err != nil { + return err + } + } + return nil +} +func sprintID(s *domain.SprintRef) any { + if s == nil { + return nil + } + return s.ID +} diff --git a/cmd/server/internal/store/sprints.go b/cmd/server/internal/store/sprints.go new file mode 100644 index 0000000..e2426aa --- /dev/null +++ b/cmd/server/internal/store/sprints.go @@ -0,0 +1,386 @@ +package store + +import ( + "database/sql" + "errors" + "fmt" + "strings" + "time" + "unicode/utf8" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/oklog/ulid/v2" +) + +type SprintCreate struct { + Name *string `json:"name"` + Goal *string `json:"goal"` + StartsOn *string `json:"startsOn"` + LengthWeeks *int `json:"lengthWeeks"` +} +type SprintPatch = SprintCreate + +const sprintStateSQL = `(CASE WHEN s.closed_at IS NOT NULL THEN 'closed' WHEN s.started_at IS NOT NULL THEN 'active' ELSE 'planned' END)` +const sprintColumns = `s.id,s.number,s.name,s.goal,` + sprintStateSQL + `,s.length_weeks,to_char(s.starts_on,'YYYY-MM-DD'),to_char(s.ends_on,'YYYY-MM-DD'),s.started_at,s.closed_at,s.created_at,s.updated_at` + +func scanSprint(row scanner) (domain.Sprint, error) { + var s domain.Sprint + err := row.Scan(&s.ID, &s.Number, &s.Name, &s.Goal, &s.State, &s.LengthWeeks, &s.StartsOn, &s.EndsOn, &s.StartedAt, &s.ClosedAt, &s.CreatedAt, &s.UpdatedAt) + s.CreatedAt, s.UpdatedAt = s.CreatedAt.UTC(), s.UpdatedAt.UTC() + if s.StartedAt != nil { + v := s.StartedAt.UTC() + s.StartedAt = &v + } + if s.ClosedAt != nil { + v := s.ClosedAt.UTC() + s.ClosedAt = &v + } + return s, err +} +func (t *Tx) sprintTotals(s *domain.Sprint) error { + var err error + s.Current, err = t.sprintTally(s.ID, s.ClosedAt, "") + if err != nil { + return err + } + if s.StartedAt != nil { + v, err := t.sprintTally(s.ID, s.StartedAt, "") + if err != nil { + return err + } + s.Commitment = &v + } + return nil +} +func (t *Tx) Sprint(id string) (domain.Sprint, error) { + s, err := scanSprint(t.SQL.QueryRowContext(t.Context, `SELECT `+sprintColumns+` FROM tracker_sprint s WHERE s.workspace_id=$1 AND s.id=$2`, t.WorkspaceID, id)) + if err == nil { + err = t.sprintTotals(&s) + } + return s, err +} +func (t *Tx) Sprints(state string) ([]domain.Sprint, error) { + if state != "" && state != "planned" && state != "active" && state != "closed" { + return nil, &domain.FieldError{Path: "state", Message: "State must be planned, active, or closed"} + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT `+sprintColumns+` FROM tracker_sprint s WHERE s.workspace_id=$1 AND ($2='' OR `+sprintStateSQL+`=$2) ORDER BY CASE WHEN s.closed_at IS NOT NULL THEN 2 WHEN s.started_at IS NOT NULL THEN 0 ELSE 1 END,CASE WHEN s.closed_at IS NULL THEN s.starts_on END, s.closed_at DESC,s.number DESC`, t.WorkspaceID, state) + if err != nil { + return nil, err + } + result := []domain.Sprint{} + for rows.Next() { + s, err := scanSprint(rows) + if err != nil { + rows.Close() + return nil, err + } + result = append(result, s) + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + for i := range result { + if err := t.sprintTotals(&result[i]); err != nil { + return nil, err + } + } + return result, nil +} +func (t *Tx) sprintTally(id string, at *time.Time, project string) (domain.Tally, error) { + var v domain.Tally + err := t.SQL.QueryRowContext(t.Context, `SELECT coalesce(sum(e.scope_points),0),coalesce(sum(e.scope_issues),0),coalesce(sum(e.done_points),0),coalesce(sum(e.done_issues),0) FROM tracker_sprint_event e JOIN tracker_issue i ON i.id=e.issue_id JOIN tracker_sprint s ON s.id=e.sprint_id WHERE s.workspace_id=$1 AND s.id=$2 AND ($3::timestamptz IS NULL OR e.at<=$3) AND ($4='' OR ($4='none' AND i.project_id IS NULL) OR i.project_id=$4)`, t.WorkspaceID, id, at, project).Scan(&v.ScopePoints, &v.ScopeIssues, &v.DonePoints, &v.DoneIssues) + return v, err +} +func (t *Tx) sprintDates(id, start string, weeks int) (string, error) { + day, err := time.Parse("2006-01-02", start) + if err != nil { + return "", &domain.FieldError{Path: "startsOn", Message: "Start date must be YYYY-MM-DD"} + } + rows, err := t.SQL.QueryContext(t.Context, `SELECT starts_on,ends_on FROM tracker_sprint WHERE workspace_id=$1 AND id<>$2 AND closed_at IS NULL`, t.WorkspaceID, id) + if err != nil { + return "", err + } + spans := []domain.SprintSpan{} + for rows.Next() { + var span domain.SprintSpan + if err := rows.Scan(&span.StartsOn, &span.EndsOn); err != nil { + rows.Close() + return "", err + } + spans = append(spans, span) + } + err = rows.Err() + rows.Close() + if err != nil { + return "", err + } + if err := domain.ValidateSprintDates(day, weeks, spans); err != nil { + if errors.Is(err, domain.ErrSprintOverlap) { + return "", httpx.Conflict(err.Error()) + } + return "", err + } + return day.AddDate(0, 0, 7*weeks-1).Format("2006-01-02"), nil +} +func validateSprint(s domain.Sprint) error { + if !domain.Text(s.Name, 1, 60) { + return &domain.FieldError{Path: "name", Message: "Sprint name must contain 1 to 60 characters"} + } + if !utf8.ValidString(s.Goal) || len(s.Goal) > 4096 { + return &domain.FieldError{Path: "goal", Message: "Sprint goal must be valid UTF-8 and at most 4096 bytes"} + } + return nil +} +func (t *Tx) CreateSprint(input SprintCreate) (domain.Sprint, error) { + var s domain.Sprint + w, err := t.Workspace() + if err != nil { + return s, err + } + s.ID = ulid.Make().String() + s.LengthWeeks = w.SprintLengthWeeks + if input.LengthWeeks != nil { + s.LengthWeeks = *input.LengthWeeks + } + if input.StartsOn != nil { + s.StartsOn = *input.StartsOn + } else { + var latest sql.NullTime + if err := t.SQL.QueryRowContext(t.Context, `SELECT max(ends_on) FROM tracker_sprint WHERE workspace_id=$1 AND closed_at IS NULL`, t.WorkspaceID).Scan(&latest); err != nil { + return s, err + } + if latest.Valid { + s.StartsOn = latest.Time.AddDate(0, 0, 1).Format("2006-01-02") + } else { + loc, err := time.LoadLocation(w.Timezone) + if err != nil { + return s, err + } + today := t.now().In(loc) + days := (int(time.Monday) - int(today.Weekday()) + 7) % 7 + if days == 0 { + days = 7 + } + s.StartsOn = today.AddDate(0, 0, days).Format("2006-01-02") + } + } + s.EndsOn, err = t.sprintDates(s.ID, s.StartsOn, s.LengthWeeks) + if err != nil { + return s, err + } + if err := t.SQL.QueryRowContext(t.Context, `UPDATE tracker_workspace SET sprint_seq=sprint_seq+1 WHERE id=$1 RETURNING sprint_seq`, t.WorkspaceID).Scan(&s.Number); err != nil { + return s, err + } + s.Name = fmt.Sprintf("Sprint %d", s.Number) + if input.Name != nil { + s.Name = strings.TrimSpace(*input.Name) + } + if input.Goal != nil { + s.Goal = *input.Goal + } + if err := validateSprint(s); err != nil { + return s, err + } + now := t.now() + if err := t.Exec(`INSERT INTO tracker_sprint (id,workspace_id,number,name,goal,length_weeks,starts_on,ends_on,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$9)`, s.ID, t.WorkspaceID, s.Number, s.Name, s.Goal, s.LengthWeeks, s.StartsOn, s.EndsOn, now); err != nil { + return s, err + } + return t.Sprint(s.ID) +} +func (t *Tx) PatchSprint(id string, input SprintPatch) (domain.Sprint, error) { + s, err := t.Sprint(id) + if err != nil { + return s, err + } + if input.StartsOn != nil || input.LengthWeeks != nil { + if s.State != "planned" { + return s, httpx.Conflict("Only planned sprints can be re-dated") + } + if input.StartsOn != nil { + s.StartsOn = *input.StartsOn + } + if input.LengthWeeks != nil { + s.LengthWeeks = *input.LengthWeeks + } + s.EndsOn, err = t.sprintDates(id, s.StartsOn, s.LengthWeeks) + if err != nil { + return s, err + } + } + if input.Name != nil { + s.Name = strings.TrimSpace(*input.Name) + } + if input.Goal != nil { + s.Goal = *input.Goal + } + if err := validateSprint(s); err != nil { + return s, err + } + if err := t.Exec(`UPDATE tracker_sprint SET name=$3,goal=$4,length_weeks=$5,starts_on=$6,ends_on=$7,updated_at=$8 WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id, s.Name, s.Goal, s.LengthWeeks, s.StartsOn, s.EndsOn, t.now()); err != nil { + return s, err + } + return t.Sprint(id) +} +func (t *Tx) StartSprint(id string) (domain.Sprint, error) { + s, err := t.Sprint(id) + if err != nil { + return s, err + } + if s.State != "planned" { + return s, httpx.Conflict("Only planned sprints can be started") + } + var active bool + if err := t.SQL.QueryRowContext(t.Context, `SELECT EXISTS(SELECT 1 FROM tracker_sprint WHERE workspace_id=$1 AND started_at IS NOT NULL AND closed_at IS NULL)`, t.WorkspaceID).Scan(&active); err != nil { + return s, err + } + if active { + return s, httpx.Conflict("Another sprint is active") + } + w, err := t.Workspace() + if err != nil { + return s, err + } + loc, err := time.LoadLocation(w.Timezone) + if err != nil { + return s, err + } + now := t.now() + today := now.In(loc).Format("2006-01-02") + if s.StartsOn > today { + s.StartsOn = today + } + s.EndsOn, err = t.sprintDates(id, s.StartsOn, s.LengthWeeks) + if err != nil { + return s, err + } + if err := t.Exec(`UPDATE tracker_sprint SET started_at=$3,starts_on=$4,ends_on=$5,updated_at=$3 WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id, now, s.StartsOn, s.EndsOn); err != nil { + return s, err + } + return t.Sprint(id) +} +func (t *Tx) CloseSprint(id string, target *string, actor domain.Person) (domain.Sprint, error) { + s, err := t.Sprint(id) + if err != nil { + return s, err + } + if s.State != "active" { + return s, httpx.Conflict("Only active sprints can be closed") + } + var next *domain.SprintRef + if target != nil { + v, err := t.Sprint(*target) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return s, &domain.FieldError{Path: "moveIncompleteTo", Message: "Target must be a planned sprint in this workspace"} + } + return s, err + } + if v.State != "planned" { + return s, &domain.FieldError{Path: "moveIncompleteTo", Message: "Target must be a planned sprint in this workspace"} + } + next = &v.SprintRef + } + members, err := t.sprintMembers(id, true) + if err != nil { + return s, err + } + if err := t.Exec(`UPDATE tracker_sprint SET closed_at=$3,updated_at=$3 WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id, t.now()); err != nil { + return s, err + } + for _, item := range members { + destination := next + candidate := item + candidate.Sprint = destination + if err := t.validateSprintMembership(candidate); err != nil { + var field *domain.FieldError + if !errors.As(err, &field) || field.Path != "sprintId" { + return s, err + } + destination = nil + } + if err := t.moveSprintMember(item, destination, actor); err != nil { + return s, err + } + } + return t.Sprint(id) +} +func (t *Tx) DeleteSprint(id string, actor domain.Actor) error { + if !domain.Can(actor, domain.ManageWorkspace, domain.Target{}) { + return httpx.Forbidden() + } + s, err := t.Sprint(id) + if err != nil { + return err + } + if s.State != "planned" { + return httpx.Conflict("Only planned sprints can be deleted") + } + members, err := t.sprintMembers(id, false) + if err != nil { + return err + } + for _, item := range members { + if err := t.moveSprintMember(item, nil, actor.Person); err != nil { + return err + } + } + // Soft-deleted members also retain a foreign key until the sprint is removed. + if err := t.Exec(`UPDATE tracker_issue SET sprint_id=NULL WHERE workspace_id=$1 AND sprint_id=$2`, t.WorkspaceID, id); err != nil { + return err + } + return t.Exec(`DELETE FROM tracker_sprint WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, id) +} +func (t *Tx) sprintMembers(id string, incomplete bool) ([]domain.Issue, error) { + rows, err := t.SQL.QueryContext(t.Context, `SELECT i.id FROM tracker_issue i JOIN tracker_status s ON s.id=i.status_id WHERE i.workspace_id=$1 AND i.sprint_id=$2 AND i.deleted_at IS NULL AND (NOT $3 OR s.category NOT IN ('completed','canceled')) ORDER BY i.id`, t.WorkspaceID, id, incomplete) + if err != nil { + return nil, err + } + ids := []string{} + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return nil, err + } + ids = append(ids, id) + } + err = rows.Err() + rows.Close() + if err != nil { + return nil, err + } + result := make([]domain.Issue, 0, len(ids)) + for _, id := range ids { + item, err := t.Issue(id) + if err != nil { + return nil, err + } + result = append(result, item) + } + return result, nil +} +func (t *Tx) moveSprintMember(item domain.Issue, next *domain.SprintRef, actor domain.Person) error { + before, err := t.standing(item) + if err != nil { + return err + } + old := item.Sprint + item.Sprint = next + after := before + after.SprintID = "" + var id any + if next != nil { + after.SprintID = next.ID + id = next.ID + } + if err := t.Exec(`UPDATE tracker_issue SET sprint_id=$3,updated_at=$4 WHERE workspace_id=$1 AND id=$2`, t.WorkspaceID, item.ID, id, t.now()); err != nil { + return err + } + if err := t.sprintEvents(item.ID, before, after); err != nil { + return err + } + return t.activity(item.ID, actor, "sprint", old, next) +} diff --git a/cmd/server/internal/store/sprints_test.go b/cmd/server/internal/store/sprints_test.go new file mode 100644 index 0000000..99527ea --- /dev/null +++ b/cmd/server/internal/store/sprints_test.go @@ -0,0 +1,571 @@ +package store + +import ( + "encoding/json" + "math/rand/v2" + "testing" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/appserver-go/appserver/pgstore/testutil" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/stretchr/testify/require" +) + +func sprintClock(s string) time.Time { + v, err := time.Parse(time.RFC3339, s) + if err != nil { + panic(err) + } + return v +} +func sprintInput(start string, weeks int) SprintCreate { + return SprintCreate{StartsOn: &start, LengthWeeks: &weeks} +} +func assertLedgerRecount(t *testing.T, tx *Tx, id string) { + t.Helper() + var want domain.Tally + rows, err := tx.SQL.QueryContext(tx.Context, `SELECT coalesce(i.estimate,''),s.category FROM tracker_issue i JOIN tracker_status s ON s.id=i.status_id WHERE i.workspace_id=$1 AND i.sprint_id=$2 AND i.deleted_at IS NULL`, tx.WorkspaceID, id) + require.NoError(t, err) + for rows.Next() { + var size, category string + require.NoError(t, rows.Scan(&size, &category)) + v := domain.Contribution(domain.SprintStanding{SprintID: id, Size: size, Category: category}) + want.ScopePoints += v.ScopePoints + want.ScopeIssues += v.ScopeIssues + want.DonePoints += v.DonePoints + want.DoneIssues += v.DoneIssues + } + require.NoError(t, rows.Err()) + require.NoError(t, rows.Close()) + got, err := tx.sprintTally(id, nil, "") + require.NoError(t, err) + require.Equal(t, want, got) +} +func TestSprintLedgerInvariant(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "ledger")) + now := sprintClock("2026-11-02T00:00:00Z") + db.Now = func() time.Time { return now } + actor := domain.Actor{Person: domain.Person{Sub: "alex", Name: "Alex"}, Role: "Admin"} + require.NoError(t, db.InWorkspace(t.Context(), "ledger", true, func(tx *Tx) error { + a, err := tx.CreateSprint(sprintInput("2026-11-02", 1)) + require.NoError(t, err) + b, err := tx.CreateSprint(sprintInput("2026-11-09", 2)) + require.NoError(t, err) + statuses, err := tx.Statuses() + require.NoError(t, err) + items := []domain.Issue{} + sizes := []string{"XS", "S", "M", "L", "XL"} + for i := range 12 { + size := sizes[i%5] + sprint := a.ID + if i%2 == 1 { + sprint = b.ID + } + item, err := tx.CreateIssue(IssueCreate{Title: "Member", Type: "task", Estimate: &size, SprintID: &sprint}, actor.Person, nil) + require.NoError(t, err) + items = append(items, item) + assertLedgerRecount(t, tx, a.ID) + assertLedgerRecount(t, tx, b.ID) + } + rng := rand.New(rand.NewPCG(42, 7)) + for i := range 90 { + now = now.Add(time.Minute) + index := rng.IntN(len(items)) + item := items[index] + patch := IssuePatch{} + switch i % 4 { + case 0: + patch.StatusID = field(statuses[rng.IntN(len(statuses))].ID) + case 1: + if i%8 == 1 { + patch.Estimate = Field[string]{Present: true} + } else { + patch.Estimate = field(sizes[rng.IntN(5)]) + } + case 2: + sprint := a.ID + if i%8 == 2 { + sprint = b.ID + } + patch.SprintID = field(sprint) + case 3: + patch.SprintID = Field[string]{Present: true} + } + item, err = tx.PatchIssue(item.ID, patch, actor.Person, nil) + require.NoError(t, err) + items[index] = item + assertLedgerRecount(t, tx, a.ID) + assertLedgerRecount(t, tx, b.ID) + } + for _, item := range items[:4] { + require.NoError(t, tx.DeleteIssue(item.ID, actor)) + assertLedgerRecount(t, tx, a.ID) + assertLedgerRecount(t, tx, b.ID) + } + return nil + })) +} +func TestSprintLifecycleAndFrozenLedger(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "sprints")) + now := sprintClock("2026-11-02T01:00:00Z") + db.Now = func() time.Time { return now } + actor := domain.Actor{Person: domain.Person{Sub: "alex", Name: "Alex"}, Role: "Admin"} + require.NoError(t, db.InWorkspace(t.Context(), "sprints", true, func(tx *Tx) error { + a, err := tx.CreateSprint(sprintInput("2026-11-02", 1)) + require.NoError(t, err) + b, err := tx.CreateSprint(sprintInput("2026-11-09", 1)) + require.NoError(t, err) + c, err := tx.CreateSprint(sprintInput("2026-11-16", 2)) + require.NoError(t, err) + size := "M" + done, err := tx.CreateIssue(IssueCreate{Title: "Done", Type: "task", Estimate: &size, SprintID: &a.ID}, actor.Person, nil) + require.NoError(t, err) + open, err := tx.CreateIssue(IssueCreate{Title: "Open", Type: "task", Estimate: &size, SprintID: &a.ID}, actor.Person, nil) + require.NoError(t, err) + canceled, err := tx.CreateIssue(IssueCreate{Title: "Canceled", Type: "task", Estimate: &size, SprintID: &a.ID}, actor.Person, nil) + require.NoError(t, err) + statuses, err := tx.Statuses() + require.NoError(t, err) + var completedID, canceledID string + for _, s := range statuses { + if s.Category == "completed" { + completedID = s.ID + } + if s.Category == "canceled" { + canceledID = s.ID + } + } + now = now.Add(time.Minute) + a, err = tx.StartSprint(a.ID) + require.NoError(t, err) + require.Equal(t, 9, a.Commitment.ScopePoints) + _, err = tx.StartSprint(b.ID) + var conflict *httpx.Error + require.ErrorAs(t, err, &conflict) + require.Equal(t, 409, conflict.Status) + now = now.Add(time.Hour) + _, err = tx.PatchIssue(done.ID, IssuePatch{StatusID: field(completedID)}, actor.Person, nil) + require.NoError(t, err) + _, err = tx.PatchIssue(canceled.ID, IssuePatch{StatusID: field(canceledID)}, actor.Person, nil) + require.NoError(t, err) + assertLedgerRecount(t, tx, a.ID) + now = now.Add(time.Hour) + closed, err := tx.CloseSprint(a.ID, &b.ID, actor.Person) + require.NoError(t, err) + require.Equal(t, domain.Tally{ScopePoints: 6, ScopeIssues: 2, DonePoints: 3, DoneIssues: 1}, closed.Current) + require.Equal(t, 9, closed.Commitment.ScopePoints) + got, err := tx.Issue(done.ID) + require.NoError(t, err) + require.Equal(t, a.ID, got.Sprint.ID) + got, err = tx.Issue(canceled.ID) + require.NoError(t, err) + require.Equal(t, a.ID, got.Sprint.ID) + got, err = tx.Issue(open.ID) + require.NoError(t, err) + require.Equal(t, b.ID, got.Sprint.ID) + assertLedgerRecount(t, tx, b.ID) + var events int + require.NoError(t, tx.SQL.QueryRowContext(tx.Context, `SELECT count(*) FROM tracker_sprint_event WHERE sprint_id=$1`, a.ID).Scan(&events)) + now = now.Add(time.Hour) + _, err = tx.PatchIssue(done.ID, IssuePatch{Estimate: field("XL"), StatusID: field(statuses[0].ID)}, actor.Person, nil) + require.NoError(t, err) + require.NoError(t, tx.DeleteIssue(done.ID, actor)) + var after int + require.NoError(t, tx.SQL.QueryRowContext(tx.Context, `SELECT count(*) FROM tracker_sprint_event WHERE sprint_id=$1`, a.ID).Scan(&after)) + require.Equal(t, events, after) + _, err = tx.PatchIssue(canceled.ID, IssuePatch{SprintID: Field[string]{Present: true}}, actor.Person, nil) + var fieldErr *domain.FieldError + require.ErrorAs(t, err, &fieldErr) + require.Equal(t, "sprintId", fieldErr.Path) + velocity, err := tx.Velocity("points", "", 8) + require.NoError(t, err) + require.Len(t, velocity.Items, 1) + require.Equal(t, 3, velocity.Items[0].Completed) + require.NoError(t, tx.DeleteSprint(b.ID, actor)) + got, err = tx.Issue(open.ID) + require.NoError(t, err) + require.Nil(t, got.Sprint) + require.NoError(t, tx.DeleteSprint(c.ID, actor)) + next, err := tx.CreateSprint(sprintInput("2026-12-01", 1)) + require.NoError(t, err) + require.Equal(t, int64(4), next.Number) + return nil + })) +} +func TestSprintLineageAndCarryOverConflict(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "lineage")) + now := sprintClock("2026-11-02T01:00:00Z") + db.Now = func() time.Time { return now } + actor := domain.Person{Sub: "alex", Name: "Alex"} + require.NoError(t, db.InWorkspace(t.Context(), "lineage", true, func(tx *Tx) error { + a, err := tx.CreateSprint(sprintInput("2026-11-02", 1)) + require.NoError(t, err) + b, err := tx.CreateSprint(sprintInput("2026-11-09", 1)) + require.NoError(t, err) + epic, err := tx.CreateIssue(IssueCreate{Title: "Epic", Type: "epic"}, actor, nil) + require.NoError(t, err) + story, err := tx.CreateIssue(IssueCreate{Title: "Story", Type: "story", ParentID: &epic.ID, SprintID: &b.ID}, actor, nil) + require.NoError(t, err) + child, err := tx.CreateIssue(IssueCreate{Title: "Child", Type: "task", SprintID: &a.ID}, actor, nil) + require.NoError(t, err) + _, err = tx.PatchIssue(child.ID, IssuePatch{ParentID: field(story.ID)}, actor, nil) + require.NoError(t, err) + _, err = tx.PatchIssue(child.ID, IssuePatch{SprintID: field(b.ID)}, actor, nil) + var fieldErr *domain.FieldError + require.ErrorAs(t, err, &fieldErr) + require.Equal(t, "sprintId", fieldErr.Path) + _, err = tx.PatchIssue(story.ID, IssuePatch{SprintID: field(a.ID)}, actor, nil) + require.Error(t, err) + _, err = tx.PatchIssue(child.ID, IssuePatch{Type: field("epic"), ParentID: Field[string]{Present: true}}, actor, nil) + require.Error(t, err) + // A reparented intermediate node must check its descendants, not just itself. + root, err := tx.CreateIssue(IssueCreate{Title: "Root", Type: "task"}, actor, nil) + require.NoError(t, err) + _, err = tx.CreateIssue(IssueCreate{Title: "Deep", Type: "task", ParentID: &root.ID, SprintID: &b.ID}, actor, nil) + require.NoError(t, err) + _, err = tx.PatchIssue(root.ID, IssuePatch{ParentID: field(story.ID)}, actor, nil) + require.ErrorAs(t, err, &fieldErr) + require.Equal(t, "sprintId", fieldErr.Path) + _, err = tx.StartSprint(a.ID) + require.NoError(t, err) + now = now.Add(time.Hour) + _, err = tx.CloseSprint(a.ID, &b.ID, actor) + require.NoError(t, err) + child, err = tx.Issue(child.ID) + require.NoError(t, err) + require.Nil(t, child.Sprint) + assertLedgerRecount(t, tx, b.ID) + return nil + })) +} +func TestSprintDatesDefaultsAndIsolation(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "dates")) + require.NoError(t, db.EnsureWorkspace(t.Context(), "other")) + now := sprintClock("2026-11-01T23:30:00Z") + db.Now = func() time.Time { return now } // Monday in Tokyo + var id string + require.NoError(t, db.InWorkspace(t.Context(), "dates", true, func(tx *Tx) error { + weeks := 2 + _, err := tx.PatchWorkspace(nil, nil, &weeks, nil) + require.NoError(t, err) + a, err := tx.CreateSprint(SprintCreate{}) + require.NoError(t, err) + id = a.ID + require.Equal(t, "2026-11-09", a.StartsOn) + require.Equal(t, "2026-11-22", a.EndsOn) + b, err := tx.CreateSprint(SprintCreate{}) + require.NoError(t, err) + require.Equal(t, "2026-11-23", b.StartsOn) + _, err = tx.CreateSprint(sprintInput("2026-11-22", 1)) + var conflict *httpx.Error + require.ErrorAs(t, err, &conflict) + require.Equal(t, 409, conflict.Status) + a, err = tx.StartSprint(a.ID) + require.NoError(t, err) + require.Equal(t, "2026-11-02", a.StartsOn) + require.Equal(t, "2026-11-15", a.EndsOn) + _, err = tx.PatchSprint(a.ID, sprintInput("2026-11-03", 1)) + require.ErrorAs(t, err, &conflict) + return nil + })) + require.NoError(t, db.InWorkspace(t.Context(), "other", true, func(tx *Tx) error { + _, err := tx.Sprint(id) + require.Error(t, err) + _, err = tx.CreateIssue(IssueCreate{Title: "Foreign", Type: "task", SprintID: &id}, domain.Person{Sub: "x"}, nil) + var fieldErr *domain.FieldError + require.ErrorAs(t, err, &fieldErr) + require.Equal(t, "sprintId", fieldErr.Path) + return nil + })) +} +func TestSprintChartsTimezoneAndProject(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "charts")) + now := sprintClock("2026-11-01T12:00:00Z") + db.Now = func() time.Time { return now } + actor := domain.Actor{Person: domain.Person{Sub: "alex", Name: "Alex"}, Role: "Admin"} + require.NoError(t, db.InWorkspace(t.Context(), "charts", true, func(tx *Tx) error { + s, err := tx.CreateSprint(sprintInput("2026-11-02", 1)) + require.NoError(t, err) + project, err := tx.CreateProject(ProjectCreate{Name: "Dashboard"}, actor) + require.NoError(t, err) + size := "M" + a, err := tx.CreateIssue(IssueCreate{Title: "Sized", Type: "task", Estimate: &size, SprintID: &s.ID, ProjectID: &project.ID}, actor.Person, nil) + require.NoError(t, err) + _, err = tx.CreateIssue(IssueCreate{Title: "Unestimated", Type: "task", SprintID: &s.ID}, actor.Person, nil) + require.NoError(t, err) + now = sprintClock("2026-11-02T00:00:00Z") + s, err = tx.StartSprint(s.ID) + require.NoError(t, err) + statuses, err := tx.Statuses() + require.NoError(t, err) + var done string + for _, status := range statuses { + if status.Category == "completed" { + done = status.ID + } + } + now = sprintClock("2026-11-02T15:00:00Z") // midnight Tokyo, must fall on day two + _, err = tx.PatchIssue(a.ID, IssuePatch{StatusID: field(done)}, actor.Person, nil) + require.NoError(t, err) + now = now.Add(time.Hour) + chart, err := tx.Burndown(s.ID, "points", project.ID) + require.NoError(t, err) + require.Equal(t, "2026-11-03", chart.Today) + require.Equal(t, 3, *chart.Points[0].Remaining) + require.Zero(t, *chart.Points[1].Remaining) + require.Nil(t, chart.Points[2].Scope) + issues, err := tx.Burndown(s.ID, "issues", "none") + require.NoError(t, err) + require.Equal(t, 1, *issues.Points[0].Scope) + // Current project membership controls historical chart attribution. + _, err = tx.PatchIssue(a.ID, IssuePatch{ProjectID: Field[string]{Present: true}}, actor.Person, nil) + require.NoError(t, err) + chart, err = tx.Burndown(s.ID, "points", project.ID) + require.NoError(t, err) + require.Zero(t, *chart.Points[0].Scope) + now = sprintClock("2026-11-10T02:00:00Z") // overdue close, last scheduled day includes close + closed, err := tx.CloseSprint(s.ID, nil, actor.Person) + require.NoError(t, err) + chart, err = tx.Burndown(s.ID, "points", "") + require.NoError(t, err) + require.Equal(t, 3, *chart.Points[6].Done) + velocity, err := tx.Velocity("points", "", 1) + require.NoError(t, err) + require.Equal(t, 3.0, *velocity.AveragePerWeek) + for name, v := range map[string]any{"Sprint": closed, "Burndown": chart, "Velocity": velocity} { + data, err := json.Marshal(v) + require.NoError(t, err) + t.Logf("%s JSON: %s", name, data) + } + return nil + })) +} +func TestSprintEstimatePagingAndProgress(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "sorting")) + actor := domain.Person{Sub: "alex"} + require.NoError(t, db.InWorkspace(t.Context(), "sorting", true, func(tx *Tx) error { + s, err := tx.CreateSprint(sprintInput("2026-11-02", 1)) + require.NoError(t, err) + story, err := tx.CreateIssue(IssueCreate{Title: "Story", Type: "story"}, actor, nil) + require.NoError(t, err) + for _, size := range []string{"XS", "M", "XL", "L", "S", ""} { + var estimate *string + if size != "" { + v := size + estimate = &v + } + _, err := tx.CreateIssue(IssueCreate{Title: "Child", Type: "task", ParentID: &story.ID, Estimate: estimate, SprintID: &s.ID}, actor, nil) + require.NoError(t, err) + } + story, err = tx.Issue(story.ID) + require.NoError(t, err) + require.Equal(t, 19, story.Progress.Points.Total) + got := []string{} + cursor := "" + for { + page, err := tx.ListIssues(ListOptions{Filter: domain.Filter{Sprint: []string{s.ID}}, Sort: domain.SortEstimate, Limit: 2, Cursor: cursor}) + require.NoError(t, err) + for _, item := range page.Items { + size := "" + if item.Estimate != nil { + size = *item.Estimate + } + got = append(got, size) + } + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + require.Equal(t, []string{"XL", "L", "M", "S", "XS", ""}, got) + page, err := tx.ListIssues(ListOptions{Filter: domain.Filter{Sprint: []string{"active"}}}) + require.NoError(t, err) + require.Empty(t, page.Items) + page, err = tx.ListIssues(ListOptions{Filter: domain.Filter{Sprint: []string{"none"}}}) + require.NoError(t, err) + require.Len(t, page.Items, 1) + return nil + })) +} + +func TestSprintSeedFixture(t *testing.T) { + db, _ := testutil.Database(t, Open) + now := sprintClock("2026-11-11T03:00:00Z") + db.Now = func() time.Time { return now } + require.NoError(t, db.SeedDev(t.Context(), "seed")) + require.NoError(t, db.SeedDev(t.Context(), "seed")) + require.NoError(t, db.InWorkspace(t.Context(), "seed", false, func(tx *Tx) error { + workspace, err := tx.Workspace() + require.NoError(t, err) + require.Equal(t, 40, workspace.IssueCount) + sprints, err := tx.Sprints("") + require.NoError(t, err) + require.Len(t, sprints, 5) + require.Equal(t, []int64{4, 5, 3, 2, 1}, []int64{sprints[0].Number, sprints[1].Number, sprints[2].Number, sprints[3].Number, sprints[4].Number}) + active, planned := sprints[0], sprints[1] + require.Equal(t, "2026-11-08", active.StartsOn) + require.Equal(t, "2026-11-21", active.EndsOn) + require.Equal(t, domain.Tally{ScopePoints: 10, ScopeIssues: 6}, active.Current) + require.Equal(t, active.Current, *active.Commitment) + require.Equal(t, domain.Tally{ScopePoints: 4, ScopeIssues: 3}, planned.Current) + require.Nil(t, planned.Commitment) + assertLedgerRecount(t, tx, active.ID) + assertLedgerRecount(t, tx, planned.ID) + page, err := tx.ListIssues(ListOptions{Sort: domain.SortNumber}) + require.NoError(t, err) + sized := 0 + sizes := map[string]bool{} + for _, issue := range page.Items { + if issue.Estimate != nil { + sized++ + sizes[*issue.Estimate] = true + } + } + require.Equal(t, 17, sized) + require.Len(t, sizes, 5) + require.Equal(t, "Speed up issue search", page.Items[36].Title) + require.Equal(t, "Show issue counts per project", page.Items[39].Title) + velocity, err := tx.Velocity("points", "", 8) + require.NoError(t, err) + require.Len(t, velocity.Items, 3) + for i, entry := range velocity.Items { + require.Equal(t, 18+3*i, entry.Completed) + require.Equal(t, 21+3*i, entry.Committed) + } + require.Equal(t, 21.0, *velocity.AveragePerWeek) + limited, err := tx.Velocity("points", "", 1) + require.NoError(t, err) + require.Len(t, limited.Items, 1) + require.Equal(t, 24, limited.Items[0].Completed) + require.Equal(t, 21.0, *limited.AveragePerWeek) + issues, err := tx.Velocity("issues", "", 8) + require.NoError(t, err) + require.Equal(t, 3.0, *issues.AveragePerWeek) + chart, err := tx.Burndown(active.ID, "points", "") + require.NoError(t, err) + require.Len(t, chart.Points, 14) + require.Equal(t, 10, *chart.Points[0].Scope) + require.Equal(t, 12, *chart.Points[1].Scope) + require.Equal(t, 10, *chart.Points[2].Scope) + require.Nil(t, chart.Points[4].Scope) + return nil + })) +} + +func TestSprintVelocityMixedLengthsAndRounding(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "velocity")) + now := sprintClock("2026-01-01T00:00:00Z") + db.Now = func() time.Time { return now } + actor := domain.Person{Sub: "alex"} + require.NoError(t, db.InWorkspace(t.Context(), "velocity", true, func(tx *Tx) error { + statuses, err := tx.Statuses() + require.NoError(t, err) + var done string + for _, s := range statuses { + if s.Category == "completed" { + done = s.ID + } + } + for _, fixture := range []struct { + start, size string + weeks int + }{{"2026-01-01", "M", 1}, {"2026-01-08", "XS", 1}, {"2026-01-15", "L", 2}, {"2026-01-29", "XL", 1}} { + start, err := time.Parse("2006-01-02", fixture.start) + require.NoError(t, err) + now = start.Add(-time.Hour) + s, err := tx.CreateSprint(sprintInput(fixture.start, fixture.weeks)) + require.NoError(t, err) + issue, err := tx.CreateIssue(IssueCreate{Title: "Member", Type: "task", Estimate: &fixture.size, SprintID: &s.ID}, actor, nil) + require.NoError(t, err) + now = start + _, err = tx.StartSprint(s.ID) + require.NoError(t, err) + now = start.Add(time.Hour) + _, err = tx.PatchIssue(issue.ID, IssuePatch{StatusID: field(done)}, actor, nil) + require.NoError(t, err) + now = start.AddDate(0, 0, 7*fixture.weeks-1) + _, err = tx.CloseSprint(s.ID, nil, actor) + require.NoError(t, err) + } + for _, unit := range []string{"points", "issues"} { + v, err := tx.Velocity(unit, "", 2) + require.NoError(t, err) + require.Len(t, v.Items, 2) + require.Equal(t, int64(3), v.Items[0].Sprint.Number) + require.Equal(t, int64(4), v.Items[1].Sprint.Number) + if unit == "points" { + require.Equal(t, 3.83, *v.AveragePerWeek) + } else { + require.Equal(t, 0.83, *v.AveragePerWeek) + } + } + return nil + })) +} + +func TestSprintConcurrentOverlap(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "concurrent")) + results := make(chan error, 2) + for range 2 { + go func() { + results <- db.InWorkspace(t.Context(), "concurrent", true, func(tx *Tx) error { _, err := tx.CreateSprint(sprintInput("2026-11-02", 1)); return err }) + }() + } + success, conflicts := 0, 0 + for range 2 { + err := <-results + if err == nil { + success++ + continue + } + var conflict *httpx.Error + require.ErrorAs(t, err, &conflict) + require.Equal(t, 409, conflict.Status) + conflicts++ + } + require.Equal(t, 1, success) + require.Equal(t, 1, conflicts) +} + +func TestSprintStartOverlapAndDST(t *testing.T) { + db, _ := testutil.Database(t, Open) + require.NoError(t, db.EnsureWorkspace(t.Context(), "dst")) + now := sprintClock("2026-10-30T16:00:00Z") + db.Now = func() time.Time { return now } + require.NoError(t, db.InWorkspace(t.Context(), "dst", true, func(tx *Tx) error { + timezone := "America/New_York" + _, err := tx.PatchWorkspace(nil, nil, nil, &timezone) + require.NoError(t, err) + a, err := tx.CreateSprint(sprintInput("2026-10-31", 1)) + require.NoError(t, err) + b, err := tx.CreateSprint(sprintInput("2026-11-07", 1)) + require.NoError(t, err) + _, err = tx.StartSprint(b.ID) + var conflict *httpx.Error + require.ErrorAs(t, err, &conflict) + require.Equal(t, 409, conflict.Status) + actor := domain.Person{Sub: "alex"} + size := "S" + _, err = tx.CreateIssue(IssueCreate{Title: "DST", Type: "task", Estimate: &size, SprintID: &a.ID}, actor, nil) + require.NoError(t, err) + now = sprintClock("2026-10-31T16:00:00Z") + a, err = tx.StartSprint(a.ID) + require.NoError(t, err) + now = sprintClock("2026-11-02T04:30:00Z") // still Nov 1 after clocks go back + chart, err := tx.Burndown(a.ID, "issues", "") + require.NoError(t, err) + require.Equal(t, "2026-11-01", chart.Today) + require.Equal(t, 1, *chart.Points[1].Remaining) + require.Nil(t, chart.Points[2].Scope) + return nil + })) +} diff --git a/cmd/server/internal/store/store.go b/cmd/server/internal/store/store.go index 6370a55..703a664 100644 --- a/cmd/server/internal/store/store.go +++ b/cmd/server/internal/store/store.go @@ -8,16 +8,22 @@ import ( "github.com/appthrust/appserver-go/appserver/httpx" "github.com/appthrust/appserver-go/appserver/pgstore" "github.com/lib/pq" + "time" ) //go:embed migrations/*.sql var migrations embed.FS // Store owns the tracker's queries and schema over the shared transaction runner. -type Store struct{ *pgstore.Store } +type Store struct { + *pgstore.Store + // Now may be injected before serving requests for deterministic sprint clocks. + Now func() time.Time +} type Tx struct { *pgstore.Tx WorkspaceID string + clock func() time.Time } func Open(ctx context.Context, dsn string) (*Store, error) { @@ -29,16 +35,28 @@ func Open(ctx context.Context, dsn string) (*Store, error) { } func (s *Store) Do(ctx context.Context, write bool, fn func(*Tx) error) error { - return translate(s.Store.Do(ctx, write, func(tx *pgstore.Tx) error { return fn(&Tx{Tx: tx}) })) + return translate(s.Store.Do(ctx, write, func(tx *pgstore.Tx) error { return fn(&Tx{Tx: tx, clock: s.Now}) })) } func (s *Store) InWorkspace(ctx context.Context, workspace string, write bool, fn func(*Tx) error) error { return s.Do(ctx, write, func(tx *Tx) error { tx.WorkspaceID = workspace + if write { + if err := tx.Exec(`SELECT id FROM tracker_workspace WHERE id=$1 FOR UPDATE`, workspace); err != nil { + return err + } + } return fn(tx) }) } +func (t *Tx) now() time.Time { + if t.clock != nil { + return t.clock().UTC() + } + return time.Now().UTC() +} + func invalid(message string) error { return httpx.Fail(400, "invalid", message) } func translate(err error) error { diff --git a/cmd/server/internal/store/store_test.go b/cmd/server/internal/store/store_test.go index e6c35cf..5f4f320 100644 --- a/cmd/server/internal/store/store_test.go +++ b/cmd/server/internal/store/store_test.go @@ -35,7 +35,7 @@ func TestSeedPagingAndFilters(t *testing.T) { require.NoError(t, database.InWorkspace(t.Context(), "pj-test", true, func(tx *Tx) error { w, err := tx.Workspace() require.NoError(t, err) - require.Equal(t, 36, w.IssueCount) + require.Equal(t, 40, w.IssueCount) statuses, err := tx.Statuses() require.NoError(t, err) require.Len(t, statuses, 6) @@ -46,7 +46,7 @@ func TestSeedPagingAndFilters(t *testing.T) { require.NoError(t, err) require.Len(t, views, 3) require.NoError(t, tx.Exec(`UPDATE tracker_issue SET created_at='2026-01-01T00:00:00Z',updated_at='2026-01-01T00:00:00Z'`)) - for _, order := range []domain.Sort{domain.SortUpdated, domain.SortCreated, domain.SortNumber, domain.SortPriority} { + for _, order := range []domain.Sort{domain.SortUpdated, domain.SortCreated, domain.SortNumber, domain.SortPriority, domain.SortEstimate} { seen := map[string]bool{} cursor := "" for { @@ -63,7 +63,7 @@ func TestSeedPagingAndFilters(t *testing.T) { } cursor = *page.NextCursor } - require.Len(t, seen, 36) + require.Len(t, seen, 40) } for _, filter := range []domain.Filter{{Type: []string{"bug"}}, {Assignee: []string{"me"}}, {Category: []string{"started"}}, {Q: "Dashboard"}, {Environment: []string{"local"}}, {Surface: []string{"apth"}}, {Label: []string{labels[0].ID}}, {Status: []string{statuses[0].ID}}, {Priority: []string{"urgent"}}, {CreatedAfter: "2025-01-01T00:00:00Z"}, {Parent: "none"}} { page, err := tx.ListIssues(ListOptions{Filter: filter, Subject: "dev-alex"}) @@ -132,7 +132,7 @@ func TestMutationsAndIsolation(t *testing.T) { require.Error(t, tx.DeleteStatus(statuses[1].ID)) require.Error(t, tx.DeleteStatus(statuses[5].ID)) key := "NEW" - _, err = tx.PatchWorkspace(&key, nil) + _, err = tx.PatchWorkspace(&key, nil, nil, nil) require.NoError(t, err) item, err = tx.Issue("new-1") require.NoError(t, err) diff --git a/cmd/server/internal/store/workspace.go b/cmd/server/internal/store/workspace.go index 3e9323e..61c31fb 100644 --- a/cmd/server/internal/store/workspace.go +++ b/cmd/server/internal/store/workspace.go @@ -6,6 +6,7 @@ import ( "errors" "slices" "strings" + "time" "github.com/appthrust/appserver-go/appserver/httpx" "github.com/appthrust/tracker/cmd/server/internal/domain" @@ -40,10 +41,10 @@ func (t *Tx) EnsureWorkspace() error { } func (t *Tx) Workspace() (domain.Workspace, error) { var w domain.Workspace - err := t.SQL.QueryRowContext(t.Context, `SELECT id,key,name,(SELECT count(*) FROM tracker_issue WHERE workspace_id=$1 AND deleted_at IS NULL),created_at,updated_at FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&w.ID, &w.Key, &w.Name, &w.IssueCount, &w.CreatedAt, &w.UpdatedAt) + err := t.SQL.QueryRowContext(t.Context, `SELECT id,key,name,(SELECT count(*) FROM tracker_issue WHERE workspace_id=$1 AND deleted_at IS NULL),created_at,updated_at,sprint_length_weeks,timezone FROM tracker_workspace WHERE id=$1`, t.WorkspaceID).Scan(&w.ID, &w.Key, &w.Name, &w.IssueCount, &w.CreatedAt, &w.UpdatedAt, &w.SprintLengthWeeks, &w.Timezone) return w, err } -func (t *Tx) PatchWorkspace(key, name *string) (domain.Workspace, error) { +func (t *Tx) PatchWorkspace(key, name *string, lengthWeeks *int, timezone *string) (domain.Workspace, error) { w, err := t.Workspace() if err != nil { return w, err @@ -54,10 +55,22 @@ func (t *Tx) PatchWorkspace(key, name *string) (domain.Workspace, error) { if name != nil { w.Name = strings.TrimSpace(*name) } + if lengthWeeks != nil { + w.SprintLengthWeeks = *lengthWeeks + } + if timezone != nil { + w.Timezone = *timezone + } + if w.SprintLengthWeeks != 1 && w.SprintLengthWeeks != 2 { + return w, &domain.FieldError{Path: "sprintLengthWeeks", Message: "Sprint length must be 1 or 2 weeks"} + } + if _, err := time.LoadLocation(w.Timezone); err != nil || w.Timezone == "" || w.Timezone == "Local" { + return w, &domain.FieldError{Path: "timezone", Message: "Timezone must be an IANA timezone name"} + } if !domain.ValidKey(w.Key) || !domain.Text(w.Name, 1, 100) { return w, invalid("Workspace requires a key of 2 to 6 uppercase letters/digits and a name of 1 to 100 characters") } - err = t.Exec(`UPDATE tracker_workspace SET key=$2,name=$3,updated_at=now() WHERE id=$1`, t.WorkspaceID, w.Key, w.Name) + err = t.Exec(`UPDATE tracker_workspace SET key=$2,name=$3,sprint_length_weeks=$4,timezone=$5,updated_at=now() WHERE id=$1`, t.WorkspaceID, w.Key, w.Name, w.SprintLengthWeeks, w.Timezone) if err != nil { return w, err } diff --git a/design/API.md b/design/API.md index f004750..f8240b6 100644 --- a/design/API.md +++ b/design/API.md @@ -279,3 +279,151 @@ the existing issues so earlier numbers do not move. Existing seeded issues `stories[n % 4]`; the rest keep `parent: null`. One shared view `By epic` (`layout: 'board'`, `groupBy: 'epic'`, empty filter) is added after `Bugs` and `My issues`. + +## Sprints, estimates, burndown and velocity (v0.1.10) + +Work is cut into one- or two-week sprints; issues carry a T-shirt-size +estimate; a ledger of signed deltas yields burndown and velocity. + +| Entity | Owner (sole writer) | Lifecycle | Invariants | +| --- | --- | --- | --- | +| **Estimate** (field on Issue) | any signed-in user | set, changed, cleared | T-shirt size `XS`, `S`, `M`, `L`, `XL`, or `null` (not estimated); not allowed on `epic`. Each size has a fixed Fibonacci point weight used only for sums: `XS=1`, `S=2`, `M=3`, `L=5`, `XL=8` (`domain.SizePoints`). People pick and read sizes; numbers appear only in sprint totals and charts. | +| **Sprint** | any signed-in user; delete Admin | `planned → active → closed`, explicit `start` and `close`; never reopened | `lengthWeeks ∈ {1, 2}`; `endsOn = startsOn + 7·lengthWeeks − 1`; date ranges of non-closed sprints do not overlap; at most one `active`; `number` from a per-workspace sequence; only a `planned` sprint is deleted or re-dated. | +| **Sprint membership** (`issue.sprintId`) | any signed-in user | set, moved, cleared; frozen once the sprint is closed | target sprint is `planned` or `active`; `epic` cannot be a member; **lineage-exclusive**: an issue cannot join a sprint that already contains one of its strict ancestors or descendants. | +| **Sprint event** (ledger) | server, in the transaction of the issue write that caused it | append-only; no rows after `closedAt` | one row per (write, sprint) with four signed deltas; the sum of a sprint's rows equals its current totals. | +| **Sprint settings** (on Workspace) | Admin | defaults | `sprintLengthWeeks ∈ {1, 2}` (default `1`), `timezone` IANA name (default `Asia/Tokyo`). | + +Vocabulary: **scope** = member issues that are not deleted and not in a +`canceled` status; **done** = scope issues in a `completed` status; +**remaining** = scope − done; **commitment** = scope at `startedAt`; +**velocity** = done at `closedAt`. Every quantity exists in two units, +`points` (sum of the members' size weights, `null` counts 0) and `issues` +(count). + + +### The ledger rule (pure) + +```go +// domain/sprint.go — no context, clock, or I/O. +type SprintStanding struct { SprintID string; Size string /* "" = not estimated */; Category string; Deleted bool } +type SprintTally struct { ScopePoints, ScopeIssues, DonePoints, DoneIssues int } + +func Contribution(s SprintStanding) SprintTally // zero when SprintID=="" or Deleted or Category==canceled +func SprintDeltas(before, after SprintStanding) map[string]SprintTally // per sprint id; zero tallies omitted +func Burndown(baseline SprintTally, events []SprintEvent, days []Day) []BurndownPoint +func ValidateSprintDates(startsOn Date, lengthWeeks int, others []SprintSpan) error +func ValidateMembership(issueType string, sprintState string, lineageMembers int) error +``` + +`SprintDeltas` is `Contribution(after) − Contribution(before)`, attributed to +each standing's sprint. Moving between sprints, estimating, completing, +reopening, canceling and soft-deleting are all the same subtraction, so a new +field that affects scope extends `SprintStanding` and nothing else. The store +calls it in `CreateIssue`, `PatchIssue` and `DeleteIssue` after loading the +row and writes one `tracker_sprint_event` per returned sprint that is not +closed. + + +```ts +type SprintState = 'planned' | 'active' | 'closed' +type Tally = { scopePoints: number; scopeIssues: number; donePoints: number; doneIssues: number } +type Sprint = { + id: string; number: number; name: string /* 1–60, default "Sprint " */; goal: string /* ≤ 4096 bytes */ + state: SprintState; lengthWeeks: 1 | 2 + startsOn: string; endsOn: string /* YYYY-MM-DD, workspace timezone, inclusive */ + startedAt: string | null; closedAt: string | null + current: Tally // sum of the ledger + commitment: Tally | null // ledger at startedAt; null while planned + createdAt: string; updatedAt: string +} +type SprintRef = { id: string; number: number; name: string; state: SprintState } +type Unit = 'points' | 'issues' +type BurndownPoint = { day: string; scope: number; done: number; remaining: number; ideal: number } +type Burndown = { sprint: SprintRef; unit: Unit; today: string; points: BurndownPoint[] /* one per day startsOn..endsOn; days after today omit scope/done/remaining */ } +type VelocityEntry = { sprint: SprintRef; lengthWeeks: 1 | 2; committed: number; completed: number } +type Velocity = { unit: Unit; items: VelocityEntry[] /* closed sprints, oldest first */; averagePerWeek: number | null /* over the last 3 closed sprints */ } +``` + +Changes to existing shapes: + +- `type Size = 'XS' | 'S' | 'M' | 'L' | 'XL'`. `Issue` and `IssueSummary` gain + `estimate: Size | null` and + `sprint: SprintRef | null`. +- `POST /issues` accepts `estimate?`, `sprintId?`; `PATCH /issues/{id}` + accepts `estimate` and `sprintId` (`null` clears). Violations → 400 + `invalid` with path `estimate` or `sprintId` (unknown or closed sprint, + epic, lineage member already in the sprint). A `PATCH` that changes `type` + or `parentId` re-checks membership, as the hierarchy check does. +- `Filter` gains `sprint?: (string | 'active' | 'none')[]`. +- `Sort` gains `'estimate'` (`XL` → `XS`, `null` last, then `updated` desc). +- `View.groupBy` gains `'sprint'`. +- `Activity.field` gains `'estimate'` (raw value) and `'sprint'` + (`SprintRef | null`). +- `Workspace` gains `sprintLengthWeeks: 1 | 2` and `timezone: string`; + `PATCH /workspace` accepts both (Admin). +- `Progress` (epic/story) gains `points: { total: number; completed: number }` + (sum of size weights). + +| Method & path | Body → Response | Authz | +| --- | --- | --- | +| `GET /sprints?state=` | → `{ items: Sprint[] }` active, then planned by `startsOn`, then closed newest first | any | +| `POST /sprints` | `{ name?, goal?, startsOn?, lengthWeeks? }` → `Sprint` 201. Defaults: `lengthWeeks` = workspace setting; `startsOn` = day after the latest non-closed sprint's `endsOn`, else the coming Monday. Overlap → 409 | any | +| `GET /sprints/{id}` | → `Sprint` | any | +| `PATCH /sprints/{id}` | `{ name?, goal?, startsOn?, lengthWeeks? }` → `Sprint`; dates only while `planned` (409 otherwise) | any | +| `POST /sprints/{id}/start` | → `Sprint`; 409 when another sprint is active or this one is not `planned`. Sets `startedAt`; `startsOn` becomes today when it was in the future, keeping `lengthWeeks` | any | +| `POST /sprints/{id}/close` | `{ moveIncompleteTo: string \| null }` → `Sprint`; target is a `planned` sprint id or `null` (backlog). Sets `closedAt`, then moves scope issues that are not done; the move is recorded only on the target's ledger | any | +| `DELETE /sprints/{id}` | 204; only `planned`; members return to the backlog | Admin | +| `GET /sprints/{id}/burndown?unit=&project=` | → `Burndown` | any | +| `GET /velocity?unit=&project=&limit=` | → `Velocity`; `limit` default 8, max 26 | any | + +Chart semantics: + +- Day boundaries are midnights in `Workspace.timezone`. A point is the ledger + summed up to the end of that day (up to now for `today`, up to `closedAt` + for the last day of a closed sprint). +- `ideal` descends linearly from the commitment's remaining at `startsOn` to 0 + at `endsOn`, flat across Saturdays and Sundays. +- `project` (an id or `none`) restricts the sum to events of issues currently + in that project. +- `Velocity.completed` is done at `closedAt`; `committed` is scope at + `startedAt`. `averagePerWeek` divides by `lengthWeeks`, so one- and two-week + sprints are comparable; the SPA shows `averagePerWeek × lengthWeeks` as the + suggested commitment while planning. + +Storage (migration `011_sprints.sql`): + +```sql +ALTER TABLE tracker_workspace ADD sprint_length_weeks int NOT NULL DEFAULT 1 CHECK (sprint_length_weeks IN (1,2)), + ADD timezone text NOT NULL DEFAULT 'Asia/Tokyo'; +CREATE TABLE tracker_sprint ( + id text PRIMARY KEY, workspace_id text NOT NULL REFERENCES tracker_workspace(id), + number bigint NOT NULL, name text NOT NULL, goal text NOT NULL DEFAULT '', + length_weeks int NOT NULL CHECK (length_weeks IN (1,2)), starts_on date NOT NULL, ends_on date NOT NULL, + started_at timestamptz, closed_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + UNIQUE (workspace_id, number), + CHECK (ends_on = starts_on + 7 * length_weeks - 1), + CHECK (closed_at IS NULL OR started_at IS NOT NULL) +); +CREATE UNIQUE INDEX tracker_sprint_one_active ON tracker_sprint (workspace_id) WHERE started_at IS NOT NULL AND closed_at IS NULL; +ALTER TABLE tracker_issue ADD estimate text CHECK (estimate IN ('XS','S','M','L','XL')), + ADD sprint_id text REFERENCES tracker_sprint(id), + ADD CHECK (type <> 'epic' OR (estimate IS NULL AND sprint_id IS NULL)); +CREATE INDEX tracker_issue_sprint ON tracker_issue (sprint_id) WHERE sprint_id IS NOT NULL; +CREATE TABLE tracker_sprint_event ( + id text PRIMARY KEY, sprint_id text NOT NULL REFERENCES tracker_sprint(id) ON DELETE CASCADE, + issue_id text NOT NULL REFERENCES tracker_issue(id) ON DELETE CASCADE, at timestamptz NOT NULL DEFAULT now(), + scope_points int NOT NULL, scope_issues int NOT NULL, done_points int NOT NULL, done_issues int NOT NULL +); +CREATE INDEX tracker_sprint_event_sprint ON tracker_sprint_event (sprint_id, at); +``` + +`state` is derived from `started_at`/`closed_at`, not stored. The overlap +invariant is checked in the transaction that takes the existing workspace row +lock; the partial unique index backs "one active". + +Fixture (dev seed and SPA mock, identical): three closed one-week sprints +with ledgers that yield velocities 18, 21, 24 points, one active two-week +sprint on its fourth day with a scope increase and one cancellation, one +planned sprint; about half of the seeded work items carry a size, spread +over all five. diff --git a/hack/smoke.sh b/hack/smoke.sh index f90703e..028182b 100755 --- a/hack/smoke.sh +++ b/hack/smoke.sh @@ -80,12 +80,12 @@ PY ) auth="Authorization: Bearer $token" request() { curl -fsS -H "$auth" -H 'Content-Type: application/json' "$@"; } -request "$base/workspace" | jq -e '.key == "APT" and .issueCount == 36' >/dev/null +request "$base/workspace" | jq -e '.key == "APT" and .issueCount == 40' >/dev/null project=$(request -X POST "$base/projects" --data '{"name":"Smoke project","color":"blue"}') project_id=$(jq -er '.id' <<<"$project") issue=$(request -X POST "$base/issues" --data "{\"title\":\"Smoke bug\",\"type\":\"bug\",\"projectId\":\"$project_id\",\"report\":{\"environment\":\"local\",\"surface\":\"apth\",\"steps\":\"Run smoke\",\"expected\":\"Success\",\"actual\":\"Under investigation\"}}") id=$(jq -er '.id' <<<"$issue") -jq -e '.identifier == "APT-37" and .report.environment == "local" and .reporter.sub == "smoke-reporter"' <<<"$issue" >/dev/null +jq -e '.identifier == "APT-41" and .report.environment == "local" and .reporter.sub == "smoke-reporter"' <<<"$issue" >/dev/null jq -e --arg project "$project_id" '.projectId == $project' <<<"$issue" >/dev/null request --get "$base/issues" --data-urlencode "filter={\"project\":[\"$project_id\"]}" | jq -e --arg id "$id" --arg project "$project_id" '.items | length == 1 and .[0].id == $id and .[0].projectId == $project' >/dev/null request --get "$base/issues" --data-urlencode 'filter={"reporter":["me"]}' | jq -e --arg id "$id" '.items | length == 1 and .[0].id == $id and .[0].reporter.sub == "smoke-reporter"' >/dev/null @@ -119,4 +119,18 @@ request --get "$base/issues" --data-urlencode 'filter={"project":["none"],"q":"S request "$base/issues/$id/timeline" | jq -e --arg project "$project_id" '[.items[] | select(.kind == "activity" and .activity.field == "project") | .activity] | length == 1 and .[0].from == $project and .[0].to == null' >/dev/null code=$(curl -sS -o "$work/deleted" -w '%{http_code}' -H "$auth" -X DELETE "$base/projects/$project_id") [[ "$code" == 204 && ! -s "$work/deleted" ]] -printf 'Tracker smoke passed: project → issue → reporter filter → invalid reporter → epic → story → parent patch → ancestry → progress → referenced delete conflict → comment → attachment → status → timeline → project filter → no project → project delete\n' +# Finish the dev fixture's active sprint before exercising a fresh lifecycle. +active=$(request "$base/sprints?state=active" | jq -er '.items[0].id') +request -X POST "$base/sprints/$active/close" --data '{"moveIncompleteTo":null}' | jq -e '.state == "closed"' >/dev/null +sprint=$(request -X POST "$base/sprints" --data '{"name":"Smoke sprint","lengthWeeks":1}') +sprint_id=$(jq -er '.id' <<<"$sprint") +first=$(request -X POST "$base/issues" --data "{\"title\":\"Sprint first\",\"type\":\"task\",\"estimate\":\"M\",\"sprintId\":\"$sprint_id\"}") +first_id=$(jq -er '.id' <<<"$first") +request -X POST "$base/issues" --data "{\"title\":\"Sprint second\",\"type\":\"feature\",\"estimate\":\"L\",\"sprintId\":\"$sprint_id\"}" | jq -e '.estimate == "L"' >/dev/null +request -X POST "$base/sprints/$sprint_id/start" | jq -e '.state == "active" and .commitment.scopePoints == 8 and .commitment.scopeIssues == 2' >/dev/null +request "$base/sprints/$sprint_id/burndown?unit=points" | jq -e '. as $chart | [.points[] | select(.day == $chart.today)][0].remaining == 8' >/dev/null +request -X PATCH "$base/issues/$first_id" --data "{\"statusId\":\"$status\"}" | jq -e '.completedAt != null' >/dev/null +request "$base/sprints/$sprint_id/burndown?unit=points" | jq -e '. as $chart | [.points[] | select(.day == $chart.today)][0] | .remaining == 5 and .done == 3 and .scope == 8' >/dev/null +request -X POST "$base/sprints/$sprint_id/close" --data '{"moveIncompleteTo":null}' | jq -e '.state == "closed" and .current.donePoints == 3' >/dev/null +request "$base/velocity?unit=points&limit=1" | jq -e --arg id "$sprint_id" '.items | length == 1 and .[0].sprint.id == $id and .[0].committed == 8 and .[0].completed == 3' >/dev/null +printf 'Tracker smoke passed: project → issue → reporter filter → invalid reporter → epic → story → parent patch → ancestry → progress → referenced delete conflict → comment → attachment → status → timeline → project filter → no project → project delete → sprint → estimates → start → burndown drop → close → velocity\n' diff --git a/web/package.json b/web/package.json index fa73952..daeea42 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@appthrust/tracker", - "version": "0.1.9", + "version": "0.1.10", "private": true, "type": "module", "scripts": { diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index d198cfa..b254886 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -4,14 +4,18 @@ // every query refetches every 15 s while the tab is visible and on window // focus (no push in v1). Issue edits (status, priority, assignee, labels, // project, parent, …) are optimistic: lists and the open issue change at once -// and roll back on failure. +// and roll back on failure. Sprints, burndown and velocity share one key +// prefix, refreshed by every issue write (estimates, statuses and membership +// move the ledger). import { infiniteQueryOptions, QueryClient, queryOptions, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { compactFilter, levelOf } from '../model/issues' +import { sprintRef } from '../model/sprints' import { trackerApi, TrackerApiError, type CreateIssueInput, type CreateProjectInput, + type CreateSprintInput, type CreateViewInput, type Filter, type Issue, @@ -22,10 +26,15 @@ import { type Person, type Project, type Sort, + type Sprint, + type SprintRef, type StatusCategory, + type Unit, type UpdateIssueInput, type UpdateProjectInput, + type UpdateSprintInput, type UpdateViewInput, + type UpdateWorkspaceInput, } from './tracker' /** Retries for a call nothing answered (rollout gap, network blip). */ @@ -52,6 +61,7 @@ export const queryClient = new QueryClient({ export const TRACKER_KEY = ['tracker'] as const const ISSUES_KEY = [...TRACKER_KEY, 'issues'] as const const ISSUE_KEY = [...TRACKER_KEY, 'issue'] as const +const SPRINTS_KEY = [...TRACKER_KEY, 'sprints'] as const export const meQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'me'], queryFn: () => trackerApi.me(), staleTime: 60_000 }) export const workspaceQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'workspace'], queryFn: () => trackerApi.workspace.get() }) @@ -60,6 +70,12 @@ export const labelsQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'labels'], export const viewsQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'views'], queryFn: () => trackerApi.views.list() }) /** Every project, archived included: issues keep showing an archived project's name; pickers offer active ones only. */ export const projectsQuery = queryOptions({ queryKey: [...TRACKER_KEY, 'projects'], queryFn: () => trackerApi.projects.list({ includeArchived: true }) }) +/** Every sprint in API order (active, planned by start, closed newest first). */ +export const sprintsQuery = queryOptions({ queryKey: [...SPRINTS_KEY, 'list'], queryFn: () => trackerApi.sprints.list() }) +export const sprintQuery = (id: string) => queryOptions({ queryKey: [...SPRINTS_KEY, 'one', id], queryFn: () => trackerApi.sprints.get(id) }) +export const burndownQuery = (id: string, unit: Unit, project?: string | null) => + queryOptions({ queryKey: [...SPRINTS_KEY, 'burndown', id, unit, project ?? null], queryFn: () => trackerApi.sprints.burndown(id, { unit, project }) }) +export const velocityQuery = (unit: Unit, project?: string | null) => queryOptions({ queryKey: [...SPRINTS_KEY, 'velocity', unit, project ?? null], queryFn: () => trackerApi.velocity({ unit, project }) }) /** Lists load the server maximum per page; "もっと見る" fetches the next cursor page. */ export const ISSUE_PAGE_SIZE = 200 @@ -132,9 +148,10 @@ export const peopleQuery = (q: string) => /** * The summary/issue as it will look after `input`; `assignee` is the picked * person for display, `parent` the picked parent's summary, from which the - * derived `epic`/`story` follow at once (the server recomputes them). + * derived `epic`/`story` follow at once (the server recomputes them), and + * `sprint` the ref of the sprint `sprintId` names. */ -export function applyIssuePatch(issue: T, input: UpdateIssueInput, assignee?: Person | null, parent?: IssueSummary | null): T { +export function applyIssuePatch(issue: T, input: UpdateIssueInput, assignee?: Person | null, parent?: IssueSummary | null, sprint?: SprintRef | null): T { const next: T = { ...issue } if (input.title !== undefined) next.title = input.title if (input.type !== undefined) next.type = input.type @@ -144,6 +161,8 @@ export function applyIssuePatch(issue: T, input: UpdateI if (input.dueOn !== undefined) next.dueOn = input.dueOn if (input.report !== undefined) next.report = input.report if (input.projectId !== undefined) next.projectId = input.projectId + if (input.estimate !== undefined) next.estimate = input.estimate + if (input.sprintId !== undefined) next.sprint = input.sprintId === null ? null : (sprint ?? issue.sprint) if (input.assigneeSub !== undefined) next.assignee = input.assigneeSub === null ? null : (assignee ?? issue.assignee) if (input.parentId === null) Object.assign(next, { parent: null, epic: null, story: null }) else if (input.parentId !== undefined && parent?.id === input.parentId) { @@ -176,7 +195,8 @@ export function useUpdateIssue() { await Promise.all([client.cancelQueries({ queryKey: ISSUES_KEY }), client.cancelQueries({ queryKey: ISSUE_KEY })]) const lists = client.getQueriesData({ queryKey: ISSUES_KEY }) const details = client.getQueriesData({ queryKey: ISSUE_KEY }) - patchCaches(client, id, (issue) => applyIssuePatch(issue, input, assignee, parent)) + const picked = input.sprintId ? client.getQueryData(sprintsQuery.queryKey)?.find((sprint) => sprint.id === input.sprintId) : undefined + patchCaches(client, id, (issue) => applyIssuePatch(issue, input, assignee, parent, picked ? sprintRef(picked) : undefined)) return { lists, details } }, onError: (_error, _edit, snapshot) => { @@ -192,6 +212,8 @@ export function useUpdateIssue() { void client.invalidateQueries({ queryKey: [...TRACKER_KEY, 'timeline', id] }) // Project and status changes move the per-project counts. void client.invalidateQueries({ queryKey: projectsQuery.queryKey }) + // Estimates, statuses and membership move sprint tallies and charts. + void client.invalidateQueries({ queryKey: SPRINTS_KEY }) }, }) } @@ -211,6 +233,7 @@ const invalidateIssues = (client: QueryClient) => client.invalidateQueries({ queryKey: ISSUE_KEY }), client.invalidateQueries({ queryKey: workspaceQuery.queryKey }), client.invalidateQueries({ queryKey: projectsQuery.queryKey }), + client.invalidateQueries({ queryKey: SPRINTS_KEY }), ]) export function useCreateIssue() { @@ -270,7 +293,7 @@ export function useViewMutations() { export function useUpdateWorkspace() { const client = useQueryClient() return useMutation({ - mutationFn: (input: { key?: string; name?: string }) => trackerApi.workspace.update(input), + mutationFn: (input: UpdateWorkspaceInput) => trackerApi.workspace.update(input), onSuccess: (workspace) => { client.setQueryData(workspaceQuery.queryKey, workspace) // A new key renames every identifier. @@ -328,3 +351,23 @@ export function useProjectMutations() { remove: useMutation({ mutationFn: (id: Project['id']) => trackerApi.projects.remove(id), onSuccess }), } } + +/** Sprint writes refresh every sprint, chart and issue list (start re-dates; close and delete move members). */ +export function useSprintMutations() { + const client = useQueryClient() + const onSuccess = () => void Promise.all([client.invalidateQueries({ queryKey: SPRINTS_KEY }), client.invalidateQueries({ queryKey: ISSUES_KEY }), client.invalidateQueries({ queryKey: ISSUE_KEY })]) + return { + create: useMutation({ + mutationFn: (input: CreateSprintInput) => trackerApi.sprints.create(input), + // The caller may navigate to the new sprint at once. + onSuccess: (sprint) => { + client.setQueryData(sprintQuery(sprint.id).queryKey, sprint) + onSuccess() + }, + }), + update: useMutation({ mutationFn: ({ id, input }: { id: string; input: UpdateSprintInput }) => trackerApi.sprints.update(id, input), onSuccess }), + start: useMutation({ mutationFn: (id: string) => trackerApi.sprints.start(id), onSuccess }), + close: useMutation({ mutationFn: ({ id, moveIncompleteTo }: { id: string; moveIncompleteTo: string | null }) => trackerApi.sprints.close(id, moveIncompleteTo), onSuccess }), + remove: useMutation({ mutationFn: (id: string) => trackerApi.sprints.remove(id), onSuccess }), + } +} diff --git a/web/src/api/tracker.ts b/web/src/api/tracker.ts index 67a5d11..dc93c21 100644 --- a/web/src/api/tracker.ts +++ b/web/src/api/tracker.ts @@ -8,7 +8,9 @@ export type Person = { sub: string; name: string; avatarUrl?: string; email?: st export type Role = 'Admin' | 'Editor' | 'Viewer' export type Me = Person & { role: Role; isAdmin: boolean } -export type Workspace = { id: string; key: string; name: string; issueCount: number; createdAt: string; updatedAt: string } +/** `sprintLengthWeeks` is the default length of a new sprint; `timezone` (IANA) sets the day boundaries of sprint dates and charts. */ +export type Workspace = { id: string; key: string; name: string; issueCount: number; sprintLengthWeeks: SprintLength; timezone: string; createdAt: string; updatedAt: string } +export type UpdateWorkspaceInput = { key?: string; name?: string; sprintLengthWeeks?: SprintLength; timezone?: string } export type StatusCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled' export type Status = { id: string; name: string; category: StatusCategory; position: number; color: string } @@ -39,8 +41,49 @@ export type Surface = 'dashboard' | 'platform-api' | 'apth' | 'builder-console' export type Report = { environment: string; surface: Surface; version?: string; steps?: string; expected?: string; actual?: string } export type IssueRef = { id: string; identifier: string; title: string; statusId: string } -/** Over all level-0 descendants: `total` excludes canceled ones, `completed` counts those in a completed status. */ -export type Progress = { total: number; completed: number } +/** Over all level-0 descendants: `total` excludes canceled ones, `completed` counts those in a completed status; `points` sums their size weights the same way. */ +export type Progress = { total: number; completed: number; points: { total: number; completed: number } } + +/** T-shirt size estimate; each size has a fixed point weight used only for sprint sums (model/sprints.ts `SIZE_POINTS`). */ +export type Size = 'XS' | 'S' | 'M' | 'L' | 'XL' +export type SprintState = 'planned' | 'active' | 'closed' +export type SprintLength = 1 | 2 +/** scope = members not deleted and not canceled; done = scope members in a completed status; each in points and issues. */ +export type Tally = { scopePoints: number; scopeIssues: number; donePoints: number; doneIssues: number } +export type Sprint = { + id: string + number: number + /** 1–60 characters, default "Sprint ". */ + name: string + /** ≤ 4096 bytes. */ + goal: string + state: SprintState + lengthWeeks: SprintLength + /** YYYY-MM-DD in the workspace timezone, inclusive; `endsOn = startsOn + 7·lengthWeeks − 1`. */ + startsOn: string + endsOn: string + startedAt: string | null + closedAt: string | null + /** The sum of the sprint's ledger. */ + current: Tally + /** The ledger at `startedAt`; null while planned. */ + commitment: Tally | null + createdAt: string + updatedAt: string +} +export type SprintRef = { id: string; number: number; name: string; state: SprintState } +export type Unit = 'points' | 'issues' +/** Days after `today` carry only `day` and `ideal`. */ +export type BurndownPoint = { day: string; scope?: number; done?: number; remaining?: number; ideal: number } +export type Burndown = { sprint: SprintRef; unit: Unit; today: string; points: BurndownPoint[] } +export type VelocityEntry = { sprint: SprintRef; lengthWeeks: SprintLength; committed: number; completed: number } +/** `items`: closed sprints, oldest first; `averagePerWeek` over the last three closed sprints, null before the first close. */ +export type Velocity = { unit: Unit; items: VelocityEntry[]; averagePerWeek: number | null } +export type CreateSprintInput = { name?: string; goal?: string; startsOn?: string; lengthWeeks?: SprintLength } +/** Dates (`startsOn`, `lengthWeeks`) only while planned. */ +export type UpdateSprintInput = Partial<{ name: string; goal: string; startsOn: string; lengthWeeks: SprintLength }> +export type ChartScope = { unit: Unit; project?: string | null } + export type Issue = { id: string /** `KEY-123` */ @@ -64,6 +107,10 @@ export type Issue = { story: IssueRef | null /** Non-null iff `type` is `epic` or `story`. */ progress: Progress | null + /** Not allowed on an epic (always null there). */ + estimate: Size | null + /** Null = backlog; an epic is never a member. */ + sprint: SprintRef | null children: IssueRef[] blocks: IssueRef[] blockedBy: IssueRef[] @@ -97,6 +144,8 @@ export type ActivityField = | 'attachment' | 'deleted' | 'project' + | 'estimate' + | 'sprint' export type Activity = { id: string; issueId: string; actor: Person; field: ActivityField; from: unknown; to: unknown; createdAt: string } export type TimelineItem = { kind: 'activity'; activity: Activity } | { kind: 'comment'; comment: Comment } @@ -122,12 +171,14 @@ export type Filter = { epic?: string[] /** The issue's derived `story` is one of these ids, or `none` for issues without one. */ story?: string[] + /** Sprint ids, `active` (the active sprint) or `none` (the backlog). */ + sprint?: string[] } -/** updated/created: desc; priority: urgent→none then updated desc; number: asc. */ -export type Sort = 'updated' | 'created' | 'priority' | 'number' +/** updated/created: desc; priority: urgent→none then updated desc; number: asc; estimate: XL→XS, none last, then updated desc. */ +export type Sort = 'updated' | 'created' | 'priority' | 'number' | 'estimate' export type ViewLayout = 'list' | 'board' -/** Client-side sectioning of a list or board by the issues' derived `epic` or `story`. */ -export type GroupBy = 'none' | 'epic' | 'story' +/** Client-side sectioning of a list or board by the issues' derived `epic` or `story`, or by sprint (backlog last). */ +export type GroupBy = 'none' | 'epic' | 'story' | 'sprint' export type View = { id: string; name: string; owner: Person; shared: boolean; layout: ViewLayout; groupBy: GroupBy; filter: Filter; sort: Sort; position: number; createdAt: string; updatedAt: string } export type IssuePage = { items: IssueSummary[]; nextCursor: string | null } @@ -146,6 +197,8 @@ export type CreateIssueInput = { dueOn?: string report?: Report projectId?: string + estimate?: Size + sprintId?: string } export type UpdateIssueInput = Partial<{ title: string @@ -161,6 +214,10 @@ export type UpdateIssueInput = Partial<{ report: Report | null /** null clears the project. */ projectId: string | null + /** null clears. */ + estimate: Size | null + /** null moves the issue to the backlog. */ + sprintId: string | null }> export type CreateViewInput = { name: string; layout?: ViewLayout; groupBy?: GroupBy; filter?: Filter; sort?: Sort; shared?: boolean } export type UpdateViewInput = Partial @@ -209,7 +266,7 @@ export interface TrackerApi { me(): Promise workspace: { get(): Promise - update(input: { key?: string; name?: string }): Promise + update(input: UpdateWorkspaceInput): Promise } statuses: { list(): Promise @@ -257,6 +314,21 @@ export interface TrackerApi { update(id: string, input: UpdateViewInput): Promise remove(id: string): Promise } + sprints: { + /** Active, then planned by `startsOn`, then closed newest first. */ + list(state?: SprintState): Promise + get(id: string): Promise + create(input: CreateSprintInput): Promise + update(id: string, input: UpdateSprintInput): Promise + /** 409 while another sprint is active or this one is not planned. */ + start(id: string): Promise + /** Unfinished scope moves to `moveIncompleteTo` (a planned sprint) or the backlog (null). */ + close(id: string, moveIncompleteTo: string | null): Promise + /** Planned sprints only (Admin); members return to the backlog. */ + remove(id: string): Promise + burndown(id: string, scope: ChartScope): Promise + } + velocity(scope: ChartScope & { limit?: number }): Promise people(q?: string): Promise } @@ -271,6 +343,14 @@ export function issueSearch({ filter, sort, cursor, limit }: IssueListParams = { return text ? `?${text}` : '' } +/** `?unit=&project=&limit=` with only the set parameters. */ +export function chartSearch({ unit, project, limit }: ChartScope & { limit?: number }): string { + const search = new URLSearchParams({ unit }) + if (project) search.set('project', project) + if (limit !== undefined) search.set('limit', String(limit)) + return `?${search}` +} + export function createTrackerApi(fetcher: Fetcher = (input, init) => fetch(input, init), reauth = browserReauth): TrackerApi { async function send(method: string, path: string, body?: unknown): Promise { const read = method === 'GET' @@ -359,6 +439,17 @@ export function createTrackerApi(fetcher: Fetcher = (input, init) => fetch(input update: (viewId, input) => send('PATCH', `/views/${id(viewId)}`, input), remove: (viewId) => send('DELETE', `/views/${id(viewId)}`), }, + sprints: { + list: (state) => list(`/sprints${state ? `?state=${state}` : ''}`), + get: (sprintId) => send('GET', `/sprints/${id(sprintId)}`), + create: (input) => send('POST', '/sprints', input), + update: (sprintId, input) => send('PATCH', `/sprints/${id(sprintId)}`, input), + start: (sprintId) => send('POST', `/sprints/${id(sprintId)}/start`), + close: (sprintId, moveIncompleteTo) => send('POST', `/sprints/${id(sprintId)}/close`, { moveIncompleteTo }), + remove: (sprintId) => send('DELETE', `/sprints/${id(sprintId)}`), + burndown: (sprintId, scope) => send('GET', `/sprints/${id(sprintId)}/burndown${chartSearch(scope)}`), + }, + velocity: (scope) => send('GET', `/velocity${chartSearch(scope)}`), people: (q) => send('GET', `/people${q ? `?q=${encodeURIComponent(q)}` : ''}`), } } diff --git a/web/src/copy.test.ts b/web/src/copy.test.ts index c59d332..8944e84 100644 --- a/web/src/copy.test.ts +++ b/web/src/copy.test.ts @@ -2,6 +2,7 @@ import { createDashboardTranslator } from '@appthrust/platform-dashboard-i18n' import { describe, expect, test } from 'bun:test' import { catalogs } from './copy' import { CATEGORIES, GROUP_BYS, ISSUE_TYPES, PRIORITIES, SORTS, SURFACES } from './model/issues' +import { UNITS } from './model/sprints' const placeholders = (text: string) => [...text.matchAll(/\{([A-Za-z][A-Za-z0-9_]*)\}/g)].map((match) => match[1]).sort() @@ -26,10 +27,18 @@ describe('tracker copy catalogs', () => { ...SURFACES.map((value) => `tracker.surface.${value}`), ...SORTS.map((value) => `tracker.sort.${value}`), ...GROUP_BYS.map((value) => `tracker.group.${value}`), + ...(['planned', 'active', 'closed'] as const).map((value) => `tracker.sprint.state.${value}`), + ...(['epic', 'frozen', 'closed', 'lineage'] as const).map((value) => `tracker.sprint.problem.${value}`), + ...UNITS.map((value) => `tracker.unit.${value}`), ] for (const id of expected) expect(ids.has(id), id).toBe(true) }) + test('every English source text is used by one id only (the dashboard catalogs key on it)', () => { + const sources = messages.map(([, message]) => message.defaultMessage) + expect(sources.filter((text, index) => sources.indexOf(text) !== index)).toEqual([]) + }) + test('ids are unique, so both languages build a translator', () => { expect(ids.size).toBe(messages.length) const ja = createDashboardTranslator('ja', catalogs) diff --git a/web/src/copy/index.ts b/web/src/copy/index.ts index ff5487e..2b190fe 100644 --- a/web/src/copy/index.ts +++ b/web/src/copy/index.ts @@ -9,8 +9,9 @@ import { issueMessages } from './issues' import { projectMessages } from './projects' import { reportMessages } from './report' import { settingsMessages } from './settings' +import { sprintMessages } from './sprints' -export const catalogs: readonly DashboardMessageCatalog[] = [commonMessages, issueMessages, epicMessages, projectMessages, reportMessages, settingsMessages] +export const catalogs: readonly DashboardMessageCatalog[] = [commonMessages, issueMessages, epicMessages, projectMessages, reportMessages, settingsMessages, sprintMessages] export type MessageId = | keyof typeof commonMessages @@ -19,3 +20,4 @@ export type MessageId = | keyof typeof projectMessages | keyof typeof reportMessages | keyof typeof settingsMessages + | keyof typeof sprintMessages diff --git a/web/src/copy/sprints.ts b/web/src/copy/sprints.ts new file mode 100644 index 0000000..6c60d50 --- /dev/null +++ b/web/src/copy/sprints.ts @@ -0,0 +1,157 @@ +// Sprints, estimates, burndown and velocity wording (API.md v0.1.10): the +// estimate and sprint properties, grouping and filtering by sprint, the +// sprints overview and a sprint's page, the create/close/delete dialogs, the +// charts, the palette's sprint commands and the workspace's sprint settings. +// Sizes (XS…XL) are shown as they are in both languages. +import { defineDashboardMessages } from '@appthrust/platform-dashboard-i18n' + +export const sprintMessages = defineDashboardMessages({ + 'tracker.nav.sprints': { defaultMessage: 'Sprints', translations: { ja: 'スプリント' } }, + 'tracker.nav.currentSprint': { defaultMessage: 'Current sprint', translations: { ja: '現在のスプリント' } }, + 'tracker.group.sprint': { defaultMessage: 'By sprint', translations: { ja: 'スプリント別' } }, + 'tracker.sort.estimate': { defaultMessage: 'Largest estimate', translations: { ja: '見積もりが大きい順' } }, + 'tracker.filter.sprint': { defaultMessage: 'Filter by sprint', translations: { ja: 'スプリントで絞り込む' } }, + 'tracker.palette.goSprints': { defaultMessage: 'Open sprints', translations: { ja: 'スプリント一覧を開く' } }, + 'tracker.palette.goCurrentSprint': { defaultMessage: 'Open the current sprint', translations: { ja: '現在のスプリントを開く' } }, + + 'tracker.property.estimate': { defaultMessage: 'Estimate', translations: { ja: '見積もり' } }, + 'tracker.property.sprint': { defaultMessage: 'Sprint', translations: { ja: 'スプリント' } }, + 'tracker.estimate.none': { defaultMessage: 'No estimate', translations: { ja: '見積もりなし' } }, + 'tracker.estimate.change': { defaultMessage: 'Set estimate…', translations: { ja: '見積もりを設定…' } }, + 'tracker.estimate.epic': { defaultMessage: 'Epics are not estimated; estimate their stories or work items.', translations: { ja: 'エピックには見積もりを付けません。ストーリーや課題に付けてください。' } }, + 'tracker.estimate.set': { defaultMessage: 'Estimated {count} issues as {size}', translations: { ja: '{count} 件の見積もりを {size} にしました' } }, + 'tracker.estimate.cleared': { defaultMessage: 'Removed the estimate from {count} issues', translations: { ja: '{count} 件の見積もりを外しました' } }, + + 'tracker.sprint.none': { defaultMessage: 'No sprint', translations: { ja: 'スプリントなし' } }, + 'tracker.sprint.backlog': { defaultMessage: 'Backlog (no sprint)', translations: { ja: 'バックログ(スプリントなし)' } }, + 'tracker.sprint.activeOption': { defaultMessage: 'The active sprint', translations: { ja: '進行中のスプリント' } }, + 'tracker.sprint.move': { defaultMessage: 'Move to sprint…', translations: { ja: 'スプリントに移す…' } }, + 'tracker.sprint.moved': { defaultMessage: 'Moved {count} issues to {name}', translations: { ja: '{count} 件を {name} に移しました' } }, + 'tracker.sprint.movedBacklog': { defaultMessage: 'Moved {count} issues to the backlog', translations: { ja: '{count} 件をバックログに戻しました' } }, + 'tracker.sprint.skipped': { defaultMessage: '{count} skipped: not allowed for them.', translations: { ja: '{count} 件は変更できないため飛ばしました。' } }, + 'tracker.sprint.through': { defaultMessage: 'via {identifier}', translations: { ja: '{identifier} 経由' } }, + 'tracker.sprint.nestedLabel': { defaultMessage: 'Work under {identifier}', translations: { ja: '{identifier} の配下の課題' } }, + 'tracker.sprint.state.planned': { defaultMessage: 'Planned', translations: { ja: '予定' } }, + 'tracker.sprint.state.active': { defaultMessage: 'Running', translations: { ja: '進行中' } }, + 'tracker.sprint.state.closed': { defaultMessage: 'Finished', translations: { ja: '終了' } }, + 'tracker.sprint.problem.epic': { defaultMessage: 'Epics do not join sprints.', translations: { ja: 'エピックはスプリントに入れられません。' } }, + 'tracker.sprint.problem.frozen': { defaultMessage: 'Its sprint is closed, so it stays there.', translations: { ja: '終了したスプリントの課題は移せません。' } }, + 'tracker.sprint.problem.closed': { defaultMessage: 'This sprint is closed.', translations: { ja: 'このスプリントは終了しています。' } }, + 'tracker.sprint.problem.lineage': { defaultMessage: 'Its parent or child is already in this sprint.', translations: { ja: '親か子の課題がすでにこのスプリントにあります。' } }, + + 'tracker.unit.label': { defaultMessage: 'Unit', translations: { ja: '単位' } }, + 'tracker.unit.points': { defaultMessage: 'Points', translations: { ja: 'ポイント' } }, + 'tracker.unit.issues': { defaultMessage: 'Issue count', translations: { ja: '件数' } }, + 'tracker.unit.pointsValue': { defaultMessage: '{count} pt', translations: { ja: '{count} pt' } }, + + 'tracker.sprints.new': { defaultMessage: 'New sprint', translations: { ja: '新しいスプリント' } }, + 'tracker.sprints.active': { defaultMessage: 'Active sprint', translations: { ja: '進行中のスプリント' } }, + 'tracker.sprints.planned': { defaultMessage: 'Planned sprints', translations: { ja: '予定のスプリント' } }, + 'tracker.sprints.closed': { defaultMessage: 'Closed sprints', translations: { ja: '終了したスプリント' } }, + 'tracker.sprints.noActive': { defaultMessage: 'No sprint is running.', translations: { ja: '進行中のスプリントはありません。' } }, + 'tracker.sprints.noActiveBody': { defaultMessage: 'Start a planned sprint when the team is ready.', translations: { ja: '準備ができたら、予定のスプリントを開始してください。' } }, + 'tracker.sprints.noPlanned': { defaultMessage: 'No planned sprints. Create the next one to plan ahead.', translations: { ja: '予定のスプリントはありません。次のスプリントを作成して計画できます。' } }, + 'tracker.sprints.emptyTitle': { defaultMessage: 'No sprints yet', translations: { ja: 'スプリントはまだありません' } }, + 'tracker.sprints.emptyBody': { + defaultMessage: 'Cut the work into one- or two-week sprints. Estimates and closed sprints give the team its velocity.', + translations: { ja: '作業を 1 週間または 2 週間のスプリントに区切ります。見積もりを付けてスプリントを終えるたびに、チームのベロシティがわかります。' }, + }, + 'tracker.sprints.goSprints': { defaultMessage: 'Go to sprints', translations: { ja: 'スプリント一覧へ' } }, + 'tracker.sprints.dates': { defaultMessage: '{start} – {end}', translations: { ja: '{start}〜{end}' } }, + 'tracker.sprints.oneWeek': { defaultMessage: '1 week', translations: { ja: '1 週間' } }, + 'tracker.sprints.twoWeeks': { defaultMessage: '2 weeks', translations: { ja: '2 週間' } }, + 'tracker.sprints.length': { defaultMessage: 'Length', translations: { ja: '期間' } }, + 'tracker.sprints.defaultLength': { defaultMessage: '(default)', translations: { ja: '(標準)' } }, + 'tracker.sprints.daysLeft': { defaultMessage: '{count} days left', translations: { ja: '残り {count} 日' } }, + 'tracker.sprints.startsIn': { defaultMessage: 'Starts in {count} days', translations: { ja: 'あと {count} 日で開始' } }, + 'tracker.sprints.readyToStart': { defaultMessage: 'Ready to start', translations: { ja: '開始できます' } }, + 'tracker.sprints.overdue': { defaultMessage: 'Past its end date: close it', translations: { ja: '終了日を過ぎています。スプリントを終了してください' } }, + 'tracker.sprints.closedOn': { defaultMessage: 'Closed {date}', translations: { ja: '{date} に終了' } }, + 'tracker.sprints.goal': { defaultMessage: 'Goal', translations: { ja: 'ゴール' } }, + 'tracker.sprints.goalHint': { defaultMessage: 'What the team wants to have done when the sprint ends.', translations: { ja: 'スプリントの終わりに達成したいこと。' } }, + 'tracker.sprints.noGoal': { defaultMessage: 'No goal yet', translations: { ja: 'ゴールは未設定です' } }, + 'tracker.sprints.summary': { defaultMessage: '{name} at a glance', translations: { ja: '{name} の概要' } }, + 'tracker.sprints.ofScope': { defaultMessage: '{done} / {scope}', translations: { ja: '{done} / {scope}' } }, + 'tracker.sprints.scopeValue': { defaultMessage: 'Scope {scope}', translations: { ja: 'スコープ {scope}' } }, + 'tracker.sprints.scopeOfSuggested': { defaultMessage: 'Scope {scope} / suggested {suggested}', translations: { ja: 'スコープ {scope}(目安 {suggested})' } }, + 'tracker.sprints.suggested': { defaultMessage: 'Suggested', translations: { ja: '目安' } }, + 'tracker.sprints.suggestedHint': { defaultMessage: 'Average velocity per week × sprint length in weeks', translations: { ja: '週あたりの平均ベロシティ × スプリントの週数' } }, + 'tracker.sprints.committedCompleted': { defaultMessage: 'Committed {committed} → completed {completed}', translations: { ja: 'コミット {committed} → 完了 {completed}' } }, + 'tracker.sprints.velocityLead': { + defaultMessage: 'Committed and completed per closed sprint; the dashed line is the weekly average of the last three.', + translations: { ja: '終了したスプリントごとのコミットと完了。破線は直近 3 スプリントの週平均です。' }, + }, + 'tracker.sprints.open': { defaultMessage: 'Open sprint', translations: { ja: 'スプリントを開く' } }, + 'tracker.sprints.plan': { defaultMessage: 'Plan', translations: { ja: '計画する' } }, + 'tracker.sprints.planFromBacklog': { defaultMessage: 'Plan from the backlog', translations: { ja: 'バックログから計画する' } }, + 'tracker.sprints.start': { defaultMessage: 'Start sprint', translations: { ja: 'スプリントを開始' } }, + 'tracker.sprints.started': { defaultMessage: '{name} started', translations: { ja: '{name} を開始しました' } }, + 'tracker.sprints.startBlocked': { defaultMessage: 'Close {name} before starting another sprint.', translations: { ja: '別のスプリントを開始する前に {name} を終了してください。' } }, + 'tracker.sprints.close': { defaultMessage: 'Close sprint', translations: { ja: 'スプリントを終了' } }, + 'tracker.sprints.menu': { defaultMessage: 'Sprint actions', translations: { ja: 'スプリントの操作' } }, + 'tracker.sprints.edit': { defaultMessage: 'Edit sprint', translations: { ja: 'スプリントを編集' } }, + 'tracker.sprints.editTitle': { defaultMessage: 'Edit {name}', translations: { ja: '{name} を編集' } }, + 'tracker.sprints.emptySprintTitle': { defaultMessage: 'No issues in this sprint yet', translations: { ja: 'このスプリントにはまだ課題がありません' } }, + 'tracker.sprints.emptySprintBody': { defaultMessage: 'Move issues in from the backlog, or create one here.', translations: { ja: 'バックログから課題を移すか、ここで作成してください。' } }, + + 'tracker.sprints.createLead': { defaultMessage: 'A timebox of one or two weeks.', translations: { ja: '1 週間または 2 週間の期間で作業を区切ります。' } }, + 'tracker.sprints.namePlaceholder': { defaultMessage: 'Optional', translations: { ja: '省略可' } }, + 'tracker.sprints.nameHint': { defaultMessage: 'Leave it empty to name the sprint “Sprint” and its number.', translations: { ja: '空欄なら「Sprint 番号」という名前になります。' } }, + 'tracker.sprints.startsOn': { defaultMessage: 'Starts on', translations: { ja: '開始日' } }, + 'tracker.sprints.endsOn': { defaultMessage: 'Runs {start} – {end}. Empty: the day after the last sprint, or next Monday.', translations: { ja: '期間は {start}〜{end}。空欄なら前のスプリントの翌日、なければ次の月曜日から始まります。' } }, + 'tracker.sprints.datesLocked': { defaultMessage: 'Dates are fixed once a sprint has started.', translations: { ja: '開始したスプリントの期間は変更できません。' } }, + 'tracker.sprints.createSubmit': { defaultMessage: 'Create sprint', translations: { ja: '作成' } }, + 'tracker.sprints.created': { defaultMessage: 'Created {name}', translations: { ja: '{name} を作成しました' } }, + + 'tracker.sprints.closeTitle': { defaultMessage: 'Close {name}?', translations: { ja: '{name} を終了しますか?' } }, + 'tracker.sprints.closeUnfinishedLabel': { defaultMessage: 'Unfinished', translations: { ja: '未完了' } }, + 'tracker.sprints.closeVelocity': { defaultMessage: 'Velocity {value}', translations: { ja: 'ベロシティ {value}' } }, + 'tracker.sprints.closeMoveTo': { defaultMessage: 'Move unfinished issues to', translations: { ja: '未完了の課題の移動先' } }, + 'tracker.sprints.closeMoveHint': { defaultMessage: 'An issue whose parent or child is already there goes to the backlog.', translations: { ja: '移動先にすでに親か子の課題がある場合は、バックログに戻ります。' } }, + 'tracker.sprints.closeAllDone': { defaultMessage: 'Every issue in this sprint is done.', translations: { ja: 'このスプリントの課題はすべて完了しています。' } }, + 'tracker.sprints.closeCanceledStay': { defaultMessage: 'Done and canceled issues stay in this sprint. A closed sprint cannot be reopened.', translations: { ja: '完了と中止の課題はこのスプリントに残ります。終了したスプリントは再開できません。' } }, + 'tracker.sprints.closeSubmit': { defaultMessage: 'Close the sprint', translations: { ja: '終了する' } }, + 'tracker.sprints.closedToast': { defaultMessage: '{name} closed', translations: { ja: '{name} を終了しました' } }, + 'tracker.sprints.movedTo': { defaultMessage: '{count} unfinished issues moved to {name}.', translations: { ja: '未完了の {count} 件を {name} に移しました。' } }, + 'tracker.sprints.movedToBacklog': { defaultMessage: '{count} unfinished issues went back to the backlog.', translations: { ja: '未完了の {count} 件をバックログに戻しました。' } }, + 'tracker.sprints.delete': { defaultMessage: 'Delete sprint', translations: { ja: 'スプリントを削除' } }, + 'tracker.sprints.deleteTitle': { defaultMessage: 'Delete {name}?', translations: { ja: '{name} を削除しますか?' } }, + 'tracker.sprints.deleteBody': { defaultMessage: 'Its issues go back to the backlog.', translations: { ja: '含まれていた課題はバックログに戻ります。' } }, + + 'tracker.chart.burndown': { defaultMessage: 'Burndown', translations: { ja: 'バーンダウン' } }, + 'tracker.chart.burndownOf': { defaultMessage: 'Burndown of {name}', translations: { ja: '{name} のバーンダウン' } }, + 'tracker.chart.velocity': { defaultMessage: 'Velocity', translations: { ja: 'ベロシティ' } }, + 'tracker.chart.remaining': { defaultMessage: 'Remaining', translations: { ja: '残り' } }, + 'tracker.chart.ideal': { defaultMessage: 'Ideal', translations: { ja: '理想' } }, + 'tracker.chart.scope': { defaultMessage: 'Scope', translations: { ja: 'スコープ' } }, + 'tracker.chart.today': { defaultMessage: 'Today', translations: { ja: '今日' } }, + 'tracker.chart.committed': { defaultMessage: 'Committed', translations: { ja: 'コミット' } }, + 'tracker.chart.completed': { defaultMessage: 'Done', translations: { ja: '完了' } }, + 'tracker.chart.average': { defaultMessage: 'Weekly average', translations: { ja: '週平均' } }, + 'tracker.chart.averageValue': { defaultMessage: 'Average {value} / week', translations: { ja: '週平均 {value}' } }, + 'tracker.chart.day': { defaultMessage: 'Day', translations: { ja: '日付' } }, + 'tracker.chart.showValues': { defaultMessage: 'Show the values ({unit})', translations: { ja: '数値を表で見る({unit})' } }, + 'tracker.chart.burndownSummary': { defaultMessage: 'On {day}: {remaining} remaining of {scope}; ideal {ideal}.', translations: { ja: '{day} 時点で残り {remaining}(スコープ {scope})。理想は {ideal}。' } }, + 'tracker.chart.velocitySummary': { + defaultMessage: '{count} closed sprints; latest completed {latest}; {average} per week on average.', + translations: { ja: '終了したスプリント {count} 件。直近の完了は {latest}、週平均は {average}。' }, + }, + 'tracker.chart.noClosed': { defaultMessage: 'Velocity appears once the first sprint is closed.', translations: { ja: '最初のスプリントを終了すると、ベロシティが表示されます。' } }, + 'tracker.chart.notStarted': { defaultMessage: 'The burndown starts when the sprint starts.', translations: { ja: 'スプリントを開始すると、バーンダウンが表示されます。' } }, + 'tracker.chart.noPoints': { + defaultMessage: 'No issue in this sprint has an estimate, so there are no points to show. Add estimates, or count issues instead.', + translations: { ja: 'このスプリントの課題には見積もりがないため、ポイントでは表示できません。見積もりを付けるか、件数で表示してください。' }, + }, + 'tracker.chart.switchToIssues': { defaultMessage: 'Count issues', translations: { ja: '件数で表示' } }, + + 'tracker.activity.estimate': { defaultMessage: '{actor} estimated it {to}', translations: { ja: '{actor} が見積もりを {to} に設定' } }, + 'tracker.activity.estimateCleared': { defaultMessage: '{actor} removed the estimate', translations: { ja: '{actor} が見積もりを外した' } }, + 'tracker.activity.sprint': { defaultMessage: '{actor} moved it to {to}', translations: { ja: '{actor} が {to} に移動' } }, + 'tracker.activity.sprintCleared': { defaultMessage: '{actor} moved it to the backlog', translations: { ja: '{actor} がバックログに戻した' } }, + + 'tracker.settings.sprintLength': { defaultMessage: 'Default sprint length', translations: { ja: 'スプリントの標準の期間' } }, + 'tracker.settings.sprintLengthHint': { defaultMessage: 'New sprints start with this length; each sprint can still choose.', translations: { ja: '新しいスプリントはこの期間で作成されます。スプリントごとに変えることもできます。' } }, + 'tracker.settings.timezone': { defaultMessage: 'Time zone', translations: { ja: 'タイムゾーン' } }, + 'tracker.settings.timezoneHint': { defaultMessage: 'Sprint dates and the days of the charts follow this time zone.', translations: { ja: 'スプリントの日付とグラフの日の区切りは、このタイムゾーンに従います。' } }, + 'tracker.settings.timezoneInvalid': { defaultMessage: 'Enter an IANA time zone, like Asia/Tokyo.', translations: { ja: 'Asia/Tokyo のような IANA のタイムゾーン名を入力してください。' } }, +}) diff --git a/web/src/dev/mock-tracker.test.ts b/web/src/dev/mock-tracker.test.ts index d66419b..6fb89d6 100644 --- a/web/src/dev/mock-tracker.test.ts +++ b/web/src/dev/mock-tracker.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, test } from 'bun:test' -import type { Attachment, Issue, IssuePage, IssueSummary, Label, Project, Status, TimelineItem, View } from '../api/tracker' +import type { Attachment, Burndown, Issue, IssuePage, IssueSummary, Label, Project, Sprint, Status, TimelineItem, Velocity, View } from '../api/tracker' +import { addDays, dayInZone } from '../model/sprints' import { MOCK_PEOPLE, trackerRoutes } from './mock-tracker' const BASE = '/api/tracker/v1' @@ -35,7 +36,7 @@ beforeEach(async () => { describe('tracker mock: fixture shared with the server dev seed', () => { test('caller, workspace, statuses, labels, views and people', async () => { expect((await call('GET', '/me')).body).toEqual({ ...MOCK_PEOPLE.alex, role: 'Admin', isAdmin: true }) - expect((await call('GET', '/workspace')).body).toMatchObject({ key: 'APT', issueCount: 36 }) + expect((await call('GET', '/workspace')).body).toMatchObject({ key: 'APT', issueCount: 40, sprintLengthWeeks: 1, timezone: 'Asia/Tokyo' }) expect((await statuses()).map((status) => [status.name, status.category, status.color, status.position])).toEqual([ ['Backlog', 'backlog', 'gray', 0], ['Todo', 'unstarted', 'gray', 1], @@ -99,9 +100,9 @@ describe('tracker mock: issues', () => { seen.push(...page.items.map((issue) => issue.identifier)) cursor = page.nextCursor } while (cursor) - expect(seen).toHaveLength(36) + expect(seen).toHaveLength(40) expect(seen[0]).toBe('APT-1') - expect(new Set(seen).size).toBe(36) + expect(new Set(seen).size).toBe(40) const urgentFirst = (await list('?sort=priority')).items expect(urgentFirst.slice(0, 6).every((issue) => issue.priority === 'urgent')).toBe(true) for (const bad of ['?filter=%7Bnope', filterQuery({ colour: ['red'] }), filterQuery({ type: ['initiative'] }), filterQuery({ epic: ['APT-31'] }), filterQuery({ story: 'none' }), '?sort=title', '?limit=500']) { @@ -158,9 +159,9 @@ describe('tracker mock: issues', () => { expect((await call('POST', '/issues', { title: 'x', type: 'task', report: { environment: 'local', surface: 'apth' } })).status).toBe(400) const created = await call('POST', '/issues', { title: ' Board drag fails ', type: 'bug', priority: 'high', report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0', steps: '' } }) expect(created.status).toBe(201) - expect(created.body).toMatchObject({ identifier: 'APT-37', title: 'Board drag fails', statusId: (await statusNamed('Backlog')).id, reporter: MOCK_PEOPLE.alex, report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0' } }) + expect(created.body).toMatchObject({ identifier: 'APT-41', title: 'Board drag fails', statusId: (await statusNamed('Backlog')).id, reporter: MOCK_PEOPLE.alex, report: { environment: 'craftsman', surface: 'dashboard', version: '0.1.0' }, estimate: null, sprint: null }) expect(created.body.report.steps).toBeUndefined() - expect((await call('GET', '/workspace')).body.issueCount).toBe(37) + expect((await call('GET', '/workspace')).body.issueCount).toBe(41) }) test('PATCH: one activity per changed field, completion time, links and cycle checks', async () => { @@ -179,6 +180,9 @@ describe('tracker mock: issues', () => { expect((await call('PATCH', `/issues/${issue.id}`, { assigneeSub: null })).body.assignee).toBeNull() const parent = (await call('GET', '/issues/APT-1')).body as Issue + // APT-2 is in the active sprint with APT-1's story (APT-34): lineage-exclusive until it leaves the sprint. + expect((await call('PATCH', `/issues/${issue.id}`, { parentId: parent.id })).body.issues[0].path).toBe('sprintId') + await call('PATCH', `/issues/${issue.id}`, { sprintId: null }) expect((await call('PATCH', `/issues/${issue.id}`, { parentId: parent.id })).body.parent.identifier).toBe('APT-1') expect((await call('GET', '/issues/APT-1')).body.children.map((child: { identifier: string }) => child.identifier)).toEqual(['APT-2']) expect((await call('PATCH', `/issues/${parent.id}`, { parentId: issue.id })).body.issues[0]).toEqual({ path: 'parentId', message: 'parent would create a cycle' }) @@ -206,7 +210,7 @@ describe('tracker mock: issues', () => { await as('dev-alex', 'Admin') expect((await call('DELETE', `/issues/${issue.id}`)).status).toBe(204) expect((await call('GET', '/issues/APT-4')).status).toBe(404) - expect((await list()).items).toHaveLength(35) + expect((await list()).items).toHaveLength(39) }) }) @@ -238,18 +242,22 @@ describe('tracker mock: epics and stories', () => { } }) - test('progress counts level-0 descendants at any depth: canceled excluded from total, completed counted', async () => { + test('progress counts level-0 descendants at any depth: canceled excluded from total, completed counted; points sum their sizes', async () => { const issues = await byNumber() const category = new Map((await statuses()).map((status) => [status.id, status.category])) + const weight = (issue: IssueSummary) => (issue.estimate ? { XS: 1, S: 2, M: 3, L: 5, XL: 8 }[issue.estimate] : 0) const expected = (inGroup: (issue: IssueSummary) => boolean) => { const counted = [...issues.values()].filter((issue) => issue.number <= 30 && inGroup(issue) && category.get(issue.statusId) !== 'canceled') - return { total: counted.length, completed: counted.filter((issue) => category.get(issue.statusId) === 'completed').length } + const completed = counted.filter((issue) => category.get(issue.statusId) === 'completed') + const points = (items: IssueSummary[]) => items.reduce((sum, issue) => sum + weight(issue), 0) + return { total: counted.length, completed: completed.length, points: { total: points(counted), completed: points(completed) } } } const epic = issues.get(31)! const story = issues.get(33)! expect(story.progress).toEqual(expected((issue) => issue.story?.id === story.id)) expect(epic.progress).toEqual(expected((issue) => issue.epic?.id === epic.id)) expect(epic.progress!.total).toBeGreaterThan(story.progress!.total) + expect(epic.progress!.points.total).toBeGreaterThan(0) // A completed sub-task two levels below its story counts there and in the epic. const parentTask = issues.get(1)! @@ -257,7 +265,7 @@ describe('tracker mock: epics and stories', () => { expect(subTask).toMatchObject({ epic: { id: parentTask.epic!.id }, story: { id: parentTask.story!.id }, progress: null }) for (const group of [parentTask.story!, parentTask.epic!]) { const before = [...issues.values()].find((issue) => issue.id === group.id)!.progress! - expect(((await call('GET', `/issues/${group.id}`)).body as Issue).progress).toEqual({ total: before.total + 1, completed: before.completed + 1 }) + expect(((await call('GET', `/issues/${group.id}`)).body as Issue).progress).toEqual({ ...before, total: before.total + 1, completed: before.completed + 1 }) } }) @@ -281,7 +289,7 @@ describe('tracker mock: epics and stories', () => { expect(inEpic.map((issue) => issue.number)).toContain(33) expect((await list(`${filterQuery({ story: [story.id] })}&limit=200`)).items.every((issue) => issue.story?.id === story.id)).toBe(true) const noEpic = (await list(`${filterQuery({ epic: ['none'] })}&limit=200`)).items - expect(noEpic.map((issue) => issue.number).sort((a, b) => a - b)).toEqual([5, 10, 15, 20, 25, 30, 31, 32]) + expect(noEpic.map((issue) => issue.number).sort((a, b) => a - b)).toEqual([5, 10, 15, 20, 25, 30, 31, 32, 37, 38, 39, 40]) expect((await list(`${filterQuery({ epic: [epic.id, 'none'] })}&limit=200`)).items).toHaveLength(inEpic.length + noEpic.length) expect((await list(filterQuery({ type: ['epic', 'story'] }))).items).toHaveLength(6) expect((await list(filterQuery({ parent: epic.id }))).items.map((issue) => issue.number).sort()).toEqual([33, 34]) @@ -412,9 +420,9 @@ describe('tracker mock: projects', () => { test('filter: project ids OR `none`', async () => { const dashboard = await projectNamed('Dashboard') - expect((await list(filterQuery({ project: ['none'] }))).items).toHaveLength(16) + expect((await list(filterQuery({ project: ['none'] }))).items).toHaveLength(20) expect((await list(filterQuery({ project: [dashboard.id] }))).items.every((issue) => issue.projectId === dashboard.id)).toBe(true) - expect((await list(filterQuery({ project: [dashboard.id, 'none'] }))).items).toHaveLength(21) + expect((await list(filterQuery({ project: [dashboard.id, 'none'] }))).items).toHaveLength(25) expect((await call('GET', `/issues${filterQuery({ project: 'none' })}`)).status).toBe(400) }) @@ -545,3 +553,309 @@ describe('tracker mock: views and settings authorization', () => { expect(body.openapi).toMatch(/^3\.1/) }) }) + +describe('tracker mock: sprints fixture (API.md v0.1.10)', () => { + const today = () => dayInZone(Date.now(), 'Asia/Tokyo') + const sprints = async (query = '') => (await call('GET', `/sprints${query}`)).body.items as Sprint[] + const byNumber = async () => new Map((await sprints()).map((sprint) => [sprint.number, sprint])) + const issueNumbered = async (n: number) => (await call('GET', `/issues/APT-${n}`)).body as Issue + const members = async (sprintId: string) => (await list(`${filterQuery({ sprint: [sprintId] })}&sort=number&limit=200`)).items.map((issue) => issue.number) + + test('three closed one-week sprints, an active two-week sprint on its fourth day, a planned one; API order', async () => { + const items = await sprints() + expect(items.map((sprint) => [sprint.number, sprint.state, sprint.lengthWeeks])).toEqual([ + [4, 'active', 2], + [5, 'planned', 1], + [3, 'closed', 1], + [2, 'closed', 1], + [1, 'closed', 1], + ]) + const sprint = await byNumber() + expect(sprint.get(4)).toMatchObject({ name: 'Sprint 4', goal: 'Sprint planning and burndown', startsOn: addDays(today(), -3), endsOn: addDays(today(), 10), closedAt: null }) + expect(sprint.get(5)).toMatchObject({ startsOn: addDays(today(), 11), endsOn: addDays(today(), 17), startedAt: null, commitment: null, current: { scopePoints: 4, scopeIssues: 3, donePoints: 0, doneIssues: 0 } }) + expect(sprint.get(1)).toMatchObject({ startsOn: addDays(today(), -24), endsOn: addDays(today(), -18) }) + expect([1, 2, 3, 4].map((n) => [sprint.get(n)!.commitment, sprint.get(n)!.current])).toEqual([ + [ + { scopePoints: 21, scopeIssues: 4, donePoints: 0, doneIssues: 0 }, + { scopePoints: 21, scopeIssues: 4, donePoints: 18, doneIssues: 3 }, + ], + [ + { scopePoints: 24, scopeIssues: 4, donePoints: 0, doneIssues: 0 }, + { scopePoints: 24, scopeIssues: 4, donePoints: 21, doneIssues: 3 }, + ], + [ + { scopePoints: 27, scopeIssues: 4, donePoints: 0, doneIssues: 0 }, + { scopePoints: 27, scopeIssues: 4, donePoints: 24, doneIssues: 3 }, + ], + [ + { scopePoints: 10, scopeIssues: 6, donePoints: 0, doneIssues: 0 }, + { scopePoints: 10, scopeIssues: 6, donePoints: 0, doneIssues: 0 }, + ], + ]) + expect(await members(sprint.get(1)!.id)).toEqual([5, 11, 17]) + expect(await members(sprint.get(2)!.id)).toEqual([23, 29, 37]) + expect(await members(sprint.get(3)!.id)).toEqual([38, 39, 40]) + expect(await members(sprint.get(4)!.id)).toEqual([2, 3, 4, 10, 15, 30, 34]) + expect(await members(sprint.get(5)!.id)).toEqual([8, 14, 26]) + expect((await issueNumbered(5)).sprint).toEqual({ id: sprint.get(1)!.id, number: 1, name: 'Sprint 1', state: 'closed' }) + }) + + test('four Done work items close the seed, and 17 work items carry a size across all five', async () => { + const all = (await list('?sort=number&limit=200')).items + const done = await statusNamed('Done') + expect(all.slice(36).map((issue) => [issue.number, issue.title, issue.type, issue.statusId === done.id, issue.parent, issue.projectId, issue.estimate])).toEqual([ + [37, 'Speed up issue search', 'task', true, null, null, 'L'], + [38, 'Add bulk status change', 'feature', true, null, null, 'XL'], + [39, 'Tidy up the settings layout', 'task', true, null, null, 'XL'], + [40, 'Show issue counts per project', 'feature', true, null, null, 'XL'], + ]) + const sized = all.filter((issue) => issue.estimate !== null) + expect(sized.map((issue) => `${issue.number}:${issue.estimate}`)).toEqual(['2:M', '3:S', '4:M', '5:XL', '8:XS', '10:S', '11:L', '14:M', '16:XS', '17:L', '23:XL', '29:XL', '30:S', '37:L', '38:XL', '39:XL', '40:XL']) + expect(all.filter((issue) => issue.type === 'epic').every((issue) => issue.estimate === null && issue.sprint === null)).toBe(true) + }) + + test('velocity: 18, 21, 24 points (committed 21, 24, 27), 21 per week; 3 issues each in the issue unit', async () => { + const points = (await call('GET', '/velocity')).body as Velocity + expect(points.unit).toBe('points') + expect(points.items.map((item) => [item.sprint.number, item.lengthWeeks, item.committed, item.completed])).toEqual([ + [1, 1, 21, 18], + [2, 1, 24, 21], + [3, 1, 27, 24], + ]) + expect(points.averagePerWeek).toBe(21) + const issues = (await call('GET', '/velocity?unit=issues')).body as Velocity + expect(issues.items.map((item) => [item.committed, item.completed])).toEqual([ + [4, 3], + [4, 3], + [4, 3], + ]) + expect(issues.averagePerWeek).toBe(3) + expect(((await call('GET', '/velocity?limit=2')).body as Velocity).items.map((item) => item.sprint.number)).toEqual([2, 3]) + for (const bad of ['?limit=0', '?limit=27', '?unit=hours']) expect((await call('GET', `/velocity${bad}`)).status, bad).toBe(400) + }) + + test('burndown of the active sprint: commitment on day one, the scope increase on day two, the cancellation on day three, nothing after today', async () => { + const active = (await byNumber()).get(4)! + const burndown = (await call('GET', `/sprints/${active.id}/burndown?unit=points`)).body as Burndown + expect(burndown).toMatchObject({ sprint: { id: active.id, state: 'active' }, unit: 'points', today: today() }) + expect(burndown.points).toHaveLength(14) + expect(burndown.points.slice(0, 4).map((point) => [point.day, point.scope, point.done, point.remaining])).toEqual([ + [addDays(today(), -3), 10, 0, 10], + [addDays(today(), -2), 12, 0, 12], + [addDays(today(), -1), 10, 0, 10], + [today(), 10, 0, 10], + ]) + expect(burndown.points[0]!.ideal).toBe(10) + expect(burndown.points[13]!.ideal).toBe(0) + expect(burndown.points.slice(4).every((point) => point.remaining === undefined && point.scope === undefined && typeof point.ideal === 'number')).toBe(true) + const issues = (await call('GET', `/sprints/${active.id}/burndown?unit=issues`)).body as Burndown + expect(issues.points.slice(0, 4).map((point) => point.scope)).toEqual([6, 7, 6, 6]) + // A closed sprint's last day carries its final tally. + const first = (await byNumber()).get(1)! + const closed = (await call('GET', `/sprints/${first.id}/burndown`)).body as Burndown + expect(closed.points[6]).toMatchObject({ scope: 21, done: 18, remaining: 3 }) + expect((await call('GET', `/sprints/${active.id}/burndown?unit=hours`)).status).toBe(400) + expect((await call('GET', '/sprints/nope/burndown')).status).toBe(404) + // `project` restricts to issues currently in that project. + const none = (await call('GET', `/sprints/${active.id}/burndown?project=none`)).body as Burndown + // APT-3 (S), APT-15, APT-30 (canceled on day three) and APT-34 have no project. + expect(none.points[3]).toMatchObject({ scope: 2, remaining: 2 }) + }) +}) + +describe('tracker mock: estimates and membership on issue writes', () => { + const sprintsByNumber = async () => new Map(((await call('GET', '/sprints')).body.items as Sprint[]).map((sprint) => [sprint.number, sprint])) + const issueNumbered = async (n: number) => (await call('GET', `/issues/APT-${n}`)).body as Issue + const refused = async (method: string, path: string, body: object, field: string) => { + const response = await call(method, path, body) + expect(response.status, JSON.stringify(body)).toBe(400) + expect(response.body).toMatchObject({ error: 'invalid', issues: [{ path: field }] }) + } + + test('estimating, completing, moving and deleting write the ledger; the burndown moves', async () => { + const sprint = await sprintsByNumber() + const active = sprint.get(4)! + const planned = sprint.get(5)! + const fifteen = await issueNumbered(15) + expect((await call('PATCH', `/issues/${fifteen.id}`, { estimate: 'L' })).body).toMatchObject({ estimate: 'L' }) + expect((await call('GET', `/sprints/${active.id}`)).body.current).toEqual({ scopePoints: 15, scopeIssues: 6, donePoints: 0, doneIssues: 0 }) + const done = await statusNamed('Done') + await call('PATCH', `/issues/${fifteen.id}`, { statusId: done.id }) + expect((await call('GET', `/sprints/${active.id}`)).body.current).toEqual({ scopePoints: 15, scopeIssues: 6, donePoints: 5, doneIssues: 1 }) + const burndown = (await call('GET', `/sprints/${active.id}/burndown`)).body as Burndown + expect(burndown.points[3]).toMatchObject({ scope: 15, done: 5, remaining: 10 }) + // Commitment stays the ledger at the start. + expect((await call('GET', `/sprints/${active.id}`)).body.commitment).toEqual({ scopePoints: 10, scopeIssues: 6, donePoints: 0, doneIssues: 0 }) + + const two = await issueNumbered(2) + expect((await call('PATCH', `/issues/${two.id}`, { sprintId: planned.id })).body.sprint).toEqual({ id: planned.id, number: 5, name: 'Sprint 5', state: 'planned' }) + expect((await call('GET', `/sprints/${active.id}`)).body.current.scopePoints).toBe(12) + expect((await call('GET', `/sprints/${planned.id}`)).body.current).toMatchObject({ scopePoints: 7, scopeIssues: 4 }) + await call('PATCH', `/issues/${two.id}`, { sprintId: null }) + expect((await call('GET', `/sprints/${planned.id}`)).body.current.scopePoints).toBe(4) + const timeline = (await call('GET', `/issues/${two.id}/timeline`)).body.items as TimelineItem[] + expect(timeline.flatMap((item) => (item.kind === 'activity' && item.activity.field === 'sprint' ? [[(item.activity.from as { number?: number } | null)?.number ?? null, (item.activity.to as { number?: number } | null)?.number ?? null]] : []))).toEqual([ + [4, 5], + [5, null], + ]) + const fifteenTimeline = (await call('GET', `/issues/${fifteen.id}/timeline`)).body.items as TimelineItem[] + expect(fifteenTimeline.find((item) => item.kind === 'activity' && item.activity.field === 'estimate')).toMatchObject({ activity: { from: null, to: 'L' } }) + + const three = await issueNumbered(3) + await call('DELETE', `/issues/${three.id}`) + expect((await call('GET', `/sprints/${active.id}`)).body.current).toEqual({ scopePoints: 10, scopeIssues: 4, donePoints: 5, doneIssues: 1 }) + // A new issue may join with its size. + const created = (await call('POST', '/issues', { title: 'Planned work', type: 'task', estimate: 'M', sprintId: planned.id })).body as Issue + expect(created).toMatchObject({ estimate: 'M', sprint: { id: planned.id } }) + expect((await call('GET', `/sprints/${planned.id}`)).body.current.scopePoints).toBe(7) + // Edits of a closed sprint's member write nothing to it. + const five = await issueNumbered(5) + await call('PATCH', `/issues/${five.id}`, { estimate: 'XS' }) + expect((await call('GET', `/sprints/${sprint.get(1)!.id}`)).body.current.donePoints).toBe(18) + }) + + test('refusals: sizes, epics, unknown or closed sprints, frozen members, lineage, re-checks on type and parent changes', async () => { + const sprint = await sprintsByNumber() + const active = sprint.get(4)! + const closed = sprint.get(1)! + const [epic, nine, ten, fifteen, five, story34] = await Promise.all([31, 9, 10, 15, 5, 34].map(issueNumbered)) + await refused('PATCH', `/issues/${nine.id}`, { estimate: 'XXL' }, 'estimate') + await refused('PATCH', `/issues/${epic!.id}`, { estimate: 'S' }, 'estimate') + await refused('PATCH', `/issues/${epic!.id}`, { sprintId: active.id }, 'sprintId') + await refused('PATCH', `/issues/${nine.id}`, { sprintId: 'nope' }, 'sprintId') + await refused('PATCH', `/issues/${nine.id}`, { sprintId: closed.id }, 'sprintId') + await refused('POST', '/issues', { title: 'x', type: 'task', sprintId: closed.id }, 'sprintId') + await refused('POST', '/issues', { title: 'x', type: 'epic', estimate: 'M' }, 'estimate') + // APT-9 sits under APT-34, which is in the active sprint. + expect(nine.parent?.id).toBe(story34!.id) + await refused('PATCH', `/issues/${nine.id}`, { sprintId: active.id }, 'sprintId') + await refused('POST', '/issues', { title: 'x', type: 'task', parentId: story34!.id, sprintId: active.id }, 'sprintId') + // A closed sprint's member is frozen, even to the backlog. + await refused('PATCH', `/issues/${five.id}`, { sprintId: active.id }, 'sprintId') + await refused('PATCH', `/issues/${five.id}`, { sprintId: null }, 'sprintId') + // Type and parent changes re-check membership. + await refused('PATCH', `/issues/${fifteen.id}`, { type: 'epic' }, 'sprintId') + await refused('PATCH', `/issues/${ten.id}`, { parentId: story34!.id }, 'sprintId') + await refused('PATCH', `/issues/${ten.id}`, { type: 'epic' }, 'estimate') + expect((await call('PATCH', `/issues/${ten.id}`, { type: 'epic', estimate: null, sprintId: null })).body).toMatchObject({ type: 'epic', estimate: null, sprint: null }) + }) + + test('filter by sprint (ids, active, none) and sort by estimate', async () => { + const sprint = await sprintsByNumber() + const active = (await list(`${filterQuery({ sprint: ['active'] })}&sort=number`)).items.map((issue) => issue.number) + expect(active).toEqual([2, 3, 4, 10, 15, 30, 34]) + const both = (await list(`${filterQuery({ sprint: [sprint.get(5)!.id, 'active'] })}&limit=200`)).items + expect(both).toHaveLength(10) + const backlog = (await list(`${filterQuery({ sprint: ['none'] })}&limit=200`)).items + expect(backlog.every((issue) => issue.sprint === null)).toBe(true) + expect(backlog).toHaveLength(40 - 3 * 3 - 7 - 3) + expect((await call('GET', `/issues${filterQuery({ sprint: ['Sprint 4'] })}`)).status).toBe(400) + const bySize = (await list('?sort=estimate&limit=200')).items + expect(bySize.slice(0, 6).every((issue) => issue.estimate === 'XL')).toBe(true) + expect(bySize.at(-1)!.estimate).toBeNull() + expect((await call('POST', '/views', { name: 'By sprint', groupBy: 'sprint', sort: 'estimate', filter: { sprint: ['active'] } })).body).toMatchObject({ groupBy: 'sprint', sort: 'estimate' }) + }) +}) + +describe('tracker mock: sprint lifecycle', () => { + const sprintsByNumber = async () => new Map(((await call('GET', '/sprints')).body.items as Sprint[]).map((sprint) => [sprint.number, sprint])) + const today = () => dayInZone(Date.now(), 'Asia/Tokyo') + + test('create: defaults (workspace length, after the last open sprint, "Sprint "), validation and overlap', async () => { + const created = await call('POST', '/sprints', {}) + expect(created.status).toBe(201) + expect(created.body).toMatchObject({ number: 6, name: 'Sprint 6', goal: '', state: 'planned', lengthWeeks: 1, startsOn: addDays(today(), 18), endsOn: addDays(today(), 24), current: { scopePoints: 0 }, commitment: null }) + expect((await call('POST', '/sprints', { name: ' Hardening ', goal: 'Fix what we broke', lengthWeeks: 2 })).body).toMatchObject({ number: 7, name: 'Hardening', lengthWeeks: 2, startsOn: addDays(today(), 25), endsOn: addDays(today(), 38) }) + expect((await call('POST', '/sprints', { startsOn: addDays(today(), 20) })).status).toBe(409) + for (const bad of [{ lengthWeeks: 3 }, { name: 'x'.repeat(61) }, { name: ' ' }, { startsOn: '2026-13-01' }, { goal: 'x'.repeat(4097) }, { colour: 'red' }]) { + expect((await call('POST', '/sprints', bad)).status, JSON.stringify(bad).slice(0, 40)).toBe(400) + } + expect((await call('GET', '/sprints?state=planned')).body.items.map((sprint: Sprint) => sprint.number)).toEqual([5, 6, 7]) + expect((await call('GET', '/sprints?state=paused')).status).toBe(400) + expect((await call('GET', '/sprints/nope')).status).toBe(404) + }) + + test('patch: names and goals any time; dates only while planned and without overlap', async () => { + const sprint = await sprintsByNumber() + const active = sprint.get(4)! + const planned = sprint.get(5)! + expect((await call('PATCH', `/sprints/${active.id}`, { name: 'Sprint 4: planning', goal: 'Ship it' })).body).toMatchObject({ name: 'Sprint 4: planning', goal: 'Ship it' }) + expect((await call('PATCH', `/sprints/${active.id}`, { lengthWeeks: 1 })).status).toBe(409) + expect((await call('PATCH', `/sprints/${planned.id}`, { lengthWeeks: 2 })).body).toMatchObject({ lengthWeeks: 2, endsOn: addDays(today(), 24) }) + expect((await call('PATCH', `/sprints/${planned.id}`, { startsOn: addDays(today(), 5) })).status).toBe(409) + }) + + test('start: 409 while another sprint is active or when not planned', async () => { + const sprint = await sprintsByNumber() + expect((await call('POST', `/sprints/${sprint.get(5)!.id}/start`)).status).toBe(409) + expect((await call('POST', `/sprints/${sprint.get(4)!.id}/start`)).status).toBe(409) + expect((await call('POST', `/sprints/${sprint.get(1)!.id}/start`)).status).toBe(409) + }) + + test('close: counts stay on the closed sprint, unfinished scope moves to the target, velocity gains a bar; then the next sprint starts today', async () => { + const sprint = await sprintsByNumber() + const active = sprint.get(4)! + const planned = sprint.get(5)! + expect((await call('POST', `/sprints/${planned.id}/close`, { moveIncompleteTo: null })).status).toBe(409) + expect((await call('POST', `/sprints/${active.id}/close`, {})).status).toBe(400) + expect((await call('POST', `/sprints/${active.id}/close`, { moveIncompleteTo: sprint.get(1)!.id })).body.issues[0].path).toBe('moveIncompleteTo') + // Complete one issue first: it stays in the closing sprint and counts as velocity. + const four = (await call('GET', '/issues/APT-4')).body as Issue + await call('PATCH', `/issues/${four.id}`, { statusId: (await statusNamed('Done')).id }) + const closed = await call('POST', `/sprints/${active.id}/close`, { moveIncompleteTo: planned.id }) + expect(closed.status).toBe(200) + expect(closed.body).toMatchObject({ state: 'closed', closedAt: expect.any(String), current: { scopePoints: 10, scopeIssues: 6, donePoints: 3, doneIssues: 1 } }) + const membersOf = async (id: string) => (await list(`${filterQuery({ sprint: [id] })}&sort=number&limit=200`)).items.map((issue) => issue.number) + expect(await membersOf(active.id)).toEqual([4, 30]) + expect(await membersOf(planned.id)).toEqual([2, 3, 8, 10, 14, 15, 26, 34]) + expect((await call('GET', `/sprints/${planned.id}`)).body.current).toEqual({ scopePoints: 4 + 3 + 2 + 2, scopeIssues: 8, donePoints: 0, doneIssues: 0 }) + const velocity = (await call('GET', '/velocity')).body as Velocity + expect(velocity.items.map((item) => [item.sprint.number, item.committed, item.completed])).toEqual([ + [1, 21, 18], + [2, 24, 21], + [3, 27, 24], + [4, 10, 3], + ]) + // The last three: 21, 24 and 3 over two weeks (1.5 a week). + expect(velocity.averagePerWeek).toBe(15.5) + // Writes after the close leave it alone. + await call('PATCH', `/issues/${four.id}`, { estimate: 'XL' }) + expect((await call('GET', `/sprints/${active.id}`)).body.current.donePoints).toBe(3) + + const started = await call('POST', `/sprints/${planned.id}/start`) + expect(started.body).toMatchObject({ state: 'active', startsOn: today(), endsOn: addDays(today(), 6), startedAt: expect.any(String) }) + expect(started.body.commitment).toEqual(started.body.current) + }) + + test('close sends an unfinished issue to the backlog when a relative is already in the target', async () => { + const sprint = await sprintsByNumber() + const [eight, story33, four] = await Promise.all(['APT-8', 'APT-33', 'APT-4'].map(async (key) => (await call('GET', `/issues/${key}`)).body as Issue)) + await call('PATCH', `/issues/${eight!.id}`, { sprintId: null }) + expect((await call('PATCH', `/issues/${story33!.id}`, { sprintId: sprint.get(5)!.id })).status).toBe(200) + await call('POST', `/sprints/${sprint.get(4)!.id}/close`, { moveIncompleteTo: sprint.get(5)!.id }) + expect(((await call('GET', `/issues/${four!.id}`)).body as Issue).sprint).toBeNull() + expect(((await call('GET', '/issues/APT-3')).body as Issue).sprint?.id).toBe(sprint.get(5)!.id) + }) + + test('delete: Admin only, planned only; members return to the backlog', async () => { + const sprint = await sprintsByNumber() + await as('dev-sam') + expect((await call('DELETE', `/sprints/${sprint.get(5)!.id}`)).status).toBe(403) + // Anyone else may create, start and close. + expect((await call('POST', '/sprints', {})).status).toBe(201) + await as('dev-alex', 'Admin') + expect((await call('DELETE', `/sprints/${sprint.get(4)!.id}`)).status).toBe(409) + expect((await call('DELETE', `/sprints/${sprint.get(5)!.id}`)).status).toBe(204) + expect((await call('GET', `/sprints/${sprint.get(5)!.id}`)).status).toBe(404) + expect(((await call('GET', '/issues/APT-8')).body as Issue).sprint).toBeNull() + }) + + test('workspace sprint settings: Admin sets length and timezone; new sprints take the length', async () => { + expect((await call('PATCH', '/workspace', { sprintLengthWeeks: 3 })).status).toBe(400) + expect((await call('PATCH', '/workspace', { timezone: 'Mars/Olympus' })).status).toBe(400) + expect((await call('PATCH', '/workspace', { sprintLengthWeeks: 2, timezone: 'Europe/Berlin' })).body).toMatchObject({ sprintLengthWeeks: 2, timezone: 'Europe/Berlin' }) + expect((await call('POST', '/sprints', {})).body.lengthWeeks).toBe(2) + await as('dev-sam') + expect((await call('PATCH', '/workspace', { sprintLengthWeeks: 1 })).status).toBe(403) + }) +}) diff --git a/web/src/dev/mock-tracker.ts b/web/src/dev/mock-tracker.ts index b6ad4cd..d5712d3 100644 --- a/web/src/dev/mock-tracker.ts +++ b/web/src/dev/mock-tracker.ts @@ -6,8 +6,13 @@ // (Dashboard/blue, Platform API/purple, Builder Console/orange), 30 issues // across every status (Alex Chen reports 10 of them, so "Reported by me" is // not empty), then 2 epics and 4 stories (APT-31…36, In Progress) that bundle -// every seeded issue n with n % 5 != 0 under stories[n % 4], and three shared -// views (Bugs, My issues, By epic). +// every seeded issue n with n % 5 != 0 under stories[n % 4], four Done work +// items (APT-37…40) and three shared views (Bugs, My issues, By epic). +// Sprints (API.md v0.1.10, relative to today in Asia/Tokyo): three closed +// one-week sprints with velocities 18/21/24 points, an active two-week sprint +// on its fourth day with a scope increase and a cancellation, and a planned +// one; 17 work items carry a size. The exact fixture (shared authority with +// the server seed) is `SPRINT_FIXTURE` below. // The caller is Alex Chen as Team Admin; MOCK_ROLE=Editor (or Viewer) makes // them a non-admin. `POST /api/tracker/v1/__mock/caller {sub, role?}` switches // the signed-in person (role default Editor); a `sub` outside the seed needs a @@ -22,6 +27,7 @@ import type { ActivityField, ApiError, Attachment, + Burndown, Comment, Filter, GroupBy, @@ -38,10 +44,19 @@ import type { Project, Report, Role, + Size, Sort, + Sprint, + SprintLength, + SprintRef, + SprintState, Status, StatusCategory, + Tally, TimelineItem, + Unit, + Velocity, + VelocityEntry, View, ViewLayout, Workspace, @@ -67,6 +82,30 @@ import { TITLE_MAX, WORK_ITEM_TYPES, } from '../model/issues' +import { + addDays, + addTally, + averagePerWeek, + burndownPoints, + comingMonday, + compareSprints, + dayInZone, + doneIn, + endsOnFor, + isDay, + overlapsAny, + scopeIn, + SIZE_POINTS, + SIZES, + SPRINT_GOAL_MAX_BYTES, + SPRINT_LENGTHS, + SPRINT_NAME_MAX, + sprintDeltas, + sprintRef, + UNITS, + ZERO_TALLY, + type SprintStanding, +} from '../model/sprints' const BASE = '/api/tracker/v1' const DEFAULT_LIMIT = 50 @@ -97,7 +136,11 @@ const FILTER_KEYS: Record = { project: true, epic: true, story: true, + sprint: true, } +const VELOCITY_LIMIT_DEFAULT = 8 +const VELOCITY_LIMIT_MAX = 26 +const DEFAULT_TIMEZONE = 'Asia/Tokyo' const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ' @@ -144,12 +187,17 @@ type StoredIssue = { updatedAt: string completedAt: string | null deleted: boolean + estimate: Size | null + sprintId: string | null } type StoredComment = Comment & { deleted: boolean } type StoredAttachment = Attachment & { bytes: Uint8Array; deleted: boolean } type StoredProject = { id: string; name: string; description: string; color: LabelColor; archivedAt: string | null; createdAt: string; updatedAt: string } type Block = { blockerId: string; blockedId: string } - +/** `state` is derived from `startedAt`/`closedAt`, as on the server. */ +type StoredSprint = { id: string; number: number; name: string; goal: string; lengthWeeks: SprintLength; startsOn: string; endsOn: string; startedAt: string | null; closedAt: string | null; createdAt: string; updatedAt: string } +/** One `tracker_sprint_event` row: the signed deltas one issue write caused in one sprint. */ +type SprintEvent = { id: string; sprintId: string; issueId: string; at: string; tally: Tally } const STATUS_SEED: readonly [string, StatusCategory, string][] = [ ['Backlog', 'backlog', 'gray'], ['Todo', 'unstarted', 'gray'], @@ -220,6 +268,64 @@ const STORY_SEED: readonly string[] = [ 'As a triager, I want to prioritize incoming work', 'As an assignee, I want to find my next task', ] +/** API.md v0.1.10 fixture: Done work items appended after the stories (closed-sprint members). */ +const DONE_SEED: readonly [string, IssueType][] = [ + ['Speed up issue search', 'task'], + ['Add bulk status change', 'feature'], + ['Tidy up the settings layout', 'task'], + ['Show issue counts per project', 'feature'], +] + +type FixtureTime = readonly [dayOffset: number, time: string] +/** + * The sprint fixture shared with the server seed (offsets are days from + * today in Asia/Tokyo, times are that zone's wall clock). Every ledger row is + * a join (+scope), done (+done) or cancel (−scope) of one issue by number at + * its size; the rows yield velocities 18/21/24 points (committed 21/24/27), + * an active sprint at commitment 10 points / 6 issues with a scope increase + * (APT-10) and a cancellation (APT-30), and a planned sprint of 4 points. + */ +export const SPRINT_FIXTURE = { + sizes: { 8: 'XS', 16: 'XS', 3: 'S', 10: 'S', 30: 'S', 2: 'M', 4: 'M', 14: 'M', 11: 'L', 17: 'L', 37: 'L', 5: 'XL', 23: 'XL', 29: 'XL', 38: 'XL', 39: 'XL', 40: 'XL' } as Record, + sprints: [ + { number: 1, lengthWeeks: 1, startOffset: -24, goal: 'Bug intake basics', started: true, closed: true, members: [5, 11, 17] }, + { number: 2, lengthWeeks: 1, startOffset: -17, goal: 'Triage flow', started: true, closed: true, members: [23, 29, 37] }, + { number: 3, lengthWeeks: 1, startOffset: -10, goal: 'Board polish', started: true, closed: true, members: [38, 39, 40] }, + { number: 4, lengthWeeks: 2, startOffset: -3, goal: 'Sprint planning and burndown', started: true, closed: false, members: [2, 3, 4, 10, 15, 30, 34] }, + { number: 5, lengthWeeks: 1, startOffset: 11, goal: '', started: false, closed: false, members: [8, 14, 26], createdAt: [-1, '10:00'] as FixtureTime }, + ] as { number: number; lengthWeeks: SprintLength; startOffset: number; goal: string; started: boolean; closed: boolean; members: number[]; createdAt?: FixtureTime }[], + rows: [ + [1, 'join', [5, 11, 17, 2], [-25, '15:00']], + [1, 'done', [5], [-22, '16:00']], + [1, 'done', [11], [-20, '11:00']], + [1, 'done', [17], [-18, '17:00']], + [2, 'join', [23, 29, 37], [-18, '15:00']], + [2, 'join', [2], [-18, '18:00']], + [2, 'done', [23], [-16, '16:00']], + [2, 'done', [37], [-14, '11:00']], + [2, 'done', [29], [-12, '17:00']], + [3, 'join', [38, 39, 40], [-11, '15:00']], + [3, 'join', [2], [-11, '18:00']], + [3, 'done', [38], [-9, '16:00']], + [3, 'done', [39], [-7, '11:00']], + [3, 'done', [40], [-4, '10:00']], + [4, 'join', [3, 4, 15, 30, 34], [-4, '14:00']], + [4, 'join', [2], [-4, '18:00']], + [4, 'join', [10], [-2, '11:00']], + [4, 'cancel', [30], [-1, '15:00']], + [5, 'join', [8, 14, 26], [-1, '10:00']], + ] as [sprint: number, kind: 'join' | 'done' | 'cancel', issues: number[], at: FixtureTime][], +} + +/** The instant at wall-clock `time` (HH:MM) on `day` in `timeZone`. */ +function zonedInstant(day: string, time: string, timeZone: string): string { + const [hour, minute] = time.split(':').map(Number) as [number, number] + const guess = Date.UTC(Number(day.slice(0, 4)), Number(day.slice(5, 7)) - 1, Number(day.slice(8, 10)), hour, minute) + const parts = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' }).formatToParts(guess) + const part = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((candidate) => candidate.type === type)!.value) + const shown = Date.UTC(part('year'), part('month') - 1, part('day'), part('hour'), part('minute')) + return new Date(guess - (shown - guess)).toISOString() +} /** * Mirrors the server's SeedDev: issue `i` has status i%6, type i%3 (bug, @@ -227,7 +333,8 @@ const STORY_SEED: readonly string[] = [ * project by `seedProjectIndex(i+1)`; bugs carry a report with environment * i%4 and surface i%7. Then the epics and stories: In Progress, medium * priority, reported by Alex, unassigned, no labels, project or description; - * seed issue n (1-based) with n % 5 != 0 gets the parent stories[n % 4]. + * seed issue n (1-based) with n % 5 != 0 gets the parent stories[n % 4]. Then + * DONE_SEED the same way in status Done, and SPRINT_FIXTURE. * Creation times are spaced one hour apart. `withProjects: false` seeds a * workspace without projects. */ @@ -275,12 +382,15 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { updatedAt: createdAt, completedAt: status.category === 'completed' || status.category === 'canceled' ? createdAt : null, deleted: false, + estimate: null, + sprintId: null, } issues.push(issue) activities.push({ id: ulid(T0 + (i + 1) * HOUR, seq++), issueId: issue.id, actor: issue.reporter, field: 'created', from: null, to: null, createdAt }) }) const inProgress = statuses.find((status) => status.name === 'In Progress')! - const bundle = (title: string, type: IssueType, parentId: string | null): StoredIssue => { + const done = statuses.find((status) => status.name === 'Done')! + const bundle = (title: string, type: IssueType, parentId: string | null, status = inProgress): StoredIssue => { const number = issues.length + 1 const createdAt = at(number) const issue: StoredIssue = { @@ -290,7 +400,7 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { description: '', type, priority: 'medium', - statusId: inProgress.id, + statusId: status.id, assignee: null, reporter: MOCK_PEOPLE.alex, labelIds: [], @@ -300,8 +410,10 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { report: null, createdAt, updatedAt: createdAt, - completedAt: null, + completedAt: status === done ? createdAt : null, deleted: false, + estimate: null, + sprintId: null, } issues.push(issue) activities.push({ id: ulid(T0 + number * HOUR, seq++), issueId: issue.id, actor: issue.reporter, field: 'created', from: null, to: null, createdAt }) @@ -312,6 +424,30 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { issues.slice(0, SEED_TITLES.length).forEach((issue) => { if (issue.number % 5 !== 0) issue.parentId = stories[issue.number % 4]!.id }) + for (const [title, type] of DONE_SEED) bundle(title, type, null, done) + const byNumber = (number: number) => issues[number - 1]! + for (const [number, size] of Object.entries(SPRINT_FIXTURE.sizes)) byNumber(Number(number)).estimate = size + const today = dayInZone(Math.max(Date.now(), T0 + 100 * HOUR), DEFAULT_TIMEZONE) + const instant = ([offset, time]: FixtureTime) => zonedInstant(addDays(today, offset), time, DEFAULT_TIMEZONE) + const sprints: StoredSprint[] = SPRINT_FIXTURE.sprints.map((fixture) => { + const startsOn = addDays(today, fixture.startOffset) + const endsOn = endsOnFor(startsOn, fixture.lengthWeeks) + const createdAt = instant(fixture.createdAt ?? [fixture.startOffset - 1, '15:00']) + const startedAt = fixture.started ? zonedInstant(startsOn, '09:00', DEFAULT_TIMEZONE) : null + const closedAt = fixture.closed ? zonedInstant(endsOn, '18:00', DEFAULT_TIMEZONE) : null + const sprint: StoredSprint = { id: ulid(Date.parse(createdAt), seq++), number: fixture.number, name: `Sprint ${fixture.number}`, goal: fixture.goal, lengthWeeks: fixture.lengthWeeks, startsOn, endsOn, startedAt, closedAt, createdAt, updatedAt: closedAt ?? startedAt ?? createdAt } + for (const number of fixture.members) byNumber(number).sprintId = sprint.id + return sprint + }) + const sprintEvents: SprintEvent[] = SPRINT_FIXTURE.rows.flatMap(([sprintNumber, kind, numbers, time]) => + numbers.map((number) => { + const points = SIZE_POINTS[SPRINT_FIXTURE.sizes[number]!] ?? 0 + const tally: Tally = + kind === 'join' ? { ...ZERO_TALLY, scopePoints: points, scopeIssues: 1 } : kind === 'done' ? { ...ZERO_TALLY, donePoints: points, doneIssues: 1 } : { ...ZERO_TALLY, scopePoints: -points, scopeIssues: -1 } + const at = instant(time) + return { id: ulid(Date.parse(at), seq++), sprintId: sprints[sprintNumber - 1]!.id, issueId: byNumber(number).id, at, tally } + }) + ) const views: (View & { ownerSub: string })[] = [ { id: ulid(T0, seq++), name: 'Bugs', owner: MOCK_PEOPLE.alex, ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { type: ['bug'] }, sort: 'updated', position: 0, createdAt: at(0), updatedAt: at(0) }, { id: ulid(T0, seq++), name: 'My issues', owner: MOCK_PEOPLE.alex, ownerSub: MOCK_PEOPLE.alex.sub, shared: true, layout: 'list', groupBy: 'none', filter: { assignee: ['me'] }, sort: 'updated', position: 1, createdAt: at(0), updatedAt: at(0) }, @@ -319,7 +455,7 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { ] const role = process.env.MOCK_ROLE === 'Editor' || process.env.MOCK_ROLE === 'Viewer' ? (process.env.MOCK_ROLE as Role) : 'Admin' return { - workspace: { id: MOCK_WORKSPACE_ID, key: 'APT', name: MOCK_WORKSPACE_ID, createdAt: at(0), updatedAt: at(0) }, + workspace: { id: MOCK_WORKSPACE_ID, key: 'APT', name: MOCK_WORKSPACE_ID, sprintLengthWeeks: 1 as SprintLength, timezone: DEFAULT_TIMEZONE, createdAt: at(0), updatedAt: at(0) }, statuses, labels, projects, @@ -329,6 +465,8 @@ function seedTracker({ withProjects = process.env.MOCK_PROJECTS !== 'none' }: { comments: [] as StoredComment[], attachments: [] as StoredAttachment[], views, + sprints, + sprintEvents, caller: MOCK_PEOPLE.alex as Person, role, clock: T0 + 100 * HOUR, @@ -392,25 +530,91 @@ function ancestorOfType(issue: StoredIssue, type: IssueType): StoredIssue | unde return undefined } -/** Epics and stories: over all live level-0 descendants, `total` excludes canceled ones, `completed` counts completed ones. */ +/** Epics and stories: over all live level-0 descendants, `total` excludes canceled ones, `completed` counts completed ones; `points` sums their sizes the same way. */ function progressOf(issue: StoredIssue): Progress | null { if (levelOf(issue.type) === 0) return null - const category = (statusId: string) => state.statuses.find((status) => status.id === statusId)?.category - const progress: Progress = { total: 0, completed: 0 } + const progress: Progress = { total: 0, completed: 0, points: { total: 0, completed: 0 } } const seen = new Set([issue.id]) for (let frontier = [issue.id]; frontier.length > 0; ) { const children = live().filter((candidate) => candidate.parentId !== null && frontier.includes(candidate.parentId) && !seen.has(candidate.id)) for (const child of children) { seen.add(child.id) - if (levelOf(child.type) !== 0 || category(child.statusId) === 'canceled') continue + if (levelOf(child.type) !== 0 || categoryOf(child.statusId) === 'canceled') continue + const points = child.estimate ? SIZE_POINTS[child.estimate] : 0 progress.total++ - if (category(child.statusId) === 'completed') progress.completed++ + progress.points.total += points + if (categoryOf(child.statusId) === 'completed') { + progress.completed++ + progress.points.completed += points + } } frontier = children.map((child) => child.id) } return progress } +const categoryOf = (statusId: string) => state.statuses.find((status) => status.id === statusId)?.category + +// --- sprints -------------------------------------------------------------------- + +function sprintState(sprint: StoredSprint): SprintState { + return sprint.closedAt ? 'closed' : sprint.startedAt ? 'active' : 'planned' +} + +const sprintById = (id: string | null) => (id ? state.sprints.find((sprint) => sprint.id === id) : undefined) +const activeSprint = () => state.sprints.find((sprint) => sprintState(sprint) === 'active') +const openSprints = () => state.sprints.filter((sprint) => sprintState(sprint) !== 'closed') +/** Today in the workspace timezone (reads the clock without advancing it). */ +const today = () => dayInZone(Math.max(Date.now(), state.clock), state.workspace.timezone) + +function refOfSprint(sprint: StoredSprint): SprintRef { + return sprintRef({ ...sprint, state: sprintState(sprint) }) +} + +/** The sum of the sprint's ledger rows, optionally only up to `until` and only for issues `keep` accepts. */ +function ledgerSum(sprintId: string, until?: string, keep: (issueId: string) => boolean = () => true): Tally { + return state.sprintEvents.filter((event) => event.sprintId === sprintId && (until === undefined || event.at <= until) && keep(event.issueId)).reduce((sum, event) => addTally(sum, event.tally), ZERO_TALLY) +} + +function sprintView(sprint: StoredSprint): Sprint { + return { ...sprint, state: sprintState(sprint), current: ledgerSum(sprint.id), commitment: sprint.startedAt ? ledgerSum(sprint.id, sprint.startedAt) : null } +} + +function standingOf(issue: Pick): SprintStanding { + return { sprintId: issue.sprintId, size: issue.estimate, category: categoryOf(issue.statusId), deleted: issue.deleted } +} + +/** The ledger rule: one row per sprint the write changed, closed sprints excepted (no rows after `closedAt`). */ +function writeLedger(issueId: string, before: SprintStanding, after: SprintStanding, at: string) { + for (const [sprintId, tally] of sprintDeltas(before, after)) { + const sprint = sprintById(sprintId) + if (sprint && sprintState(sprint) !== 'closed') state.sprintEvents.push({ id: nextId(), sprintId, issueId, at, tally }) + } +} + +/** Live strict ancestors of an issue whose parent is `parentId`. */ +function ancestorsFrom(parentId: string | null): StoredIssue[] { + const out: StoredIssue[] = [] + for (let cursor = issueById(parentId); cursor && out.length < ANCESTOR_HOPS; cursor = issueById(cursor.parentId)) out.push(cursor) + return out +} + +function descendantsOf(issueId: string): StoredIssue[] { + const out: StoredIssue[] = [] + for (let frontier = [issueId]; frontier.length > 0; ) { + const children = live().filter((candidate) => candidate.parentId !== null && frontier.includes(candidate.parentId)) + out.push(...children) + frontier = children.map((child) => child.id) + } + return out +} + +/** Ancestors (through `parentId`) and descendants of the issue that are members of `sprintId` (lineage-exclusive). */ +function lineageMembers(issueId: string | null, parentId: string | null, sprintId: string): number { + const relatives = [...ancestorsFrom(parentId), ...(issueId ? descendantsOf(issueId) : [])] + return relatives.filter((relative) => relative.id !== issueId && relative.sprintId === sprintId).length +} + function summary(issue: StoredIssue): IssueSummary { const parent = issueById(issue.parentId) const epic = ancestorOfType(issue, 'epic') @@ -431,6 +635,8 @@ function summary(issue: StoredIssue): IssueSummary { epic: epic ? ref(epic) : null, story: story ? ref(story) : null, progress: progressOf(issue), + estimate: issue.estimate, + sprint: issue.sprintId && sprintById(issue.sprintId) ? refOfSprint(sprintById(issue.sprintId)!) : null, dueOn: issue.dueOn, report: issue.report, commentCount: state.comments.filter((comment) => comment.issueId === issue.id && !comment.deleted).length, @@ -566,6 +772,24 @@ function hierarchyMessage(childType: IssueType): string { return childType === 'epic' ? 'Epics cannot have a parent' : 'Stories can only have an epic parent' } +function estimateProblem(value: unknown, type: IssueType): Problem | undefined { + if (value === null || value === undefined) return undefined + if (!SIZES.includes(value as Size)) return { path: 'estimate', message: `estimate must be one of ${SIZES.join(', ')} or null` } + if (type === 'epic') return { path: 'estimate', message: 'an epic takes no estimate' } + return undefined +} + +/** Why an issue (`issueId` null while creating) of `type` under `parentId` cannot join `value` (`domain.ValidateMembership`). */ +function sprintJoinProblem(value: unknown, type: IssueType, issueId: string | null, parentId: string | null): Problem | undefined { + if (typeof value !== 'string') return { path: 'sprintId', message: 'sprintId must be a string or null' } + const sprint = sprintById(value) + if (!sprint) return { path: 'sprintId', message: 'unknown sprint' } + if (type === 'epic') return { path: 'sprintId', message: 'an epic cannot join a sprint' } + if (sprintState(sprint) === 'closed') return { path: 'sprintId', message: 'sprint is closed' } + if (lineageMembers(issueId, parentId, value) > 0) return { path: 'sprintId', message: 'an ancestor or descendant is already in this sprint' } + return undefined +} + function parseFilter(raw: string | null): Filter | Problem { if (!raw) return {} let parsed: unknown @@ -592,6 +816,7 @@ function parseFilter(raw: string | null): Filter | Problem { for (const key of ['epic', 'story'] as const) { if ((filter[key] as string[] | undefined)?.some((value) => value !== 'none' && !ULID_PATTERN.test(value))) return { path: `filter.${key}`, message: `${key} must list issue ids or none` } } + if ((filter.sprint as string[] | undefined)?.some((value) => value !== 'none' && value !== 'active' && !ULID_PATTERN.test(value))) return { path: 'filter.sprint', message: 'sprint must list sprint ids, active or none' } return filter as Filter } @@ -615,7 +840,7 @@ function listIssues(url: URL): Response { const descriptions = new Map(state.issues.map((issue) => [issue.id, issue.description])) const matching = live() .map(summary) - .filter((issue) => matchesFilter(issue, filter, { me: state.caller.sub, statuses: state.statuses, description: (candidate) => descriptions.get(candidate.id) ?? '' })) + .filter((issue) => matchesFilter(issue, filter, { me: state.caller.sub, statuses: state.statuses, description: (candidate) => descriptions.get(candidate.id) ?? '', activeSprintId: activeSprint()?.id ?? null })) .sort(compareIssues(sort)) const page = matching.slice(offset, offset + limit) const next = offset + limit < matching.length ? Buffer.from(String(offset + limit), 'utf8').toString('base64url') : null @@ -648,6 +873,12 @@ async function createIssue(request: Request): Promise { const problem = projectRefProblem(input.projectId, null) if (problem) return invalid(problem.path, problem.message) } + const estimate = estimateProblem(input.estimate, type) + if (estimate) return invalid(estimate.path, estimate.message) + if (input.sprintId !== undefined && input.sprintId !== null) { + const problem = sprintJoinProblem(input.sprintId, type, null, parent?.id ?? null) + if (problem) return invalid(problem.path, problem.message) + } const time = now() const number = Math.max(0, ...state.issues.map((issue) => issue.number)) + 1 const issue: StoredIssue = { @@ -669,16 +900,19 @@ async function createIssue(request: Request): Promise { updatedAt: time, completedAt: closedStatus(statusId) ? time : null, deleted: false, + estimate: (input.estimate as Size | null | undefined) ?? null, + sprintId: (input.sprintId as string | null | undefined) ?? null, } state.issues.push(issue) record(issue, 'created', null, null, time) + writeLedger(issue.id, { sprintId: null, size: null, category: undefined, deleted: false }, standingOf(issue), time) return json(full(issue), 201) } async function updateIssue(issue: StoredIssue, request: Request): Promise { const input = await body(request) if (!input) return invalid('', 'A JSON object is required') - const known = ['title', 'description', 'type', 'priority', 'statusId', 'assigneeSub', 'labelIds', 'parentId', 'blocks', 'dueOn', 'report', 'projectId'] + const known = ['title', 'description', 'type', 'priority', 'statusId', 'assigneeSub', 'labelIds', 'parentId', 'blocks', 'dueOn', 'report', 'projectId', 'estimate', 'sprintId'] const unknownKey = Object.keys(input).find((key) => !known.includes(key)) if (unknownKey) return invalid(unknownKey, `unknown field ${unknownKey}`) if ('title' in input) { @@ -721,8 +955,28 @@ async function updateIssue(issue: StoredIssue, request: Request): Promise child.parentId === issue.id && !canParent(child.type, nextType)) if (misfit) return invalid('type', `${identifier(misfit)}: ${hierarchyMessage(misfit.type)}`) } + // Estimate and sprint (API.md v0.1.10): an epic takes neither; a closed sprint's members are frozen; a type or parent change re-checks membership. + const nextEstimate = 'estimate' in input ? ((input.estimate as Size | null) ?? null) : issue.estimate + const estimate = 'estimate' in input ? estimateProblem(input.estimate, nextType) : nextType === 'epic' && nextEstimate ? { path: 'estimate', message: 'an epic takes no estimate' } : undefined + if (estimate) return invalid(estimate.path, estimate.message) + const nextSprintId = 'sprintId' in input ? ((input.sprintId as string | null) ?? null) : issue.sprintId + const sprintChanged = nextSprintId !== issue.sprintId + const currentSprint = sprintById(issue.sprintId) + if (sprintChanged && currentSprint && sprintState(currentSprint) === 'closed') return invalid('sprintId', 'membership is frozen once the sprint is closed') + const nextParentId = nextParent?.id ?? null + if (nextSprintId && (sprintChanged || parentChanged || nextType !== issue.type)) { + const problem = sprintChanged ? sprintJoinProblem(nextSprintId, nextType, issue.id, nextParentId) : nextType === 'epic' ? { path: 'sprintId', message: 'an epic cannot join a sprint' } : lineageMembers(issue.id, nextParentId, nextSprintId) > 0 ? { path: 'sprintId', message: 'an ancestor or descendant is already in this sprint' } : undefined + if (problem) return invalid(problem.path, problem.message) + } + if (parentChanged) { + // The subtree's members against the new ancestors, open sprints only. + const ancestors = ancestorsFrom(nextParentId) + const clash = descendantsOf(issue.id).find((child) => child.sprintId && sprintState(sprintById(child.sprintId)!) !== 'closed' && ancestors.some((ancestor) => ancestor.sprintId === child.sprintId)) + if (clash) return invalid('sprintId', `${identifier(clash)}: an ancestor or descendant is already in this sprint`) + } const time = now() + const before = standingOf(issue) let changed = false const change = (field: ActivityField, from: unknown, to: unknown) => { record(issue, field, from, to, time) @@ -789,6 +1043,16 @@ async function updateIssue(issue: StoredIssue, request: Request): Promise (status.position = position)) } +// --- sprints (API.md v0.1.10) ------------------------------------------------------- + +function isTimeZone(value: unknown): value is string { + if (typeof value !== 'string' || !value) return false + try { + new Intl.DateTimeFormat('en-US', { timeZone: value }) + return true + } catch { + return false + } +} + +function sprintInputProblem(input: Record): Problem | undefined { + const unknownKey = Object.keys(input).find((key) => !['name', 'goal', 'startsOn', 'lengthWeeks'].includes(key)) + if (unknownKey) return { path: unknownKey, message: `unknown field ${unknownKey}` } + if ('name' in input && (typeof input.name !== 'string' || !input.name.trim() || Array.from(input.name.trim()).length > SPRINT_NAME_MAX)) return { path: 'name', message: `name must be 1–${SPRINT_NAME_MAX} characters` } + if ('goal' in input && (typeof input.goal !== 'string' || bytes(input.goal) > SPRINT_GOAL_MAX_BYTES)) return { path: 'goal', message: `goal must be at most ${SPRINT_GOAL_MAX_BYTES} bytes` } + if ('startsOn' in input && !isDay(input.startsOn)) return { path: 'startsOn', message: 'startsOn must be YYYY-MM-DD' } + if ('lengthWeeks' in input && !SPRINT_LENGTHS.includes(input.lengthWeeks as SprintLength)) return { path: 'lengthWeeks', message: 'lengthWeeks must be 1 or 2' } + return undefined +} + +/** `?unit=` (default points) and `?project=` (an id or `none`: only events of issues currently in that project). */ +function chartScope(url: URL): { unit: Unit; keep: (issueId: string) => boolean } | Problem { + const unit = (url.searchParams.get('unit') ?? 'points') as Unit + if (!UNITS.includes(unit)) return { path: 'unit', message: 'unit must be points or issues' } + const project = url.searchParams.get('project') + if (!project) return { unit, keep: () => true } + const projectOf = (issueId: string) => state.issues.find((issue) => issue.id === issueId)?.projectId ?? null + return { unit, keep: (issueId) => (project === 'none' ? projectOf(issueId) === null : projectOf(issueId) === project) } +} + +function burndownOf(sprint: StoredSprint, unit: Unit, keep: (issueId: string) => boolean): Burndown { + const zone = state.workspace.timezone + const rows = state.sprintEvents.filter((event) => event.sprintId === sprint.id && keep(event.issueId)).map((event) => ({ day: dayInZone(event.at, zone), tally: event.tally })) + const baseline = ledgerSum(sprint.id, sprint.startedAt ?? undefined, keep) + const day = today() + return { sprint: refOfSprint(sprint), unit, today: day, points: burndownPoints({ startsOn: sprint.startsOn, endsOn: sprint.endsOn, today: day, unit, baseline, rows, closed: sprintState(sprint) === 'closed' }) } +} + +function velocityOf(unit: Unit, keep: (issueId: string) => boolean, limit: number): Velocity { + const entries: VelocityEntry[] = state.sprints + .filter((sprint) => sprintState(sprint) === 'closed') + .sort((a, b) => a.closedAt!.localeCompare(b.closedAt!)) + .map((sprint) => ({ sprint: refOfSprint(sprint), lengthWeeks: sprint.lengthWeeks, committed: scopeIn(ledgerSum(sprint.id, sprint.startedAt!, keep), unit), completed: doneIn(ledgerSum(sprint.id, undefined, keep), unit) })) + return { unit, items: entries.slice(-limit), averagePerWeek: averagePerWeek(entries) } +} + +/** Moves `issue` to `sprintId` (null = backlog) at `time`: `sprint` activity and the ledger rows of the open sprints involved. */ +function moveToSprint(issue: StoredIssue, sprintId: string | null, time: string) { + const before = standingOf(issue) + const from = sprintById(issue.sprintId) + const to = sprintById(sprintId) + record(issue, 'sprint', from ? refOfSprint(from) : null, to ? refOfSprint(to) : null, time) + issue.sprintId = sprintId + issue.updatedAt = time + writeLedger(issue.id, before, standingOf(issue), time) +} + +async function sprintRoutes(request: Request, url: URL, route: string): Promise { + let match: RegExpMatchArray | null + if (route === 'GET /velocity') { + const scope = chartScope(url) + if (isProblem(scope)) return invalid(scope.path, scope.message) + const limitParam = url.searchParams.get('limit') + const limit = limitParam === null ? VELOCITY_LIMIT_DEFAULT : Number(limitParam) + if (!Number.isInteger(limit) || limit < 1 || limit > VELOCITY_LIMIT_MAX) return invalid('limit', `limit must be between 1 and ${VELOCITY_LIMIT_MAX}`) + return json(velocityOf(scope.unit, scope.keep, limit)) + } + if (route === 'GET /sprints') { + const wanted = url.searchParams.get('state') + if (wanted !== null && !['planned', 'active', 'closed'].includes(wanted)) return invalid('state', 'state must be planned, active or closed') + const items = state.sprints.map(sprintView).filter((sprint) => wanted === null || sprint.state === wanted) + return json({ items: items.sort(compareSprints) }) + } + if (route === 'POST /sprints') { + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + const problem = sprintInputProblem(input) + if (problem) return invalid(problem.path, problem.message) + const lengthWeeks = (input.lengthWeeks as SprintLength | undefined) ?? state.workspace.sprintLengthWeeks + const latest = openSprints().sort((a, b) => b.endsOn.localeCompare(a.endsOn))[0] + const startsOn = (input.startsOn as string | undefined) ?? (latest ? addDays(latest.endsOn, 1) : comingMonday(today())) + const endsOn = endsOnFor(startsOn, lengthWeeks) + if (overlapsAny({ startsOn, endsOn }, openSprints())) return conflict('the dates overlap another sprint that is not closed') + const time = now() + const number = Math.max(0, ...state.sprints.map((sprint) => sprint.number)) + 1 + const sprint: StoredSprint = { + id: nextId(), + number, + name: typeof input.name === 'string' ? input.name.trim() : `Sprint ${number}`, + goal: (input.goal as string | undefined) ?? '', + lengthWeeks, + startsOn, + endsOn, + startedAt: null, + closedAt: null, + createdAt: time, + updatedAt: time, + } + state.sprints.push(sprint) + return json(sprintView(sprint), 201) + } + if ((match = route.match(/^(GET|PATCH|DELETE) \/sprints\/([^/]+)$/))) { + const [, method, rawId] = match + const sprint = sprintById(decodeURIComponent(rawId!)) + if (!sprint) return notFound() + if (method === 'GET') return json(sprintView(sprint)) + if (method === 'DELETE') { + if (!isAdmin()) return forbidden() + if (sprintState(sprint) !== 'planned') return conflict('only a planned sprint can be deleted') + const time = now() + for (const issue of live().filter((candidate) => candidate.sprintId === sprint.id)) moveToSprint(issue, null, time) + state.sprintEvents = state.sprintEvents.filter((event) => event.sprintId !== sprint.id) + state.sprints = state.sprints.filter((candidate) => candidate !== sprint) + return noContent() + } + const input = await body(request) + if (!input) return invalid('', 'A JSON object is required') + const problem = sprintInputProblem(input) + if (problem) return invalid(problem.path, problem.message) + if (('startsOn' in input || 'lengthWeeks' in input) && sprintState(sprint) !== 'planned') return conflict('dates change only while the sprint is planned') + const startsOn = (input.startsOn as string | undefined) ?? sprint.startsOn + const lengthWeeks = (input.lengthWeeks as SprintLength | undefined) ?? sprint.lengthWeeks + const endsOn = endsOnFor(startsOn, lengthWeeks) + if (overlapsAny({ startsOn, endsOn }, openSprints().filter((other) => other !== sprint))) return conflict('the dates overlap another sprint that is not closed') + if (typeof input.name === 'string') sprint.name = input.name.trim() + if (typeof input.goal === 'string') sprint.goal = input.goal + Object.assign(sprint, { startsOn, lengthWeeks, endsOn, updatedAt: now() }) + return json(sprintView(sprint)) + } + if ((match = route.match(/^(POST|GET) \/sprints\/([^/]+)\/(start|close|burndown)$/))) { + const [, method, rawId, action] = match + const sprint = sprintById(decodeURIComponent(rawId!)) + if (!sprint) return notFound() + if (method === 'GET' && action === 'burndown') { + const scope = chartScope(url) + if (isProblem(scope)) return invalid(scope.path, scope.message) + return json(burndownOf(sprint, scope.unit, scope.keep)) + } + if (method !== 'POST' || action === 'burndown') return notFound() + if (action === 'start') { + if (sprintState(sprint) !== 'planned') return conflict('only a planned sprint can be started') + if (activeSprint()) return conflict('another sprint is active; close it first') + // A start before the planned date moves the sprint to today, keeping its length. + const startsOn = sprint.startsOn > today() ? today() : sprint.startsOn + const endsOn = endsOnFor(startsOn, sprint.lengthWeeks) + if (overlapsAny({ startsOn, endsOn }, openSprints().filter((other) => other !== sprint))) return conflict('starting today would overlap another sprint that is not closed') + const time = now() + Object.assign(sprint, { startsOn, endsOn, startedAt: time, updatedAt: time }) + return json(sprintView(sprint)) + } + const input = await body(request) + if (!input || !('moveIncompleteTo' in input) || (input.moveIncompleteTo !== null && typeof input.moveIncompleteTo !== 'string')) return invalid('moveIncompleteTo', 'moveIncompleteTo must be a planned sprint id or null') + if (sprintState(sprint) !== 'active') return conflict('only the active sprint can be closed') + const target = input.moveIncompleteTo === null ? null : sprintById(input.moveIncompleteTo as string) + if (input.moveIncompleteTo !== null && (!target || sprintState(target) !== 'planned')) return invalid('moveIncompleteTo', 'moveIncompleteTo must be a planned sprint id or null') + const time = now() + Object.assign(sprint, { closedAt: time, updatedAt: time }) + // Unfinished scope moves; the closed sprint takes no rows, so the move is on the target's ledger only. A relative already in the target sends an issue to the backlog. + const unfinished = live().filter((issue) => issue.sprintId === sprint.id && categoryOf(issue.statusId) !== 'completed' && categoryOf(issue.statusId) !== 'canceled') + for (const issue of unfinished) moveToSprint(issue, target && lineageMembers(issue.id, issue.parentId, target.id) === 0 ? target.id : null, time) + return json(sprintView(sprint)) + } + return undefined +} + /** Handles `/api/tracker/v1/*`; undefined for any other path. */ export async function trackerRoutes(request: Request, url: URL): Promise { if (!url.pathname.startsWith(`${BASE}/`)) return undefined @@ -904,8 +1335,12 @@ export async function trackerRoutes(request: Request, url: URL): Promise 100)) return invalid('name', 'name must be 1–100 characters') + if ('sprintLengthWeeks' in input && !SPRINT_LENGTHS.includes(input.sprintLengthWeeks as SprintLength)) return invalid('sprintLengthWeeks', 'sprintLengthWeeks must be 1 or 2') + if ('timezone' in input && !isTimeZone(input.timezone)) return invalid('timezone', 'timezone must be an IANA time zone name') if (typeof input.key === 'string') state.workspace.key = input.key if (typeof input.name === 'string') state.workspace.name = input.name.trim() + if (typeof input.sprintLengthWeeks === 'number') state.workspace.sprintLengthWeeks = input.sprintLengthWeeks as SprintLength + if (typeof input.timezone === 'string') state.workspace.timezone = input.timezone state.workspace.updatedAt = now() return json(workspace()) } @@ -1053,7 +1488,9 @@ export async function trackerRoutes(request: Request, url: URL): Promise