diff --git a/backend/src/github_pm/api.py b/backend/src/github_pm/api.py index a1f227c..2a89779 100644 --- a/backend/src/github_pm/api.py +++ b/backend/src/github_pm/api.py @@ -28,6 +28,21 @@ # We sort "semver" style milestones first, then others alphabetically VERSION_MATCH = re.compile(r"^v\d+\.\d+\.\d+$") + +# Assisted-by: openai-code-assist +def _milestone_sort_key(milestone: dict[str, Any]) -> tuple: + """Sort version milestones numerically before other milestones.""" + title = milestone.get("title") or "" + version_match = VERSION_MATCH.fullmatch(title) + if version_match: + return ( + 0, + tuple(int(part) for part in version_match.group(0)[1:].split(".")), + "", + ) + return (1, (), title) + + # Bounded retries for transient GitHub gateway timeouts (504). _GITHUB_504_MAX_ATTEMPTS = 5 _GITHUB_504_BACKOFF_SEC = 1.5 @@ -664,29 +679,27 @@ async def get_comment_reactions( @api_router.get("/milestones") -async def get_milestones(gitctx: Annotated[Connector, Depends(connection)]): +async def get_milestones( + gitctx: Annotated[Connector, Depends(connection)], + state: Annotated[ + Literal["open", "closed"], + Query(title="Milestone State"), + ] = "open", +): milestones = gitctx.get_paged( - f"/repos/{context.github_repo}/milestones", + f"/repos/{context.github_repo}/milestones?state={state}", headers=_GITHUB_BODY_ACCEPT, ) - versions = [] - others = [] - for m in milestones: - if VERSION_MATCH.match(m["title"]): - versions.append(m) - else: - others.append(m) - milestones = sorted(versions, key=lambda x: x["title"]) + sorted( - others, key=lambda x: x["title"] - ) - milestones.append( - { - "title": "none", - "number": 0, - "description": "No milestone", - "due_on": None, - } - ) + milestones = sorted(milestones, key=_milestone_sort_key) + if state == "open": + milestones.append( + { + "title": "none", + "number": 0, + "description": "No milestone", + "due_on": None, + } + ) return milestones @@ -703,6 +716,11 @@ class UpdateMilestone(BaseModel): due_on: datetime | None = Field(default=None, title="Milestone Due Date") +# Assisted-by: openai-code-assist +class UpdateMilestoneState(BaseModel): + state: Literal["open", "closed"] = Field(title="Milestone State") + + @api_router.post("/milestones") async def create_milestone( gitctx: Annotated[Connector, Depends(connection)], @@ -738,6 +756,38 @@ async def update_milestone( ) +# Assisted-by: openai-code-assist +@api_router.get("/milestones/{milestone_number}/open-counts") +async def get_milestone_open_counts( + gitctx: Annotated[Connector, Depends(connection)], + milestone_number: Annotated[int, Path(title="Milestone")], +): + """Return open issue and pull-request counts for a milestone.""" + items = gitctx.get_paged( + f"/repos/{context.github_repo}/issues?milestone={milestone_number}&state=open", + headers=_GITHUB_BODY_ACCEPT, + ) + open_pull_requests = sum("pull_request" in item for item in items) + return { + "open_issues": len(items) - open_pull_requests, + "open_pull_requests": open_pull_requests, + } + + +# Assisted-by: openai-code-assist +@api_router.patch("/milestones/{milestone_number}/state") +async def update_milestone_state( + gitctx: Annotated[Connector, Depends(connection)], + milestone_number: Annotated[int, Path(title="Milestone")], + milestone: Annotated[UpdateMilestoneState, Body(title="Milestone State")], +): + """Open or close a milestone without modifying its other fields.""" + return gitctx.patch( + f"/repos/{context.github_repo}/milestones/{milestone_number}", + data={"state": milestone.state}, + ) + + @api_router.delete("/milestones/{milestone_number}") async def delete_milestone( gitctx: Annotated[Connector, Depends(connection)], @@ -1141,6 +1191,17 @@ class CreateLabel(BaseModel): description: str | None = Field(default=None, title="Label Description") +class UpdateLabel(BaseModel): + """Body for updating a repository label. + + Assisted-by: openai-code-assist + """ + + name: str = Field(title="Label Name") + color: str | None = Field(default=None, title="Label Color") + description: str | None = Field(default=None, title="Label Description") + + @api_router.post("/labels") async def create_label( gitctx: Annotated[Connector, Depends(connection)], @@ -1157,6 +1218,28 @@ async def create_label( return response +@api_router.patch("/labels/{label_name}") +async def update_label( + gitctx: Annotated[Connector, Depends(connection)], + label_name: str, + label: Annotated[UpdateLabel, Body(title="Label")], +): + """Update a repository label, including its name, color, or description. + + Assisted-by: openai-code-assist + """ + + response = gitctx.patch( + f"/repos/{context.github_repo}/labels/{label_name}", + data={ + "new_name": label.name, + "color": label.color, + "description": label.description, + }, + ) + return response + + @api_router.delete("/labels/{label_name}") async def delete_label( gitctx: Annotated[Connector, Depends(connection)], label_name: str diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index a61dcbb..1b9ce57 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -38,6 +38,7 @@ get_issue_reactions, get_issues, get_labels, + get_milestone_open_counts, get_milestones, get_project, remove_blocked_by, @@ -51,9 +52,13 @@ update_comment, update_issue_body, update_issue_title, + update_label, + update_milestone_state, UpdateComment, UpdateIssueBody, UpdateIssueTitle, + UpdateLabel, + UpdateMilestoneState, ) from github_pm.app import app @@ -893,6 +898,45 @@ async def test_get_milestones(self): assert result[2]["due_on"] is None mock_gitctx.get_paged.assert_called_once() + @pytest.mark.asyncio + async def test_get_milestones_sorts_versions_numerically_before_other_milestones( + self, + ): + mock_milestones = [ + {"title": "v0.9.0", "number": 9}, + {"title": "Backlog", "number": 1}, + {"title": "v0.10.0", "number": 10}, + {"title": "v0.8.1", "number": 8}, + ] + mock_gitctx = Mock(spec=Connector) + mock_gitctx.get_paged = Mock(return_value=mock_milestones) + + result = await get_milestones(mock_gitctx) + + assert [milestone["title"] for milestone in result] == [ + "v0.8.1", + "v0.9.0", + "v0.10.0", + "Backlog", + "none", + ] + + @pytest.mark.asyncio + async def test_get_closed_milestones_omits_none_placeholder(self): + mock_milestones = [{"title": "Completed", "number": 3}] + mock_gitctx = Mock(spec=Connector) + mock_gitctx.get_paged = Mock(return_value=mock_milestones) + + with patch("github_pm.api.context") as mock_context: + mock_context.github_repo = "test/repo" + result = await get_milestones(mock_gitctx, state="closed") + + assert result == mock_milestones + mock_gitctx.get_paged.assert_called_once_with( + "/repos/test/repo/milestones?state=closed", + headers={"Accept": "application/vnd.github.full+json"}, + ) + class TestCreateMilestone: """Test the create_milestone endpoint.""" @@ -957,6 +1001,52 @@ async def test_create_milestone_with_defaults(self): assert "due_on" not in call_args[1]["data"] +class TestMilestoneState: + """Test milestone state and open-work endpoints.""" + + @pytest.mark.asyncio + async def test_get_milestone_open_counts(self): + mock_gitctx = Mock(spec=Connector) + mock_gitctx.get_paged = Mock( + return_value=[ + {"number": 1}, + {"number": 2, "pull_request": {"url": "https://example.test/pr/2"}}, + {"number": 3}, + ] + ) + + with patch("github_pm.api.context") as mock_context: + mock_context.github_repo = "test/repo" + + result = await get_milestone_open_counts(mock_gitctx, milestone_number=7) + + assert result == {"open_issues": 2, "open_pull_requests": 1} + mock_gitctx.get_paged.assert_called_once_with( + "/repos/test/repo/issues?milestone=7&state=open", + headers={"Accept": "application/vnd.github.full+json"}, + ) + + @pytest.mark.asyncio + async def test_update_milestone_state(self): + mock_response = {"number": 7, "state": "closed"} + mock_gitctx = Mock(spec=Connector) + mock_gitctx.patch = Mock(return_value=mock_response) + + with patch("github_pm.api.context") as mock_context: + mock_context.github_repo = "test/repo" + + result = await update_milestone_state( + mock_gitctx, + milestone_number=7, + milestone=UpdateMilestoneState(state="closed"), + ) + + assert result == mock_response + mock_gitctx.patch.assert_called_once_with( + "/repos/test/repo/milestones/7", data={"state": "closed"} + ) + + class TestDeleteMilestone: """Test the delete_milestone endpoint.""" @@ -1519,6 +1609,40 @@ async def test_delete_label_not_found(self): await delete_label(mock_gitctx, label_name="nonexistent") +class TestUpdateLabel: + """Test the update_label endpoint.""" + + @pytest.mark.asyncio + async def test_update_label_success(self): + """Test successfully updating a label, including its name.""" + mock_label_response = { + "id": 1, + "name": "updated-label", + "color": "green", + "description": "Updated label", + } + label_data = UpdateLabel( + name="updated-label", color="green", description="Updated label" + ) + mock_gitctx = Mock(spec=Connector) + mock_gitctx.patch = Mock(return_value=mock_label_response) + + with patch("github_pm.api.context") as mock_context: + mock_context.github_repo = "test/repo" + + result = await update_label(mock_gitctx, "old-label", label_data) + + assert result == mock_label_response + mock_gitctx.patch.assert_called_once_with( + "/repos/test/repo/labels/old-label", + data={ + "new_name": "updated-label", + "color": "green", + "description": "Updated label", + }, + ) + + class TestAddLabelToIssue: """Test the add_label_to_issue endpoint.""" diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index d9b1306..85dd7aa 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -69,39 +69,12 @@ const App = () => { } }); - const [issueMilestoneRefresh, setIssueMilestoneRefresh] = useState({ - key: 0, - milestoneNumbers: [], - }); - // Milestone numbers whose issue/PR lists may be stale after local edits. - const [dirtyMilestoneNumbers, setDirtyMilestoneNumbers] = useState([]); + // A refresh cycle is global so it also catches changes made outside this UI. + const [issueMilestoneRefresh, setIssueMilestoneRefresh] = useState(0); const [hierarchyAction, setHierarchyAction] = useState(null); - const markMilestonesDirty = (numbers) => { - const normalized = numbers - .map((n) => (n == null ? 0 : n)) - .filter((n) => typeof n === 'number'); - if (normalized.length === 0) return; - setDirtyMilestoneNumbers((prev) => [...new Set([...prev, ...normalized])]); - }; - const handleHierarchyChanged = (action) => { setHierarchyAction({ ...action, key: Date.now() }); - if (action.type === 'relink') { - markMilestonesDirty([ - action.sourceMilestoneNumber, - action.targetMilestoneNumber, - action.fromMilestone, - action.toMilestone, - ]); - } else if (action.type === 'unlink') { - markMilestonesDirty([action.sourceMilestoneNumber]); - } else if (action.type === 'error') { - markMilestonesDirty([ - action.sourceMilestoneNumber, - action.targetMilestoneNumber, - ]); - } }; // MilestoneCards apply hierarchyAction in their effects (children run first). @@ -267,24 +240,8 @@ const App = () => { } }; - const handleIssueMilestoneMoved = ({ - fromMilestoneNumber, - toMilestoneNumber, - }) => { - markMilestonesDirty([fromMilestoneNumber, toMilestoneNumber]); - }; - - const handleIssueLabelsChanged = ({ milestoneNumber }) => { - markMilestonesDirty([milestoneNumber]); - }; - - const handleRefreshDirtyMilestones = () => { - if (dirtyMilestoneNumbers.length === 0) return; - setIssueMilestoneRefresh((s) => ({ - key: s.key + 1, - milestoneNumbers: [...dirtyMilestoneNumbers], - })); - setDirtyMilestoneNumbers([]); + const handleRefresh = () => { + setIssueMilestoneRefresh((key) => key + 1); }; const handleLabelChange = () => { @@ -332,8 +289,6 @@ const App = () => { sortOrder={sortOrder} issueMilestoneRefresh={issueMilestoneRefresh} hierarchyAction={hierarchyAction} - onIssueMilestoneMoved={handleIssueMilestoneMoved} - onIssueLabelsChanged={handleIssueLabelsChanged} onMilestoneUpdated={handleMilestoneUpdated} /> ))} @@ -386,14 +341,8 @@ const App = () => {
- , + + )} + {milestone.number !== 0 && milestoneFilter === 'closed' && ( + + + + )} , + , + ]} + > + {actionError && ( + + {actionError} + + )} + {closeCounts.open_issues === 0 && + closeCounts.open_pull_requests === 0 ? ( +

There are no open issues or PRs against this milestone.

+ ) : ( +

+ There are {closeCounts.open_issues} open issue + {closeCounts.open_issues === 1 ? '' : 's'} and{' '} + {closeCounts.open_pull_requests} open PR + {closeCounts.open_pull_requests === 1 ? '' : 's'} against this + milestone. +

+ )} + + Closing this milestone will not close its issues or pull requests. + + + )} ); }; diff --git a/frontend/src/components/ManageMilestones.test.jsx b/frontend/src/components/ManageMilestones.test.jsx new file mode 100644 index 0000000..402f074 --- /dev/null +++ b/frontend/src/components/ManageMilestones.test.jsx @@ -0,0 +1,97 @@ +// Generated-by: openai-code-assist +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import ManageMilestones from './ManageMilestones'; +import * as api from '../services/api'; +import { clearMilestonesCache } from '../utils/milestonesCache'; + +vi.mock('../services/api'); + +describe('ManageMilestones state actions', () => { + const openMilestone = { + number: 6, + title: 'v0.6.0', + description: 'Version 0.6.0', + due_on: null, + state: 'open', + }; + const closedMilestone = { ...openMilestone, state: 'closed' }; + let openResults; + let closedResults; + + beforeEach(() => { + vi.clearAllMocks(); + clearMilestonesCache(); + openResults = [openMilestone]; + closedResults = [closedMilestone]; + api.fetchMilestones.mockImplementation((state = 'open') => + Promise.resolve(state === 'closed' ? closedResults : openResults) + ); + api.fetchMilestoneOpenCounts.mockResolvedValue({ + open_issues: 2, + open_pull_requests: 1, + }); + api.updateMilestoneState.mockResolvedValue({ + ...closedMilestone, + }); + }); + + it('confirms close with open issue and pull-request counts', async () => { + const user = userEvent.setup(); + render( + + ); + + await waitFor(() => expect(screen.getByText('v0.6.0')).toBeInTheDocument()); + await user.click( + screen.getByRole('button', { name: 'Close v0.6.0 milestone' }) + ); + + await waitFor(() => { + expect(api.fetchMilestoneOpenCounts).toHaveBeenCalledWith(6); + expect( + screen.getByText( + 'There are 2 open issues and 1 open PR against this milestone.' + ) + ).toBeInTheDocument(); + }); + expect( + screen.getByText(/will not close its issues or pull requests/i) + ).toBeInTheDocument(); + openResults = []; + await user.click(screen.getByRole('button', { name: 'Close milestone' })); + + await waitFor(() => { + expect(api.updateMilestoneState).toHaveBeenCalledWith(6, 'closed'); + expect(screen.queryByText('v0.6.0')).not.toBeInTheDocument(); + }); + }); + + it('loads closed milestones and can reopen one', async () => { + const user = userEvent.setup(); + render( + + ); + + await waitFor(() => expect(screen.getByText('v0.6.0')).toBeInTheDocument()); + await user.selectOptions( + screen.getByLabelText('Milestone filter'), + 'closed' + ); + + await waitFor(() => { + expect(api.fetchMilestones).toHaveBeenCalledWith('closed'); + expect(screen.getByText('Closed')).toBeInTheDocument(); + }); + closedResults = []; + await user.click( + screen.getByRole('button', { name: 'Reopen v0.6.0 milestone' }) + ); + + await waitFor(() => { + expect(api.updateMilestoneState).toHaveBeenCalledWith(6, 'open'); + expect(screen.queryByText('v0.6.0')).not.toBeInTheDocument(); + }); + }); +}); diff --git a/frontend/src/components/MilestoneCard.jsx b/frontend/src/components/MilestoneCard.jsx index 2f68622..6c2172a 100644 --- a/frontend/src/components/MilestoneCard.jsx +++ b/frontend/src/components/MilestoneCard.jsx @@ -57,9 +57,7 @@ const itemTableHeader = (includeType) => ( const MilestoneCard = ({ milestone, sortOrder = [], - issueMilestoneRefresh = { key: 0, milestoneNumbers: [] }, - onIssueMilestoneMoved, - onIssueLabelsChanged, + issueMilestoneRefresh = 0, hierarchyAction, onMilestoneUpdated, }) => { @@ -197,13 +195,13 @@ const MilestoneCard = ({ }, [sortOrder]); useEffect(() => { - const { key, milestoneNumbers } = issueMilestoneRefresh; - if (key === 0) return; - if (!milestoneNumbers.includes(milestone.number)) return; + // Loaded cards own the visible issue data; unopened cards fetch current + // data when expanded instead of doing work that cannot be displayed yet. + if (issueMilestoneRefresh === 0) return; if (!hasLoadedOnce) return; refetchIssues(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [issueMilestoneRefresh.key]); + }, [issueMilestoneRefresh]); // Apply optimistic hierarchy mutations from Planning DnD / adopt. useEffect(() => { @@ -435,16 +433,7 @@ const MilestoneCard = ({ onDragEndIssue={() => { dnd?.finishDrag(); }} - onMilestoneChange={(detail) => { - onIssueMilestoneMoved?.(detail); - }} - onLabelsChange={(detail) => { - onIssueLabelsChanged?.(detail); - }} onIssueUpdate={updateItemInForest(setIssues)} - onAdoptParentMilestone={(detail) => { - onIssueMilestoneMoved?.(detail); - }} onIssueCreated={handleIssueCreated} onIssueClosed={handleIssueClosed} /> @@ -471,12 +460,6 @@ const MilestoneCard = ({ issue={issue} enableHierarchy={false} columnCount={7} - onMilestoneChange={(detail) => { - onIssueMilestoneMoved?.(detail); - }} - onLabelsChange={(detail) => { - onIssueLabelsChanged?.(detail); - }} onIssueUpdate={updateItemInForest(setPullRequests)} /> ))} diff --git a/frontend/src/components/MilestoneCard.test.jsx b/frontend/src/components/MilestoneCard.test.jsx index 48838f7..61f1ab2 100644 --- a/frontend/src/components/MilestoneCard.test.jsx +++ b/frontend/src/components/MilestoneCard.test.jsx @@ -246,23 +246,16 @@ describe('MilestoneCard', () => { ).not.toBeInTheDocument(); }); - it('refetches issues when issueMilestoneRefresh targets this milestone', async () => { + it('refetches issues when the planning refresh cycle changes', async () => { const user = userEvent.setup(); api.fetchIssues.mockResolvedValue({ issues: [mockIssue], pull_requests: [], }); - const onIssueMilestoneMoved = vi.fn(); - const initialRefresh = { key: 0, milestoneNumbers: [] }; - const { rerender } = await act(async () => render( - + ) ); @@ -275,11 +268,7 @@ describe('MilestoneCard', () => { await act(async () => { rerender( - + ); }); @@ -298,10 +287,7 @@ describe('MilestoneCard', () => { const { rerender } = await act(async () => render( - + ) ); @@ -315,10 +301,7 @@ describe('MilestoneCard', () => { await act(async () => { rerender( - + ); }); diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index a9a6e3e..08b9308 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -27,14 +27,28 @@ const raiseForResponse = async (response, fallback) => { throw new Error(`${fallback}: ${detail}`); }; -export const fetchMilestones = async () => { - const response = await fetch(`${API_BASE}/milestones`); +export const fetchMilestones = async (state = 'open') => { + const query = state === 'open' ? '' : `?state=${encodeURIComponent(state)}`; + const response = await fetch(`${API_BASE}/milestones${query}`); if (!response.ok) { throw new Error(`Failed to fetch milestones: ${response.statusText}`); } return response.json(); }; +// Assisted-by: openai-code-assist +export const fetchMilestoneOpenCounts = async (milestoneNumber) => { + const response = await fetch( + `${API_BASE}/milestones/${milestoneNumber}/open-counts` + ); + if (!response.ok) { + throw new Error( + `Failed to fetch milestone open counts: ${response.statusText}` + ); + } + return response.json(); +}; + export const fetchIssues = async (milestoneNumber, sortOrder = []) => { let url = `${API_BASE}/issues/${milestoneNumber}`; if (sortOrder && sortOrder.length > 0) { @@ -228,6 +242,24 @@ export const updateMilestone = async (milestoneNumber, milestoneData) => { return response.json(); }; +// Assisted-by: openai-code-assist +export const updateMilestoneState = async (milestoneNumber, state) => { + const response = await fetch( + `${API_BASE}/milestones/${milestoneNumber}/state`, + { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ state }), + } + ); + if (!response.ok) { + throw new Error(`Failed to update milestone state: ${response.statusText}`); + } + return response.json(); +}; + export const deleteMilestone = async (milestoneNumber) => { const response = await fetch(`${API_BASE}/milestones/${milestoneNumber}`, { method: 'DELETE', @@ -252,6 +284,21 @@ export const createLabel = async (labelData) => { return response.json(); }; +// Assisted-by: openai-code-assist +export const updateLabel = async (labelName, labelData) => { + const response = await fetch(`${API_BASE}/labels/${labelName}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(labelData), + }); + if (!response.ok) { + throw new Error(`Failed to update label: ${response.statusText}`); + } + return response.json(); +}; + export const deleteLabel = async (labelName) => { const response = await fetch(`${API_BASE}/labels/${labelName}`, { method: 'DELETE', diff --git a/frontend/src/services/api.test.js b/frontend/src/services/api.test.js index b6b1578..1e55200 100644 --- a/frontend/src/services/api.test.js +++ b/frontend/src/services/api.test.js @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { fetchMilestones, + fetchMilestoneOpenCounts, fetchIssues, fetchComments, fetchProject, @@ -23,6 +24,8 @@ import { updateComment, updateIssueBody, updateIssueTitle, + updateLabel, + updateMilestoneState, } from './api'; describe('api', () => { @@ -55,6 +58,80 @@ describe('api', () => { 'Failed to fetch milestones' ); }); + + it('fetches closed milestones with a state filter', async () => { + global.fetch.mockResolvedValue({ + ok: true, + json: async () => [{ number: 1, title: 'Completed' }], + }); + + await fetchMilestones('closed'); + + expect(global.fetch).toHaveBeenCalledWith( + '/api/v1/milestones?state=closed' + ); + }); + }); + + describe('milestone state APIs', () => { + it('fetches open issue and pull-request counts', async () => { + const counts = { open_issues: 2, open_pull_requests: 1 }; + global.fetch.mockResolvedValue({ + ok: true, + json: async () => counts, + }); + + const result = await fetchMilestoneOpenCounts(6); + + expect(result).toEqual(counts); + expect(global.fetch).toHaveBeenCalledWith( + '/api/v1/milestones/6/open-counts' + ); + }); + + it('updates milestone state', async () => { + const milestone = { number: 6, state: 'closed' }; + global.fetch.mockResolvedValue({ + ok: true, + json: async () => milestone, + }); + + const result = await updateMilestoneState(6, 'closed'); + + expect(result).toEqual(milestone); + expect(global.fetch).toHaveBeenCalledWith('/api/v1/milestones/6/state', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ state: 'closed' }), + }); + }); + }); + + describe('label APIs', () => { + it('updates a label', async () => { + const updatedLabel = { id: 1, name: 'defect', color: 'b60205' }; + global.fetch.mockResolvedValue({ + ok: true, + json: async () => updatedLabel, + }); + + const result = await updateLabel('bug', { + name: 'defect', + color: 'b60205', + description: 'Something is broken', + }); + + expect(result).toEqual(updatedLabel); + expect(global.fetch).toHaveBeenCalledWith('/api/v1/labels/bug', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'defect', + color: 'b60205', + description: 'Something is broken', + }), + }); + }); }); describe('fetchIssues', () => { diff --git a/frontend/src/utils/milestones.js b/frontend/src/utils/milestones.js new file mode 100644 index 0000000..72700a2 --- /dev/null +++ b/frontend/src/utils/milestones.js @@ -0,0 +1,35 @@ +// Generated-by: openai-code-assist + +const VERSION_PATTERN = /^v(\d+)\.(\d+)\.(\d+)$/; + +const versionParts = (title) => { + const match = VERSION_PATTERN.exec(title || ''); + return match ? match.slice(1).map(Number) : null; +}; + +// Assisted-by: openai-code-assist +export const compareMilestones = (left, right) => { + const leftIsNoMilestone = left.number === 0; + const rightIsNoMilestone = right.number === 0; + if (leftIsNoMilestone !== rightIsNoMilestone) { + return leftIsNoMilestone ? 1 : -1; + } + + const leftVersion = versionParts(left.title); + const rightVersion = versionParts(right.title); + if (leftVersion && rightVersion) { + for (let index = 0; index < leftVersion.length; index += 1) { + if (leftVersion[index] !== rightVersion[index]) { + return leftVersion[index] - rightVersion[index]; + } + } + return 0; + } + if (leftVersion) return -1; + if (rightVersion) return 1; + + return String(left.title || '').localeCompare(String(right.title || '')); +}; + +export const sortMilestones = (milestones) => + [...milestones].sort(compareMilestones); diff --git a/frontend/src/utils/milestones.test.js b/frontend/src/utils/milestones.test.js new file mode 100644 index 0000000..e99877f --- /dev/null +++ b/frontend/src/utils/milestones.test.js @@ -0,0 +1,19 @@ +// Generated-by: openai-code-assist +import { describe, expect, it } from 'vitest'; +import { sortMilestones } from './milestones'; + +describe('milestone sorting', () => { + it('sorts versions numerically and keeps non-version sections at the end', () => { + const milestones = [ + { number: 9, title: 'v0.9.0' }, + { number: 0, title: 'none' }, + { number: 1, title: 'Backlog' }, + { number: 10, title: 'v0.10.0' }, + { number: 8, title: 'v0.8.1' }, + ]; + + expect( + sortMilestones(milestones).map((milestone) => milestone.title) + ).toEqual(['v0.8.1', 'v0.9.0', 'v0.10.0', 'Backlog', 'none']); + }); +});