diff --git a/README.md b/README.md index 2cc7385..d5831b6 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Our inital spec, written for the first deliverable, and what we are basing the development on, is outlined in [./docs/inital-plan.md](./docs/initial-plan.md) +Password for admin page access is "guinness" + ## Index - [Prerequisites](#prerequisites) diff --git a/apps/backend/src/schema/schema.ts b/apps/backend/src/schema/schema.ts index 75b68b4..5229d19 100644 --- a/apps/backend/src/schema/schema.ts +++ b/apps/backend/src/schema/schema.ts @@ -808,6 +808,88 @@ builder.mutationType({ }) }, }), + deleteVenue: t.field({ + type: 'Boolean', + description: + 'Permanently delete a venue together with its opening hours, prices and reviews.', + args: { + id: t.arg.string({ required: true }), + }, + resolve: async (_parent, args, context) => { + requireAdmin(context) + + const venue = await prisma.venue.findUnique({ + where: { id: args.id }, + select: { id: true }, + }) + + if (venue === null) { + throw new GraphQLError(`Unknown venue: ${args.id}`, { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + await prisma.$transaction([ + prisma.openingHours.deleteMany({ where: { venueId: args.id } }), + prisma.openingHoursNote.deleteMany({ where: { venueId: args.id } }), + prisma.priceSighting.deleteMany({ where: { venueId: args.id } }), + prisma.review.deleteMany({ where: { venueId: args.id } }), + prisma.venue.delete({ where: { id: args.id } }), + ]) + + return true + }, + }), + deleteReview: t.field({ + type: 'Boolean', + description: 'Permanently delete a review.', + args: { + id: t.arg.string({ required: true }), + }, + resolve: async (_parent, args, context) => { + requireAdmin(context) + + const review = await prisma.review.findUnique({ + where: { id: args.id }, + select: { id: true }, + }) + + if (review === null) { + throw new GraphQLError(`Unknown review: ${args.id}`, { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + await prisma.review.delete({ where: { id: args.id } }) + + return true + }, + }), + deletePriceSighting: t.field({ + type: 'Boolean', + description: 'Permanently delete a price sighting.', + args: { + id: t.arg.string({ required: true }), + }, + resolve: async (_parent, args, context) => { + requireAdmin(context) + + const sighting = await prisma.priceSighting.findUnique({ + where: { id: args.id }, + select: { id: true }, + }) + + if (sighting === null) { + throw new GraphQLError(`Unknown price sighting: ${args.id}`, { + extensions: { code: 'BAD_USER_INPUT' }, + }) + } + + await prisma.priceSighting.delete({ where: { id: args.id } }) + + return true + }, + }), createVenue: t.prismaFieldWithInput({ type: 'Venue', input: { diff --git a/apps/backend/tests/e2e/api.spec.ts b/apps/backend/tests/e2e/api.spec.ts index ff37182..caf0264 100644 --- a/apps/backend/tests/e2e/api.spec.ts +++ b/apps/backend/tests/e2e/api.spec.ts @@ -886,3 +886,228 @@ test('createVenue requires an admin user', async ({ request }) => { expect(response.status(), JSON.stringify(body)).toBe(200) expect(body.errors?.[0]?.message).toBe('Unauthorized') }) + +test('deleteVenue removes the venue and all of its related records', async ({ + request, +}) => { + const suffix = randomUUID() + let cityId: string | undefined + let venueId: string | undefined + + try { + const city = await prisma.city.create({ + data: { + name: `zz delete city ${suffix}`, + centreLat: 59.9139, + centreLon: 10.7522, + }, + }) + cityId = city.id + + const venue = await prisma.venue.create({ + data: { + name: `zz delete venue ${suffix}`, + address: 'Testveien 2', + lat: 59.9139, + lon: 10.7522, + cityId: city.id, + openingHours: { + create: [ + { + days: [Day.MON], + opening: new Date('2000-01-01T12:00:00Z'), + closing: new Date('2000-01-01T20:00:00Z'), + }, + ], + }, + openingHoursNotes: { + create: [{ days: [Day.MON], note: 'Closed in July.' }], + }, + pricesSighted: { + create: [ + { + price: 99, + size: GlassSize.PINT, + limitation: [], + }, + ], + }, + reviews: { + create: [ + { + username: 'playwright', + body: `Delete venue review ${suffix}`, + rating: 4, + }, + ], + }, + }, + }) + venueId = venue.id + + const { deleteVenue } = await adminQuery<{ deleteVenue: boolean }>( + request, + ` + mutation DeleteVenue($id: String!) { + deleteVenue(id: $id) + } + `, + { id: venue.id }, + ) + + expect(deleteVenue).toBe(true) + + const [deletedVenue, openingHours, openingHoursNotes, prices, reviews] = + await Promise.all([ + prisma.venue.findUnique({ where: { id: venue.id } }), + prisma.openingHours.count({ where: { venueId: venue.id } }), + prisma.openingHoursNote.count({ where: { venueId: venue.id } }), + prisma.priceSighting.count({ where: { venueId: venue.id } }), + prisma.review.count({ where: { venueId: venue.id } }), + ]) + + expect(deletedVenue).toBeNull() + expect(openingHours).toBe(0) + expect(openingHoursNotes).toBe(0) + expect(prices).toBe(0) + expect(reviews).toBe(0) + } finally { + if (venueId) { + await prisma.openingHours.deleteMany({ where: { venueId } }) + await prisma.openingHoursNote.deleteMany({ where: { venueId } }) + await prisma.priceSighting.deleteMany({ where: { venueId } }) + await prisma.review.deleteMany({ where: { venueId } }) + await prisma.venue.deleteMany({ where: { id: venueId } }) + } + + if (cityId) { + await prisma.city.deleteMany({ where: { id: cityId } }) + } + } +}) + +test('deleteVenue rejects an unknown venue', async ({ request }) => { + const unknownVenueId = '00000000-0000-0000-0000-000000000000' + const response = await request.post('/', { + headers: { authorization: `Bearer ${adminToken()}` }, + data: { + query: ` + mutation { + deleteVenue(id: "${unknownVenueId}") + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe(`Unknown venue: ${unknownVenueId}`) +}) + +test('deleteReview removes the review', async ({ request }) => { + const { venue } = await query<{ venue: { id: string }[] }>( + request, + ` + query { + venue { + id + } + } + `, + ) + const seededVenue = venue.at(0) + + if (!seededVenue) { + throw new Error('No seeded venue was returned') + } + + const review = await prisma.review.create({ + data: { + venueId: seededVenue.id, + username: 'playwright', + body: `Delete review ${randomUUID()}`, + rating: 3, + }, + }) + + const { deleteReview } = await adminQuery<{ deleteReview: boolean }>( + request, + ` + mutation DeleteReview($id: String!) { + deleteReview(id: $id) + } + `, + { id: review.id }, + ) + + expect(deleteReview).toBe(true) + expect( + await prisma.review.findUnique({ where: { id: review.id } }), + ).toBeNull() +}) + +test('deletePriceSighting removes the price sighting', async ({ request }) => { + const { venue } = await query<{ venue: { id: string }[] }>( + request, + ` + query { + venue { + id + } + } + `, + ) + const seededVenue = venue.at(0) + + if (!seededVenue) { + throw new Error('No seeded venue was returned') + } + + const sighting = await prisma.priceSighting.create({ + data: { + venueId: seededVenue.id, + price: 99, + size: GlassSize.PINT, + limitation: [], + }, + }) + + try { + const { deletePriceSighting } = await adminQuery<{ + deletePriceSighting: boolean + }>( + request, + ` + mutation DeletePriceSighting($id: String!) { + deletePriceSighting(id: $id) + } + `, + { id: sighting.id }, + ) + + expect(deletePriceSighting).toBe(true) + expect( + await prisma.priceSighting.findUnique({ where: { id: sighting.id } }), + ).toBeNull() + } finally { + await prisma.priceSighting.deleteMany({ where: { id: sighting.id } }) + } +}) + +test('delete mutations require an admin user', async ({ request }) => { + const response = await request.post('/', { + data: { + query: ` + mutation { + deleteVenue(id: "00000000-0000-0000-0000-000000000000") + deleteReview(id: "00000000-0000-0000-0000-000000000000") + deletePriceSighting(id: "00000000-0000-0000-0000-000000000000") + } + `, + }, + }) + const body: GraphQLResponse = await response.json() + + expect(response.status(), JSON.stringify(body)).toBe(200) + expect(body.errors?.[0]?.message).toBe('Unauthorized') +}) diff --git a/apps/frontend/src/components/__tests__/AdminLogin.test.tsx b/apps/frontend/src/components/__tests__/AdminLogin.test.tsx new file mode 100644 index 0000000..fdc5986 --- /dev/null +++ b/apps/frontend/src/components/__tests__/AdminLogin.test.tsx @@ -0,0 +1,54 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { AdminLogin } from '../admin/AdminLogin' +import { isAdminAuthenticated } from '#/lib/admin-auth' + +describe('AdminLogin', () => { + beforeEach(() => { + window.sessionStorage.clear() + }) + + it('shows a secret-password field', () => { + render( {}} />) + + expect( + screen.getByRole('heading', { name: 'Admin access' }), + ).toBeInTheDocument() + expect(screen.getByLabelText('Secret password')).toBeInTheDocument() + expect( + screen.getByPlaceholderText('Enter the secret password'), + ).toBeInTheDocument() + }) + + it('rejects an incorrect password', async () => { + const user = userEvent.setup() + const onAuthenticated = vi.fn() + + render() + + await user.type(screen.getByLabelText('Secret password'), 'stout') + await user.click(screen.getByRole('button', { name: 'Enter admin' })) + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Incorrect password.', + ) + expect(onAuthenticated).not.toHaveBeenCalled() + expect(isAdminAuthenticated()).toBe(false) + expect(screen.getByLabelText('Secret password')).toHaveValue('') + }) + + it('authenticates with guinness and persists the session', async () => { + const user = userEvent.setup() + const onAuthenticated = vi.fn() + + render() + + await user.type(screen.getByLabelText('Secret password'), 'guinness') + await user.click(screen.getByRole('button', { name: 'Enter admin' })) + + expect(onAuthenticated).toHaveBeenCalledOnce() + expect(isAdminAuthenticated()).toBe(true) + }) +}) diff --git a/apps/frontend/src/components/__tests__/DeleteReviewsPanel.test.tsx b/apps/frontend/src/components/__tests__/DeleteReviewsPanel.test.tsx new file mode 100644 index 0000000..2b537c9 --- /dev/null +++ b/apps/frontend/src/components/__tests__/DeleteReviewsPanel.test.tsx @@ -0,0 +1,92 @@ +import { screen, waitFor, within } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { graphqlFetch } from '#/graphql/client' +import { DELETE_REVIEW } from '#/graphql/reviews' +import { makeReview, makeVenue } from '#/test/fixtures' +import { renderWithProviders } from '#/test/render' +import { DeleteReviewsPanel } from '../admin/DeleteReviewsPanel' + +vi.mock('#/graphql/client', () => ({ + graphqlFetch: vi.fn(), +})) + +const mockGraphqlFetch = vi.mocked(graphqlFetch) + +const ALPHA = makeVenue({ + id: 'venue-alpha', + name: 'Alpha Pub', + reviews: [makeReview({ id: 'review-alpha', body: 'Lovely quiet pub.' })], +}) + +const BETA = makeVenue({ + id: 'venue-beta', + name: 'Beta Bar', + reviews: [makeReview({ id: 'review-beta', body: 'Great late-night spot.' })], +}) + +describe('DeleteReviewsPanel', () => { + beforeEach(() => { + mockGraphqlFetch.mockReset() + }) + + it('filters reviews by venue', async () => { + const { user } = renderWithProviders( + , + ) + + expect(await screen.findByText('Lovely quiet pub.')).toBeInTheDocument() + expect(screen.getByText('Great late-night spot.')).toBeInTheDocument() + + await user.selectOptions( + await screen.findByLabelText('Filter by venue'), + 'venue-beta', + ) + + expect(screen.queryByText('Lovely quiet pub.')).not.toBeInTheDocument() + expect(screen.getByText('Great late-night spot.')).toBeInTheDocument() + expect(screen.getByText('1 review')).toBeInTheDocument() + }) + + it('requires confirmation before deleting a review', async () => { + mockGraphqlFetch.mockResolvedValue({ deleteReview: true }) + + const { user, queryClient } = renderWithProviders( + , + ) + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + + await user.selectOptions( + await screen.findByLabelText('Filter by venue'), + 'venue-beta', + ) + await user.click(await screen.findByRole('button', { name: 'Delete' })) + + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Delete review?') + expect(dialog).toHaveTextContent('will be permanently deleted') + expect(mockGraphqlFetch).not.toHaveBeenCalled() + + await user.click( + within(dialog).getByRole('button', { name: 'Delete review' }), + ) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith( + DELETE_REVIEW, + { id: 'review-beta' }, + expect.any(String), + ) + }) + + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) + }) + + it('shows an empty state when there are no reviews', async () => { + renderWithProviders() + + expect( + await screen.findByText('There are no reviews to delete.'), + ).toBeInTheDocument() + }) +}) diff --git a/apps/frontend/src/components/__tests__/ManagePricesDialog.test.tsx b/apps/frontend/src/components/__tests__/ManagePricesDialog.test.tsx new file mode 100644 index 0000000..f87bfb6 --- /dev/null +++ b/apps/frontend/src/components/__tests__/ManagePricesDialog.test.tsx @@ -0,0 +1,101 @@ +import { screen, waitFor, within } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { graphqlFetch } from '#/graphql/client' +import { DELETE_PRICE_SIGHTING } from '#/graphql/price-sightings' +import { makeVenue, makeVenuePriceSighting } from '#/test/fixtures' +import { renderWithProviders } from '#/test/render' +import { ManagePricesDialog } from '../admin/ManagePricesDialog' + +vi.mock('#/graphql/client', () => ({ + graphqlFetch: vi.fn(), +})) + +vi.mock('#/lib/use-user-time-zone', () => ({ + useUserTimeZone: () => 'UTC', +})) + +const mockGraphqlFetch = vi.mocked(graphqlFetch) + +const VENUE = makeVenue({ + pricesSighted: [ + makeVenuePriceSighting({ + id: 'price-1', + price: 89, + timeSighted: '2026-10-01T12:00:00.000Z', + }), + makeVenuePriceSighting({ + id: 'price-2', + price: 99, + timeSighted: '2026-09-01T12:00:00.000Z', + }), + ], +}) + +describe('ManagePricesDialog', () => { + beforeEach(() => { + mockGraphqlFetch.mockReset() + }) + + it('lists price sightings and deletes a confirmed sighting', async () => { + mockGraphqlFetch.mockResolvedValue({ deletePriceSighting: true }) + + const { user, queryClient } = renderWithProviders( + , + ) + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + + await user.click( + await screen.findByRole('button', { name: 'Manage prices' }), + ) + + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Manage price sightings') + expect(within(dialog).getByText('NOK 89 · 500 ml')).toBeInTheDocument() + expect(within(dialog).getByText('NOK 99 · 500 ml')).toBeInTheDocument() + + const sighting = within(dialog).getByText('NOK 89 · 500 ml').closest('li') + + if (!sighting) throw new Error('Price sighting row was not found') + + await user.click(within(sighting).getByRole('button', { name: 'Delete' })) + + const confirmation = await screen.findByRole('dialog', { + name: 'Delete price sighting?', + }) + await user.click( + within(confirmation).getByRole('button', { name: 'Delete price' }), + ) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith( + DELETE_PRICE_SIGHTING, + { id: 'price-1' }, + expect.any(String), + ) + }) + + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) + await waitFor(() => { + expect( + screen.queryByRole('dialog', { name: 'Delete price sighting?' }), + ).not.toBeInTheDocument() + }) + }) + + it('shows an empty state when the venue has no price sightings', async () => { + const { user } = renderWithProviders( + , + ) + + await user.click( + await screen.findByRole('button', { name: 'Manage prices' }), + ) + + expect( + await screen.findByText( + 'No price sightings have been reported for this venue.', + ), + ).toBeInTheDocument() + }) +}) diff --git a/apps/frontend/src/components/__tests__/VenueTable.test.tsx b/apps/frontend/src/components/__tests__/VenueTable.test.tsx index 9dd4d24..9a46b02 100644 --- a/apps/frontend/src/components/__tests__/VenueTable.test.tsx +++ b/apps/frontend/src/components/__tests__/VenueTable.test.tsx @@ -1,11 +1,23 @@ -import { screen, within } from '@testing-library/react' -import { describe, expect, it } from 'vitest' +import { screen, waitFor, within } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { graphqlFetch } from '#/graphql/client' +import { DELETE_VENUE } from '#/graphql/venues' import { makeReview, makeVenue } from '#/test/fixtures' import { renderWithProviders } from '#/test/render' import { VenueTable } from '../admin/VenueTable' +vi.mock('#/graphql/client', () => ({ + graphqlFetch: vi.fn(), +})) + +const mockGraphqlFetch = vi.mocked(graphqlFetch) + describe('VenueTable', () => { + beforeEach(() => { + mockGraphqlFetch.mockReset() + }) + it('lists venue details, coordinates, hours, price and review count', async () => { renderWithProviders( { expect(within(table).getByText('Elgeseter gate 1')).toBeInTheDocument() expect(within(table).getByText('63.42280, 10.39570')).toBeInTheDocument() expect(within(table).getByText(/Weekdays/)).toBeInTheDocument() - expect(within(table).getByText('NOK 89 · 500 ml')).toBeInTheDocument() + expect( + within(table).getAllByText('NOK 89 · 500 ml').length, + ).toBeGreaterThan(0) expect(within(table).getByText('1')).toBeInTheDocument() }) + it('deletes a venue after confirmation', async () => { + mockGraphqlFetch.mockResolvedValue({ deleteVenue: true }) + + const { user, queryClient } = renderWithProviders( + , + ) + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + + await user.click(await screen.findByRole('button', { name: 'Delete' })) + + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Delete venue?') + expect(dialog).toHaveTextContent( + 'all of its opening hours, price sightings and reviews', + ) + expect(mockGraphqlFetch).not.toHaveBeenCalled() + + await user.click( + within(dialog).getByRole('button', { name: 'Delete venue' }), + ) + + await waitFor(() => { + expect(mockGraphqlFetch).toHaveBeenCalledWith( + DELETE_VENUE, + { id: 'venue-1' }, + expect.any(String), + ) + }) + + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['venues'] }) + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + }) + }) + + it('cancels venue deletion without sending a request', async () => { + const { user } = renderWithProviders() + + await user.click(await screen.findByRole('button', { name: 'Delete' })) + + const dialog = await screen.findByRole('dialog') + await user.click(within(dialog).getByRole('button', { name: 'Cancel' })) + + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + }) + expect(mockGraphqlFetch).not.toHaveBeenCalled() + }) + it('shows an empty state when there are no venues', async () => { renderWithProviders() diff --git a/apps/frontend/src/components/admin/AddVenueDialog.tsx b/apps/frontend/src/components/admin/AddVenueDialog.tsx index 8eb484a..a3c5f27 100644 --- a/apps/frontend/src/components/admin/AddVenueDialog.tsx +++ b/apps/frontend/src/components/admin/AddVenueDialog.tsx @@ -8,6 +8,7 @@ import { Dialog, useDialog } from '#/components/ui/Dialog' import { FormField, inputClassName } from '#/components/ui/FormField' import { graphqlFetch } from '#/graphql/client' import { CREATE_VENUE } from '#/graphql/venues' +import { ADMIN_TOKEN } from '#/lib/admin-token' import { timeToIso } from '#/lib/opening-hours' import type { City } from '#/types/city' import { OpeningHoursEditor } from './OpeningHoursEditor' @@ -33,11 +34,6 @@ interface AddVenueDialogProps { onCreated?: () => void } -// Token lasts till 2033 for development. In production this would come from an -// auth provider. -const ADMIN_TOKEN = - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIwMWExZmZlZC1hNDY3LTc3MDQtOTM0MS1jM2ZjZjNiMTk5YWMiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MjAwMDAwMDAwMH0.EohmXYCm3GANzUwpGetPEbEP8CRt5oF6Roc-4Y4ZLQk' - export function AddVenueDialog({ onCreated }: AddVenueDialogProps) { return ( void +} + +export function AdminLogin({ onAuthenticated }: AdminLoginProps) { + const passwordId = useId() + const passwordRef = useRef(null) + const [password, setPassword] = useState('') + const [error, setError] = useState(null) + + function handleSubmit(event: FormEvent) { + event.preventDefault() + + if (signInAdmin(password)) { + setError(null) + onAuthenticated() + return + } + + setPassword('') + setError('Incorrect password.') + passwordRef.current?.focus() + } + + return ( +
+
+

Admin access

+

+ Enter the secret password to manage venues, prices and reviews. +

+ +
+ + setPassword(event.target.value)} + autoComplete="current-password" + autoFocus + required + placeholder="Enter the secret password" + className={inputClassName} + /> + + + {error && ( +

+ {error} +

+ )} + +
+ +
+
+
+
+ ) +} diff --git a/apps/frontend/src/components/admin/DeleteReviewsPanel.tsx b/apps/frontend/src/components/admin/DeleteReviewsPanel.tsx new file mode 100644 index 0000000..b88b789 --- /dev/null +++ b/apps/frontend/src/components/admin/DeleteReviewsPanel.tsx @@ -0,0 +1,260 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { useId, useMemo, useState } from 'react' + +import { Button } from '#/components/ui/Button' +import { ConfirmDialog } from '#/components/ui/ConfirmDialog' +import { FormField, inputClassName } from '#/components/ui/FormField' +import { graphqlFetch } from '#/graphql/client' +import { DELETE_REVIEW } from '#/graphql/reviews' +import { ADMIN_TOKEN } from '#/lib/admin-token' +import type { VenueReview, venue } from '#/types/venue' + +interface DeleteReviewsPanelProps { + venues: venue[] +} + +interface ReviewRow { + review: VenueReview + venueId: string + venueName: string + cityName: string +} + +function formatReviewDate(iso: string) { + const date = new Date(iso) + + if (Number.isNaN(date.getTime())) return '—' + + return date.toLocaleDateString('en-GB', { + year: 'numeric', + month: 'short', + day: 'numeric', + }) +} + +export function DeleteReviewsPanel({ venues }: DeleteReviewsPanelProps) { + const [venueFilter, setVenueFilter] = useState('') + const [reviewToDelete, setReviewToDelete] = useState(null) + const filterId = useId() + const queryClient = useQueryClient() + + const rows = useMemo( + () => + venues + .flatMap((current) => + current.reviews.map((review) => ({ + review, + venueId: current.id, + venueName: current.name, + cityName: current.city.name, + })), + ) + .sort((a, b) => + b.review.timeCreated.localeCompare(a.review.timeCreated), + ), + [venues], + ) + + const filteredRows = + venueFilter === '' + ? rows + : rows.filter((row) => row.venueId === venueFilter) + + const { mutate, reset, isPending, isError, error } = useMutation({ + mutationFn: (id: string) => + graphqlFetch<{ deleteReview: boolean }>( + DELETE_REVIEW, + { id }, + ADMIN_TOKEN, + ), + onSuccess: () => { + setReviewToDelete(null) + void queryClient.invalidateQueries({ queryKey: ['venues'] }) + void queryClient.invalidateQueries({ queryKey: ['nearbyVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['cityVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['search'] }) + }, + }) + + function openConfirmation(row: ReviewRow) { + reset() + setReviewToDelete(row) + } + + function closeConfirmation() { + if (isPending) return + + reset() + setReviewToDelete(null) + } + + function confirmDelete() { + if (reviewToDelete !== null) mutate(reviewToDelete.review.id) + } + + if (rows.length === 0) { + return ( +

+ There are no reviews to delete. +

+ ) + } + + const errorMessage = isError + ? `Could not delete the review${error instanceof Error ? `: ${error.message}` : '.'}` + : null + + return ( +
+ + + + +

+ {filteredRows.length} {filteredRows.length === 1 ? 'review' : 'reviews'} +

+ +
+ + + + + + + + + + + + + + + + + + + + + {filteredRows.length === 0 && ( + + + + )} + + {filteredRows.map((row) => { + const { review, venueName, cityName } = row + const submitted = formatReviewDate(review.timeCreated) + + return ( + + + + + + + + + ) + })} + +
+ Venue + + Reviewer + + Rating + + Review + + Submitted + + Actions +
+ No reviews have been added for this venue. +
+ + {venueName} + + {' '} + · {cityName} + + + + + {review.username} + + + {review.rating} / 5 + + + {review.body} + + + + {submitted} + + + +
+
+ + {reviewToDelete && ( + + The review by {reviewToDelete.review.username}{' '} + for “{reviewToDelete.venueName}” will be + permanently deleted. This cannot be undone. + + } + confirmLabel="Delete review" + pendingLabel="Deleting…" + pending={isPending} + error={errorMessage} + onConfirm={confirmDelete} + onClose={closeConfirmation} + /> + )} +
+ ) +} diff --git a/apps/frontend/src/components/admin/ManagePricesDialog.tsx b/apps/frontend/src/components/admin/ManagePricesDialog.tsx new file mode 100644 index 0000000..8afda32 --- /dev/null +++ b/apps/frontend/src/components/admin/ManagePricesDialog.tsx @@ -0,0 +1,155 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { useState } from 'react' + +import { Button } from '#/components/ui/Button' +import { ConfirmDialog } from '#/components/ui/ConfirmDialog' +import { Dialog, useDialog } from '#/components/ui/Dialog' +import { graphqlFetch } from '#/graphql/client' +import { DELETE_PRICE_SIGHTING } from '#/graphql/price-sightings' +import { ADMIN_TOKEN } from '#/lib/admin-token' +import { formatPrice, formatPriceLimitation } from '#/lib/format-price' +import { useUserTimeZone } from '#/lib/use-user-time-zone' +import type { VenuePriceSighting, venue } from '#/types/venue' + +interface ManagePricesDialogProps { + venue: venue +} + +function formatSightedDate(iso: string) { + const date = new Date(iso) + + if (Number.isNaN(date.getTime())) return '—' + + return date.toLocaleDateString('en-GB', { + year: 'numeric', + month: 'short', + day: 'numeric', + }) +} + +export function ManagePricesDialog({ venue }: ManagePricesDialogProps) { + return ( + Manage prices} + title="Manage price sightings" + description={`View and remove prices reported for ${venue.name}.`} + > + + + ) +} + +function ManagePricesContent({ venue }: ManagePricesDialogProps) { + const { close } = useDialog() + const [sightingToDelete, setSightingToDelete] = + useState(null) + const timeZone = useUserTimeZone() + const queryClient = useQueryClient() + + const prices = [...(venue.pricesSighted ?? [])].sort((a, b) => + b.timeSighted.localeCompare(a.timeSighted), + ) + + const { mutate, reset, isPending, isError, error } = useMutation({ + mutationFn: (id: string) => + graphqlFetch<{ deletePriceSighting: boolean }>( + DELETE_PRICE_SIGHTING, + { id }, + ADMIN_TOKEN, + ), + onSuccess: () => { + setSightingToDelete(null) + void queryClient.invalidateQueries({ queryKey: ['venues'] }) + void queryClient.invalidateQueries({ queryKey: ['nearbyVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['cityVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['search'] }) + }, + }) + + function openConfirmation(sighting: VenuePriceSighting) { + reset() + setSightingToDelete(sighting) + } + + function closeConfirmation() { + if (isPending) return + + reset() + setSightingToDelete(null) + } + + function confirmDelete() { + if (sightingToDelete?.id) mutate(sightingToDelete.id) + } + + const errorMessage = isError + ? `Could not delete the price sighting${error instanceof Error ? `: ${error.message}` : '.'}` + : null + + return ( +
+ {prices.length === 0 ? ( +

+ No price sightings have been reported for this venue. +

+ ) : ( +
    + {prices.map((sighting, index) => { + const limitation = formatPriceLimitation(sighting, timeZone) + const details = limitation + ? `${limitation} · Reported ${formatSightedDate(sighting.timeSighted)}` + : `Reported ${formatSightedDate(sighting.timeSighted)}` + + return ( +
  • +
    +

    {formatPrice(sighting)}

    +

    {details}

    +
    + +
  • + ) + })} +
+ )} + +
+ +
+ + {sightingToDelete && ( + + The {formatPrice(sightingToDelete)} price + sighting will be permanently deleted. This cannot be undone. + + } + confirmLabel="Delete price" + pendingLabel="Deleting…" + pending={isPending} + error={errorMessage} + onConfirm={confirmDelete} + onClose={closeConfirmation} + /> + )} +
+ ) +} diff --git a/apps/frontend/src/components/admin/VenueTable.tsx b/apps/frontend/src/components/admin/VenueTable.tsx index 05e47a6..ca16c5e 100644 --- a/apps/frontend/src/components/admin/VenueTable.tsx +++ b/apps/frontend/src/components/admin/VenueTable.tsx @@ -1,5 +1,13 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' import { Link } from '@tanstack/react-router' +import { useState } from 'react' +import { ManagePricesDialog } from '#/components/admin/ManagePricesDialog' +import { Button } from '#/components/ui/Button' +import { ConfirmDialog } from '#/components/ui/ConfirmDialog' +import { graphqlFetch } from '#/graphql/client' +import { DELETE_VENUE } from '#/graphql/venues' +import { ADMIN_TOKEN } from '#/lib/admin-token' import { formatOpeningHours } from '#/lib/format-opening-hours' import { formatPrice } from '#/lib/format-price' import type { venue } from '#/types/venue' @@ -14,6 +22,37 @@ function latestRegularPrice(current: venue) { } export function VenueTable({ venues }: { venues: venue[] }) { + const [venueToDelete, setVenueToDelete] = useState(null) + const queryClient = useQueryClient() + + const { mutate, reset, isPending, isError, error } = useMutation({ + mutationFn: (id: string) => + graphqlFetch<{ deleteVenue: boolean }>(DELETE_VENUE, { id }, ADMIN_TOKEN), + onSuccess: () => { + setVenueToDelete(null) + void queryClient.invalidateQueries({ queryKey: ['venues'] }) + void queryClient.invalidateQueries({ queryKey: ['nearbyVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['cityVenues'] }) + void queryClient.invalidateQueries({ queryKey: ['search'] }) + }, + }) + + function openConfirmation(current: venue) { + reset() + setVenueToDelete(current) + } + + function closeConfirmation() { + if (isPending) return + + reset() + setVenueToDelete(null) + } + + function confirmDelete() { + if (venueToDelete !== null) mutate(venueToDelete.id) + } + if (venues.length === 0) { return (

@@ -22,78 +61,124 @@ export function VenueTable({ venues }: { venues: venue[] }) { ) } + const errorMessage = isError + ? `Could not delete the venue${error instanceof Error ? `: ${error.message}` : '.'}` + : null + return ( -

- - - - - - - - - - - - - - {venues.map((current) => { - const latestPrice = latestRegularPrice(current) + <> +
+
- Venue - - City - - Address - - Coordinates - - Opening hours - - Latest price - - Reviews -
+ + + + + + + + + + + + + + {venues.map((current) => { + const latestPrice = latestRegularPrice(current) - return ( - - + - - - - - - - - ) - })} - -
+ Actions + + Venue + + City + + Address + + Coordinates + + Opening hours + + Latest price + + Reviews +
- + +
+ + +
+
- {current.name} - - {current.city.name} - {current.address} - - {current.lat.toFixed(5)}, {current.lon.toFixed(5)} - - {current.openingHours.length > 0 - ? formatOpeningHours(current.openingHours) - : '—'} - - {latestPrice ? formatPrice(latestPrice) : '—'} - - {current.reviews.length} -
-
+ + {current.name} + + + + {current.city.name} + + + {current.address} + + + {current.lat.toFixed(5)}, {current.lon.toFixed(5)} + + + {current.openingHours.length > 0 + ? formatOpeningHours(current.openingHours) + : '—'} + + + {latestPrice ? formatPrice(latestPrice) : '—'} + + + {current.reviews.length} + + + ) + })} + + + + + {venueToDelete && ( + + “{venueToDelete.name}” and all of its opening + hours, price sightings and reviews will be permanently deleted. + This cannot be undone. + + } + confirmLabel="Delete venue" + pendingLabel="Deleting…" + pending={isPending} + error={errorMessage} + onConfirm={confirmDelete} + onClose={closeConfirmation} + /> + )} + ) } diff --git a/apps/frontend/src/components/ui/Button.tsx b/apps/frontend/src/components/ui/Button.tsx index 248376f..d1ceddb 100644 --- a/apps/frontend/src/components/ui/Button.tsx +++ b/apps/frontend/src/components/ui/Button.tsx @@ -6,8 +6,7 @@ const VARIANTS = { secondary: 'bg-(--chip-bg) text-(--sea-ink) hover:-translate-y-0.5 hover:bg-(--link-bg-hover)', ghost: 'text-(--sea-ink-soft) hover:bg-(--chip-bg) hover:text-(--sea-ink)', - danger: - 'border border-red-500/40 bg-red-500/10 text-(--sea-ink) hover:bg-red-500/20', + danger: 'bg-red-500/10 text-(--sea-ink) hover:bg-red-500/20', } as const export type ButtonVariant = keyof typeof VARIANTS diff --git a/apps/frontend/src/components/ui/ConfirmDialog.tsx b/apps/frontend/src/components/ui/ConfirmDialog.tsx new file mode 100644 index 0000000..c4bb470 --- /dev/null +++ b/apps/frontend/src/components/ui/ConfirmDialog.tsx @@ -0,0 +1,100 @@ +import { useEffect, useId, useRef } from 'react' +import type { ReactNode } from 'react' + +import { Button } from './Button' + +interface ConfirmDialogProps { + open: boolean + title: string + description: ReactNode + confirmLabel: string + pendingLabel: string + pending?: boolean + error?: string | null + onConfirm: () => void + onClose: () => void +} + +export function ConfirmDialog({ + open, + title, + description, + confirmLabel, + pendingLabel, + pending = false, + error = null, + onConfirm, + onClose, +}: ConfirmDialogProps) { + const dialogRef = useRef(null) + const titleId = useId() + const descriptionId = useId() + + useEffect(() => { + const dialog = dialogRef.current + + if (dialog === null) return + + if (open && !dialog.open) { + dialog.showModal() + } else if (!open && dialog.open) { + dialog.close() + } + }, [open]) + + useEffect(() => { + const dialog = dialogRef.current + + if (dialog === null) return + + const handleClose = () => onClose() + + dialog.addEventListener('close', handleClose) + + return () => dialog.removeEventListener('close', handleClose) + }, [onClose]) + + return ( + { + if (pending) event.preventDefault() + }} + onClick={(event) => { + if (event.target === dialogRef.current && !pending) { + dialogRef.current.close() + } + }} + className="m-auto max-h-[calc(100dvh-2rem)] w-[min(30rem,calc(100vw-2rem))] overflow-y-auto rounded-2xl bg-(--surface-strong) p-0 text-(--sea-ink) shadow-2xl backdrop:bg-black/50 backdrop:backdrop-blur-sm" + > +
+

+ {title} +

+
+ {description} +
+ + {error && ( +

+ {error} +

+ )} + +
+ + +
+
+
+ ) +} diff --git a/apps/frontend/src/graphql/price-sightings.ts b/apps/frontend/src/graphql/price-sightings.ts index 230f381..5c0b16b 100644 --- a/apps/frontend/src/graphql/price-sightings.ts +++ b/apps/frontend/src/graphql/price-sightings.ts @@ -1,3 +1,9 @@ +export const DELETE_PRICE_SIGHTING = ` + mutation DeletePriceSighting($id: String!) { + deletePriceSighting(id: $id) + } +` + export const CREATE_PRICE_SIGHTING = ` mutation CreatePriceSighting($input: MutationCreatePriceSightingInput!) { createPriceSighting(input: $input) { diff --git a/apps/frontend/src/graphql/reviews.ts b/apps/frontend/src/graphql/reviews.ts index 03fc4ae..ba28a8e 100644 --- a/apps/frontend/src/graphql/reviews.ts +++ b/apps/frontend/src/graphql/reviews.ts @@ -1,3 +1,9 @@ +export const DELETE_REVIEW = ` + mutation DeleteReview($id: String!) { + deleteReview(id: $id) + } +` + export const CREATE_REVIEW = ` mutation CreateReview($input: MutationCreateReviewInput!) { createReview(input: $input) { diff --git a/apps/frontend/src/graphql/venues.ts b/apps/frontend/src/graphql/venues.ts index 9d8389e..5b97628 100644 --- a/apps/frontend/src/graphql/venues.ts +++ b/apps/frontend/src/graphql/venues.ts @@ -27,6 +27,12 @@ export const CREATE_VENUE = ` } ` +export const DELETE_VENUE = ` + mutation DeleteVenue($id: String!) { + deleteVenue(id: $id) + } +` + export const GET_VENUE = ` query GetVenues { venue { @@ -51,6 +57,7 @@ export const GET_VENUE = ` note } pricesSighted { + id price size sizeMl @@ -119,6 +126,7 @@ export const GET_CITY_VENUES = ` closing } pricesSighted { + id price size sizeMl diff --git a/apps/frontend/src/lib/admin-auth.ts b/apps/frontend/src/lib/admin-auth.ts new file mode 100644 index 0000000..00f6267 --- /dev/null +++ b/apps/frontend/src/lib/admin-auth.ts @@ -0,0 +1,32 @@ +const ADMIN_AUTH_STORAGE_KEY = 'g-spotter:admin-authenticated' +const ADMIN_PASSWORD = 'guinness' + +export function isAdminAuthenticated() { + if (typeof window === 'undefined') return false + + try { + return window.sessionStorage.getItem(ADMIN_AUTH_STORAGE_KEY) === 'true' + } catch { + return false + } +} + +export function signInAdmin(password: string) { + if (password !== ADMIN_PASSWORD) return false + + try { + window.sessionStorage.setItem(ADMIN_AUTH_STORAGE_KEY, 'true') + } catch { + // Authentication still succeeds for this page view if storage is blocked. + } + + return true +} + +export function signOutAdmin() { + try { + window.sessionStorage.removeItem(ADMIN_AUTH_STORAGE_KEY) + } catch { + // Nothing to clear when storage is blocked. + } +} diff --git a/apps/frontend/src/lib/admin-token.ts b/apps/frontend/src/lib/admin-token.ts new file mode 100644 index 0000000..9724909 --- /dev/null +++ b/apps/frontend/src/lib/admin-token.ts @@ -0,0 +1,4 @@ +// Token lasts till 2033 for development. In production this would come from an +// auth provider. +export const ADMIN_TOKEN = + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIwMWExZmZlZC1hNDY3LTc3MDQtOTM0MS1jM2ZjZjNiMTk5YWMiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MjAwMDAwMDAwMH0.EohmXYCm3GANzUwpGetPEbEP8CRt5oF6Roc-4Y4ZLQk' diff --git a/apps/frontend/src/routes/admin.tsx b/apps/frontend/src/routes/admin.tsx index 1ae2625..2cf347e 100644 --- a/apps/frontend/src/routes/admin.tsx +++ b/apps/frontend/src/routes/admin.tsx @@ -1,52 +1,172 @@ import { useQuery } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' +import { useEffect, useRef, useState } from 'react' +import type { KeyboardEvent } from 'react' +import { AdminLogin } from '#/components/admin/AdminLogin' import { AddVenueDialog } from '#/components/admin/AddVenueDialog' +import { DeleteReviewsPanel } from '#/components/admin/DeleteReviewsPanel' import { VenueTable } from '#/components/admin/VenueTable' +import { Button } from '#/components/ui/Button' import { venuesQueryOptions } from '#/graphql/venues' +import { isAdminAuthenticated, signOutAdmin } from '#/lib/admin-auth' export const Route = createFileRoute('/admin')({ - loader: ({ context }) => - context.queryClient.prefetchQuery(venuesQueryOptions), component: AdminPage, }) +const TABS = [ + { id: 'venues', label: 'Venues' }, + { id: 'delete-reviews', label: 'Reviews' }, +] as const + +type AdminTab = (typeof TABS)[number]['id'] + function AdminPage() { + const [isAuthenticated, setIsAuthenticated] = useState(null) + + useEffect(() => { + setIsAuthenticated(isAdminAuthenticated()) + }, []) + + if (isAuthenticated === null) { + return ( +
+

+ Checking access… +

+
+ ) + } + + if (!isAuthenticated) { + return setIsAuthenticated(true)} /> + } + + return ( + { + signOutAdmin() + setIsAuthenticated(false) + }} + /> + ) +} + +function AdminDashboard({ onSignOut }: { onSignOut: () => void }) { const { data, isPending, isError } = useQuery(venuesQueryOptions) + const [activeTab, setActiveTab] = useState('venues') + const tabRefs = useRef>([]) + + function handleTabKeyDown( + event: KeyboardEvent, + index: number, + ) { + const lastIndex = TABS.length - 1 + let nextIndex: number | null = null + + if (event.key === 'ArrowRight') { + nextIndex = index === lastIndex ? 0 : index + 1 + } else if (event.key === 'ArrowLeft') { + nextIndex = index === 0 ? lastIndex : index - 1 + } else if (event.key === 'Home') { + nextIndex = 0 + } else if (event.key === 'End') { + nextIndex = lastIndex + } + + if (nextIndex === null) return + + event.preventDefault() + setActiveTab(TABS[nextIndex].id) + tabRefs.current[nextIndex]?.focus() + } return (
-
+

Admin

- Manage the venues shown on the map and their opening hours. + Manage the venues shown on the map, their opening hours and reviews.

- +
- {isPending && ( -

- Loading venues… -

- )} +
+ {TABS.map((tab, index) => { + const isActive = activeTab === tab.id - {isError && ( -

- Could not load venues. -

- )} + return ( + + ) + })} +
- {data && ( - <> -

- {data.venue.length} {data.venue.length === 1 ? 'venue' : 'venues'} +

+ {isPending && ( +

+ Loading venues…

- - - )} + )} + + {isError && ( +

+ Could not load venues. +

+ )} + + {data && activeTab === 'venues' && ( + <> +
+

+ {data.venue.length}{' '} + {data.venue.length === 1 ? 'venue' : 'venues'} +

+ +
+ + + )} + + {data && activeTab === 'delete-reviews' && ( + + )} +
) diff --git a/apps/frontend/src/styles.css b/apps/frontend/src/styles.css index bf2a5d3..2201391 100644 --- a/apps/frontend/src/styles.css +++ b/apps/frontend/src/styles.css @@ -427,6 +427,14 @@ a { background: color-mix(in oklab, var(--sea-ink) 6%, transparent); } +.striped-table > tbody > tr:not(.no-stripe):nth-child(even) { + background: color-mix(in oklab, var(--sea-ink) 6%, transparent); +} + +.striped-table > tbody > tr:not(.no-stripe):hover { + background: color-mix(in oklab, var(--lagoon) 8%, transparent); +} + .venue-list > li:hover { background: var(--chip-bg); } diff --git a/apps/frontend/src/test/fixtures.ts b/apps/frontend/src/test/fixtures.ts index ee22805..318eebb 100644 --- a/apps/frontend/src/test/fixtures.ts +++ b/apps/frontend/src/test/fixtures.ts @@ -3,7 +3,7 @@ import type { SearchPriceSighting, SearchResult, } from '#/types/search' -import type { VenueReview, venue } from '#/types/venue' +import type { VenuePriceSighting, VenueReview, venue } from '#/types/venue' export function makeOpeningHours( overrides: Partial = {}, @@ -31,6 +31,16 @@ export function makePriceSighting( } } +export function makeVenuePriceSighting( + overrides: Partial = {}, +): VenuePriceSighting { + return { + id: 'price-1', + ...makePriceSighting(), + ...overrides, + } +} + export function makeSearchResult( overrides: Partial = {}, ): SearchResult { @@ -78,7 +88,7 @@ export function makeVenue(overrides: Partial = {}): venue { }, openingHours: [makeOpeningHours()], openingHoursNotes: [], - pricesSighted: [makePriceSighting()], + pricesSighted: [makeVenuePriceSighting()], reviews: [makeReview()], ...overrides, } diff --git a/apps/frontend/src/types/venue.ts b/apps/frontend/src/types/venue.ts index 516d1a7..a130628 100644 --- a/apps/frontend/src/types/venue.ts +++ b/apps/frontend/src/types/venue.ts @@ -17,6 +17,7 @@ export interface VenueOpeningHoursNote { } export interface VenuePriceSighting { + id?: string price: number size: string sizeMl: number | null