From 4911bf023731f197e4a824afc080033e5169fdee Mon Sep 17 00:00:00 2001 From: Saisinare Date: Thu, 22 Oct 2026 09:12:03 +0530 Subject: [PATCH] feat: add projects overview page (#4852) Read-only admin page at /admin/projects listing every project with its author, category, difficulty, moderation status, published date or draft state, step count, comment and view counts, and remake count. Deleted projects are greyed out and not linked. Paginated, 20 per page. ModerationBadge moves out of MapPinsPage so both pages share it. --- .../cypress/src/integration/admin.spec.ts | 10 ++ shared/models/library.ts | 62 ++++++++ src/pages/Admin/AdminSidebar.test.tsx | 8 +- src/pages/Admin/AdminSidebar.tsx | 5 +- src/pages/Admin/MapPins/MapPinsPage.tsx | 15 +- src/pages/Admin/ModerationBadge.tsx | 14 ++ .../Admin/Projects/ProjectsPage.test.tsx | 132 +++++++++++++++++ src/pages/Admin/Projects/ProjectsPage.tsx | 105 ++++++++++++++ src/routes/_.admin.projects.tsx | 31 ++++ src/services/libraryService.server.test.ts | 133 ++++++++++++++++++ src/services/libraryService.server.ts | 44 ++++++ src/test/factories/Library.ts | 21 ++- 12 files changed, 561 insertions(+), 19 deletions(-) create mode 100644 src/pages/Admin/ModerationBadge.tsx create mode 100644 src/pages/Admin/Projects/ProjectsPage.test.tsx create mode 100644 src/pages/Admin/Projects/ProjectsPage.tsx create mode 100644 src/routes/_.admin.projects.tsx create mode 100644 src/services/libraryService.server.test.ts diff --git a/packages/cypress/src/integration/admin.spec.ts b/packages/cypress/src/integration/admin.spec.ts index fd4c440774..afa1cffeb1 100644 --- a/packages/cypress/src/integration/admin.spec.ts +++ b/packages/cypress/src/integration/admin.spec.ts @@ -16,6 +16,16 @@ describe('[Admin]', () => { cy.contains('Overview'); }); + it('[Admin can reach the projects overview from the admin navigation]', () => { + cy.signIn(admin.email, admin.password); + + cy.visit('/admin'); + cy.contains('button', 'Library').click(); + cy.contains('a', 'Projects').click(); + cy.url().should('include', '/admin/projects'); + cy.contains('h1', 'Projects'); + }); + it('[Admin can reach the remakes overview from the admin navigation]', () => { cy.signIn(admin.email, admin.password); diff --git a/shared/models/library.ts b/shared/models/library.ts index 1fe255e6d5..0d64eac8e8 100644 --- a/shared/models/library.ts +++ b/shared/models/library.ts @@ -252,3 +252,65 @@ export type ProjectStepDTO = { images: DBMedia[] | null; videoUrl: string | null; }; + +export type DBAdminProject = Pick< + DBProject, + | 'id' + | 'created_at' + | 'title' + | 'slug' + | 'difficulty_level' + | 'moderation' + | 'is_draft' + | 'published_at' + | 'comment_count' + | 'total_views' + | 'deleted' +> & { + profile: Pick | null; + category: Pick | null; + steps: { count: number }[]; + remakes: { count: number }[]; +}; + +export class AdminProject { + id: number; + title: string; + slug: string; + author: { username: string | null; displayName: string } | null; + category: string | null; + difficultyLevel: DifficultyLevel | null; + moderation: Moderation | null; + isDraft: boolean; + publishedAt: Date | null; + commentCount: number; + totalViews: number; + stepCount: number; + remakeCount: number; + deleted: boolean; + + constructor(obj: AdminProject) { + Object.assign(this, obj); + } + + static fromDB(obj: DBAdminProject) { + return new AdminProject({ + id: obj.id, + title: obj.title, + slug: obj.slug, + author: obj.profile + ? { username: obj.profile.username, displayName: obj.profile.display_name } + : null, + category: obj.category?.name ?? null, + difficultyLevel: obj.difficulty_level, + moderation: obj.moderation, + isDraft: obj.is_draft || false, + publishedAt: obj.published_at ? new Date(obj.published_at) : null, + commentCount: obj.comment_count ?? 0, + totalViews: obj.total_views ?? 0, + stepCount: obj.steps[0]?.count ?? 0, + remakeCount: obj.remakes[0]?.count ?? 0, + deleted: obj.deleted || false, + }); + } +} diff --git a/src/pages/Admin/AdminSidebar.test.tsx b/src/pages/Admin/AdminSidebar.test.tsx index 49bb71d7f5..8d9f796b11 100644 --- a/src/pages/Admin/AdminSidebar.test.tsx +++ b/src/pages/Admin/AdminSidebar.test.tsx @@ -46,10 +46,12 @@ describe('AdminSidebar', () => { renderAt('/admin/remakes'); expect(screen.getByRole('link', { name: 'Remakes' })).toBeInTheDocument(); - expect(screen.queryByRole('link', { name: /Projects/ })).not.toBeInTheDocument(); - expect(screen.getByText('Projects').parentElement).toHaveAttribute('aria-disabled', 'true'); + expect(screen.getByRole('link', { name: 'Projects' })).toHaveAttribute( + 'href', + '/admin/projects', + ); expect(screen.getByRole('button', { name: /Research/ })).toBeDisabled(); - expect(screen.getAllByText('Coming soon')).toHaveLength(2); + expect(screen.getAllByText('Coming soon')).toHaveLength(1); }); it('opens the section containing the current page', () => { diff --git a/src/pages/Admin/AdminSidebar.tsx b/src/pages/Admin/AdminSidebar.tsx index c74a5140c4..0285217895 100644 --- a/src/pages/Admin/AdminSidebar.tsx +++ b/src/pages/Admin/AdminSidebar.tsx @@ -45,7 +45,10 @@ const ADMIN_NAV_ITEMS = [ { label: 'Library', icon: LibraryIcon, - items: [{ label: 'Projects' }, { label: 'Remakes', href: '/admin/remakes' }], + items: [ + { label: 'Projects', href: '/admin/projects' }, + { label: 'Remakes', href: '/admin/remakes' }, + ], }, { label: 'Research', icon: FlaskConicalIcon }, { label: 'Questions', href: '/admin/questions', icon: MessageCircleQuestionMarkIcon }, diff --git a/src/pages/Admin/MapPins/MapPinsPage.tsx b/src/pages/Admin/MapPins/MapPinsPage.tsx index 4af888c1b2..ab80f00e89 100644 --- a/src/pages/Admin/MapPins/MapPinsPage.tsx +++ b/src/pages/Admin/MapPins/MapPinsPage.tsx @@ -1,7 +1,7 @@ import { ExternalLinkIcon } from 'lucide-react'; import { Link } from 'react-router'; import { AdminPagination } from 'src/pages/Admin/AdminPagination'; -import { Badge } from '@/components/ui/badge'; +import { ModerationBadge } from 'src/pages/Admin/ModerationBadge'; import { Table, TableBody, @@ -40,19 +40,6 @@ export interface MapPinsPageProps { totalCount: number; } -function ModerationBadge({ status }: { status: string }) { - const variant = - status === 'accepted' - ? 'success' - : status === 'awaiting-moderation' - ? 'warning' - : status === 'improvements-needed' - ? 'info' - : 'destructive'; - - return {status}; -} - export function MapPinsPage({ mapPins, page, totalPages, totalCount }: MapPinsPageProps) { return (
diff --git a/src/pages/Admin/ModerationBadge.tsx b/src/pages/Admin/ModerationBadge.tsx new file mode 100644 index 0000000000..ba59e4e522 --- /dev/null +++ b/src/pages/Admin/ModerationBadge.tsx @@ -0,0 +1,14 @@ +import { Badge } from '@/components/ui/badge'; + +export function ModerationBadge({ status }: { status: string }) { + const variant = + status === 'accepted' + ? 'success' + : status === 'awaiting-moderation' + ? 'warning' + : status === 'improvements-needed' + ? 'info' + : 'destructive'; + + return {status}; +} diff --git a/src/pages/Admin/Projects/ProjectsPage.test.tsx b/src/pages/Admin/Projects/ProjectsPage.test.tsx new file mode 100644 index 0000000000..f052ab804f --- /dev/null +++ b/src/pages/Admin/Projects/ProjectsPage.test.tsx @@ -0,0 +1,132 @@ +import '@testing-library/jest-dom/vitest'; +import { render, screen, within } from '@testing-library/react'; +import type { AdminProject } from 'oa-shared'; +import { MemoryRouter } from 'react-router'; +import { FactoryAdminProject } from 'src/test/factories/Library'; +import { describe, expect, it } from 'vitest'; +import { ProjectsPage } from './ProjectsPage'; + +const project = FactoryAdminProject({ + title: 'Plastic bench', + slug: 'plastic-bench', + author: { username: 'maker', displayName: 'Maker One' }, + category: 'Furniture', + difficultyLevel: 'very-hard', + moderation: 'awaiting-moderation', + publishedAt: new Date('2026-08-20T10:00:00Z'), + stepCount: 7, + commentCount: 12, + totalViews: 345, + remakeCount: 2, +}); + +const renderPage = (projects: AdminProject[], page = 1, totalPages = 1) => + render( + + + , + ); + +const cellsOf = (title: string) => + within(screen.getByText(title).closest('tr')!).getAllByRole('cell'); + +describe('ProjectsPage', () => { + it('lists each project with its details', () => { + renderPage([project]); + + expect(screen.getByRole('heading', { name: 'Projects' })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Maker One' })).toHaveAttribute('href', '/u/maker'); + expect(cellsOf('Plastic bench').map((cell) => cell.textContent)).toEqual([ + 'Plastic bench', + 'Maker One', + 'Furniture', + 'Very Hard', + 'awaiting-moderation', + '20 Aug 2026', + '7', + '12', + '345', + '2', + ]); + }); + + it('links each project to its live page', () => { + renderPage([project]); + + expect(screen.getByRole('link', { name: 'Plastic bench' })).toHaveAttribute( + 'href', + '/library/plastic-bench', + ); + }); + + it('shows drafts as Draft instead of a published date', () => { + renderPage([FactoryAdminProject({ ...project, isDraft: true, publishedAt: null })]); + + expect(cellsOf('Plastic bench')[5]).toHaveTextContent('Draft'); + }); + + it('greys out a deleted project and does not link to it', () => { + renderPage([FactoryAdminProject({ ...project, deleted: true })]); + + expect(screen.getByText('Plastic bench (marked for deletion)').closest('tr')).toHaveClass( + 'bg-muted', + ); + expect(screen.queryByRole('link', { name: 'Plastic bench' })).not.toBeInTheDocument(); + }); + + it('leaves optional fields empty when a project has none', () => { + renderPage([ + FactoryAdminProject({ + ...project, + category: null, + difficultyLevel: null, + moderation: null, + publishedAt: null, + }), + ]); + + const cells = cellsOf('Plastic bench'); + for (const index of [2, 3, 4, 5]) { + expect(cells[index]).toBeEmptyDOMElement(); + } + }); + + it('keeps an unavailable author visible without a profile link', () => { + renderPage([FactoryAdminProject({ ...project, author: null })]); + + expect(screen.getByText('Author unavailable')).toBeInTheDocument(); + expect(screen.getAllByRole('link')).toHaveLength(1); + }); + + it('renders an author without a username as plain text', () => { + renderPage([FactoryAdminProject({ ...project, author: { displayName: 'Maker One', username: null } })]); + + expect(screen.getByText('Maker One')).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'Maker One' })).not.toBeInTheDocument(); + }); + + it('shows an empty state when there are no projects', () => { + renderPage([]); + + expect(screen.getByText('No projects yet.')).toBeInTheDocument(); + }); + + it('has no create, edit or delete controls', () => { + renderPage([project]); + + expect(screen.queryByRole('button')).not.toBeInTheDocument(); + }); + + it('pages through the projects', () => { + renderPage([project], 2, 3); + + expect(screen.getByText('Page 2 of 3')).toBeInTheDocument(); + expect(screen.getByText('Previous').closest('a')).toHaveAttribute('href', '/?page=1'); + expect(screen.getByText('Next').closest('a')).toHaveAttribute('href', '/?page=3'); + }); +}); diff --git a/src/pages/Admin/Projects/ProjectsPage.tsx b/src/pages/Admin/Projects/ProjectsPage.tsx new file mode 100644 index 0000000000..7a3e425ca2 --- /dev/null +++ b/src/pages/Admin/Projects/ProjectsPage.tsx @@ -0,0 +1,105 @@ +import type { AdminProject } from 'oa-shared'; +import { DifficultyLevelRecord } from 'oa-shared'; +import { Link } from 'react-router'; +import { AdminPagination } from 'src/pages/Admin/AdminPagination'; +import { ModerationBadge } from 'src/pages/Admin/ModerationBadge'; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from '@/components/ui/table'; + +const PUBLISHED_AT_FORMAT = new Intl.DateTimeFormat('en-GB', { + dateStyle: 'medium', + timeZone: 'UTC', +}); + +interface IProps { + projects: AdminProject[]; + page: number; + totalPages: number; + totalCount: number; +} + +export function ProjectsPage({ projects, page, totalPages, totalCount }: IProps) { + return ( +
+
+

Projects

+ Total: {totalCount} +
+ + + + + Title + Author + Category + Difficulty + Moderation + Published + Steps + Comments + Views + Remakes + + + + {projects.length === 0 ? ( + + + No projects yet. + + + ) : ( + projects.map((project) => ( + + + {project.deleted ? ( + `${project.title} (marked for deletion)` + ) : ( + + {project.title} + + )} + + + {!project.author ? ( + Author unavailable + ) : project.author.username ? ( + + {project.author.displayName} + + ) : ( + project.author.displayName + )} + + {project.category} + + {project.difficultyLevel && DifficultyLevelRecord[project.difficultyLevel]} + + + {project.moderation && } + + + {project.isDraft + ? 'Draft' + : project.publishedAt && PUBLISHED_AT_FORMAT.format(project.publishedAt)} + + {project.stepCount} + {project.commentCount} + {project.totalViews} + {project.remakeCount} + + )) + )} + +
+ + +
+ ); +} diff --git a/src/routes/_.admin.projects.tsx b/src/routes/_.admin.projects.tsx new file mode 100644 index 0000000000..24e9ed8ba7 --- /dev/null +++ b/src/routes/_.admin.projects.tsx @@ -0,0 +1,31 @@ +import type { LoaderFunctionArgs } from 'react-router'; +import { useLoaderData } from 'react-router'; +import { ProjectsPage } from 'src/pages/Admin/Projects/ProjectsPage'; +import { createSupabaseServerClient } from 'src/repository/supabase.server'; +import { LibraryServiceServer } from 'src/services/libraryService.server'; + +export const handle = { breadcrumb: 'Projects' }; + +const PAGE_SIZE = 20; + +export async function loader({ request }: LoaderFunctionArgs) { + const url = new URL(request.url); + const page = Math.max(1, Number(url.searchParams.get('page')) || 1); + const { client } = createSupabaseServerClient(request); + + const { projects, totalCount } = await new LibraryServiceServer(client).getAdminPage( + page, + PAGE_SIZE, + ); + const totalPages = Math.ceil(totalCount / PAGE_SIZE) || 1; + + return { projects, page, totalPages, totalCount }; +} + +export default function Index() { + const { projects, page, totalPages, totalCount } = useLoaderData(); + + return ( + + ); +} diff --git a/src/services/libraryService.server.test.ts b/src/services/libraryService.server.test.ts new file mode 100644 index 0000000000..594e4ca790 --- /dev/null +++ b/src/services/libraryService.server.test.ts @@ -0,0 +1,133 @@ +import { createClient } from '@supabase/supabase-js'; +import { LibraryServiceServer } from 'src/services/libraryService.server'; +import { describe, expect, it } from 'vitest'; + +import type { DBAdminProject } from 'oa-shared'; + +const dbAdminProject: DBAdminProject = { + id: 4, + created_at: '2026-08-19T10:00:00Z', + title: 'Plastic bench', + slug: 'plastic-bench', + difficulty_level: 'medium', + moderation: 'accepted', + is_draft: null, + published_at: '2026-08-20T10:00:00Z', + comment_count: 3, + total_views: 120, + deleted: null, + profile: { username: 'owner', display_name: 'Owner' }, + category: { name: 'Furniture' }, + steps: [{ count: 5 }], + remakes: [{ count: 2 }], +}; + +const buildClient = ( + response: { status: number; body: unknown; contentRange?: string } = { + status: 200, + body: [dbAdminProject], + contentRange: '20-20/41', + }, +) => { + const requests: URL[] = []; + const client = createClient('https://supabase.example', 'test-key', { + auth: { persistSession: false, autoRefreshToken: false }, + global: { + fetch: async (input) => { + requests.push(new URL(String(input))); + + return new Response(JSON.stringify(response.body), { + status: response.status, + headers: { + 'Content-Type': 'application/json', + ...(response.contentRange ? { 'Content-Range': response.contentRange } : {}), + }, + }); + }, + }, + }); + + return { client, requests }; +}; + +describe('LibraryServiceServer.getAdminPage', () => { + it('requests one page of projects, newest first, with their counts', async () => { + const { client, requests } = buildClient(); + + await new LibraryServiceServer(client).getAdminPage(2, 20); + + expect(requests).toHaveLength(1); + expect(requests[0].pathname).toBe('/rest/v1/projects'); + expect(requests[0].searchParams.get('order')).toBe('created_at.desc,id.desc'); + expect(requests[0].searchParams.get('offset')).toBe('20'); + expect(requests[0].searchParams.get('limit')).toBe('20'); + expect(requests[0].searchParams.get('select')).toMatch( + /profile:profiles\(username,display_name\)[\s\S]*category:categories\(name\)[\s\S]*steps:project_steps\(count\)[\s\S]*remakes\(count\)/, + ); + }); + + it('maps each row and returns the total count', async () => { + const { client } = buildClient(); + + const { projects, totalCount } = await new LibraryServiceServer(client).getAdminPage(2, 20); + + expect(totalCount).toBe(41); + expect(projects).toHaveLength(1); + expect(projects[0]).toMatchObject({ + id: 4, + title: 'Plastic bench', + slug: 'plastic-bench', + author: { username: 'owner', displayName: 'Owner' }, + category: 'Furniture', + difficultyLevel: 'medium', + moderation: 'accepted', + isDraft: false, + publishedAt: new Date('2026-08-20T10:00:00Z'), + commentCount: 3, + totalViews: 120, + stepCount: 5, + remakeCount: 2, + deleted: false, + }); + }); + + it('keeps projects whose author or category is unavailable', async () => { + const { client } = buildClient({ + status: 200, + body: [{ ...dbAdminProject, profile: null, category: null, steps: [], remakes: [] }], + contentRange: '0-0/1', + }); + + const { projects } = await new LibraryServiceServer(client).getAdminPage(1, 20); + + expect(projects[0]).toMatchObject({ + author: null, + category: null, + stepCount: 0, + remakeCount: 0, + }); + }); + + it('returns an empty page when the page is past the last one', async () => { + const { client } = buildClient({ + status: 416, + body: { code: 'PGRST103', message: 'Requested range not satisfiable' }, + }); + + await expect(new LibraryServiceServer(client).getAdminPage(99, 20)).resolves.toEqual({ + projects: [], + totalCount: 0, + }); + }); + + it('throws when the query fails', async () => { + const { client } = buildClient({ + status: 403, + body: { code: '42501', message: 'permission denied' }, + }); + + await expect(new LibraryServiceServer(client).getAdminPage(1, 20)).rejects.toMatchObject({ + code: '42501', + }); + }); +}); diff --git a/src/services/libraryService.server.ts b/src/services/libraryService.server.ts index 4ef178d6ab..cd8d169a13 100644 --- a/src/services/libraryService.server.ts +++ b/src/services/libraryService.server.ts @@ -1,6 +1,8 @@ import type { SupabaseClient } from '@supabase/supabase-js'; import { + AdminProject, type Database, + type DBAdminProject, type DBProject, type DBProjectStep, Image, @@ -99,6 +101,48 @@ export class LibraryServiceServer { }); } + async getAdminPage(page: number, pageSize: number) { + const from = (page - 1) * pageSize; + const { data, count, error } = await this.client + .from('projects') + .select( + ` + id, + created_at, + title, + slug, + difficulty_level, + moderation, + is_draft, + published_at, + comment_count, + total_views, + deleted, + profile:profiles(username, display_name), + category:categories(name), + steps:project_steps(count), + remakes(count) + `, + { count: 'exact' }, + ) + .order('created_at', { ascending: false }) + .order('id', { ascending: false }) + .range(from, from + pageSize - 1); + + if (error?.code === 'PGRST103') { + return { projects: [], totalCount: 0 }; + } + + if (error) { + throw error; + } + + return { + projects: (data as unknown as DBAdminProject[]).map(AdminProject.fromDB), + totalCount: count ?? 0, + }; + } + getProjectPublicMedia(projectDb: DBProject) { const allImages: Image[] = []; diff --git a/src/test/factories/Library.ts b/src/test/factories/Library.ts index 8d09d40bd9..f2752adadb 100644 --- a/src/test/factories/Library.ts +++ b/src/test/factories/Library.ts @@ -1,5 +1,4 @@ import { faker } from '@faker-js/faker'; - import type { DifficultyLevel, Moderation, @@ -8,6 +7,7 @@ import type { ProjectStep, ProjectStepFormData, } from 'oa-shared'; +import { AdminProject } from 'oa-shared'; export const FactoryProjectFormData = ( overloads: Partial = {}, @@ -170,3 +170,22 @@ export const FactoryLibraryItemDraft = (itemOverloads: Partial = {}): P publishedAt: faker.date.past(), ...itemOverloads, }); + +export const FactoryAdminProject = (overloads: Partial = {}): AdminProject => + new AdminProject({ + id: faker.number.int(), + title: faker.lorem.words(3), + slug: faker.lorem.slug(), + author: { username: faker.internet.username(), displayName: faker.person.fullName() }, + category: faker.lorem.word(), + difficultyLevel: 'easy', + moderation: 'accepted', + isDraft: false, + publishedAt: faker.date.past(), + commentCount: faker.number.int({ max: 100 }), + totalViews: faker.number.int({ max: 10000 }), + stepCount: faker.number.int({ min: 1, max: 20 }), + remakeCount: 0, + deleted: false, + ...overloads, + });