Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ personal wantlist ("crate").

IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`.

**Status: M2 – PostgreSQL and GraphQL.** The frontend supports album and artist search, while the backend implements searching, filtering, sorting and pagination. Album details, reviews, crate functionality, simulated user identity and additional frontend controls are planned for later milestones. See the README for current implementation status.
**Status: M3 – Functional beta.** See the README's
[implementation status](README.md#implementation-status) for implemented features
and planned work.

## Commands

Expand Down Expand Up @@ -43,10 +45,10 @@ requirements work - do not casually change them.
from a field resolver.
4. **User input is never interpolated into SQL.** Use parameterised queries.
5. **Users are simulated.** A UUID in `localStorage`, sent as an `X-User-Id`
header on **every** request, not just mutations. `myReview`, `isInCrate` and
`myCrate` are queries and need it just as much. The server reads the header
once into the GraphQL context, so no field in `schema.graphql` takes a
`userId` argument. No authentication.
header on **every** request, not just mutations. The implemented `myReview`
and `isInCrate` fields, as well as the planned `myCrate` query, rely on
this identity. The server reads the header once into the GraphQL context,
so no field in `schema.graphql` takes a `userId` argument. No authentication.
- Missing or malformed id means **anonymous**: reads degrade to `null` or
`false`, mutations that need identity fail with a clear error.
- The context is **per request**. Hoisting the user id into a module-level
Expand Down
34 changes: 25 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ CI also builds the project and checks the client bundle size.
| `pnpm db:fetch:musicbrainz` | Rebuild the local MusicBrainz snapshot (network required) |
| `pnpm db:seed:large` | Reset to a large synthetic catalog |

Unit tests cover frontend components and backend logic, but do not test a running PostgreSQL database. The [VM setup guide](docs/VM-setup.md) includes API smoke tests.
Tests cover frontend components and backend logic. Additional PostgreSQL tests cover search, sorting, rating updates and filters. These run when `TEST_DATABASE_URL` is configured and require a separate test database with migrations applied. The
[VM setup guide](docs/VM-setup.md) includes API smoke tests.

## Database seed data

Expand Down Expand Up @@ -180,6 +181,12 @@ Measurements are based on two local runs with cached synthetic data and cover on

The read-only benchmark is available in `server/scripts/prefix-search-perf.sql`. PostgreSQL tests can be run by setting `TEST_DATABASE_URL` before running the server tests.

### Accessibility

The interface supports keyboard navigation, visible focus indicators, labelled form controls and a skip link to the main content. Search results, loading states and errors provide feedback to assistive technologies. The layout adapts to smaller screens and respects reduced-motion preferences.

Automated accessibility tests use axe-core to check key search states, including initial, results, no-results and error views. Component tests also cover keyboard interactions and focus behavior. Since these tests run in jsdom, they cannot fully verify visual accessibility, such as color contrast and layout at different zoom levels. Manual browser testing is still needed.

### Sustainability measures

We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs.
Expand All @@ -189,10 +196,10 @@ We consider sustainability through design choices that reduce unnecessary data t
| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle |
| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it |
| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it |
| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free |
| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached |
| Explicit search submission | Typing would otherwise cost one request per change | Typing sends no search requests; Search or Enter commits the query |
| `cache-first` fetch policy | A repeated search is already in the cache | No request when the complete requested result is cached |
| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages |
| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle |
| Code-split album route | The detail page is not needed to browse search results | Separate detail chunks; see dated measurements below |
| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk |
| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes |

Expand All @@ -206,7 +213,7 @@ We consider sustainability through design choices that reduce unnecessary data t
| `AlbumDetailPage-*.css` | 1.94 kB | 0.71 kB |
| `index.html` | 0.51 kB | 0.31 kB |

The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. The album link currently causes a full page load, so opening an album also reloads the main bundle.
The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. Opening an album uses normal page navigation, while previously downloaded assets may be reused by the browser.

**Requests for a typical search:** An uncached search initially fetches up to 20 albums in one `searchAlbums` request. Infinite scroll loads up to two additional pages automatically, while further pages are loaded using the Load more button. Previously fetched pages are reused from Apollo's cache without new requests. No search requests are sent while the user types.

Expand All @@ -228,15 +235,24 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai
| `schema.graphql` | GraphQL schema |
| `docs/` | Architecture, data model, UI, workflow, AI log and VM guide |

**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre, decade and has-reviews filters with facet counts, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results.
## Implementation status

**Search and filtering:** Users can search for albums by title or artist using Search or Enter. Results can be sorted by relevance, title, release year or average rating, and filtered by genre, decade or whether an album has reviews. Search terms, sorting and filters are preserved in the URL.

**Results and pagination:** Searches initially display up to 20 albums. Additional results load automatically as the user scrolls, up to 60 albums. Load more is also available before this limit; further pages require the button. The interface provides loading, error and no-results feedback.

**Album details and reviews:** Album pages display tracks, average ratings and reviews. Users can write, edit and delete their own reviews.

The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. A Filters button above the results opens a panel that narrows them by genre, decade and whether an album has reviews. Genres combine with AND, so a genre's count is how many albums would remain after ticking it. Decades combine with OR, so a decade's count is how many matching albums that decade has, and ticking another decade adds them to the selection. Options with no matches are hidden, but selected ones always stay so they can be removed. Changing a filter starts again from the first page. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page.
**Personal crate:** Users can add or remove albums from their crate on both search results and album detail pages. User identity is simulated using a locally stored ID rather than a login system.

**Planned:** A page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker.
**Planned for M4:** A page for viewing all albums saved in the user's crate, the supporting `myCrate` query, and Playwright end-to-end tests. Browsing albums without entering a search term is also planned.

### Backend search behavior

The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre, decade and has-reviews filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. All of it is exposed in the frontend.
The API uses PostgreSQL full-text search with prefix matching (e.g. `radi`
matches `Radiohead`). SQL handles sorting, filtering, facet counts and cursor
pagination; see the [architecture decisions](docs/architecture.md#3-sorting-and-filtering-in-sql)
for details.

## Try the application

Expand Down
2 changes: 1 addition & 1 deletion client/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
}
#main {
max-width: 1240px;
padding: 0 2rem;
padding-inline: 2rem;
margin: auto;
}
.search-section {
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/AlbumCard.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
}
.album-info h3 {
margin: 0;
font-size: 1rem;
font-size: 1.1rem;
line-height: 1.4;
overflow-wrap: anywhere;
}
Expand Down
12 changes: 10 additions & 2 deletions client/src/components/CrateButton.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@
color: var(--danger, #a32626);
font-size: 0.85rem;
}
.crate-button--saved {
.crate-button {
background: transparent;
border: 1px solid var(--accent);
color: var(--accent);
}
.crate-button:not(.crate-button--saved):not(:disabled):hover {
background: var(--chip-bg);
}
.crate-button.crate-button--saved {
background: var(--accent);
color: var(--accent-text);
}
.crate-button--saved:hover {
.crate-button--saved:not(:disabled):hover {
background: var(--accent-hover);
}
6 changes: 6 additions & 0 deletions client/src/components/ReviewForm.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,19 @@
}
.review-form__ratings label {
align-items: center;
cursor: pointer;
display: flex;
gap: 0.25rem;
padding: 0.35rem 0.5rem;
}
.review-form textarea {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
display: block;
font: inherit;
padding: 0.65rem 0.75rem;
resize: vertical;
width: 100%;
}
Expand Down
46 changes: 44 additions & 2 deletions client/src/pages/AlbumDetailPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,38 @@ it('renders an album tracklist and its first page of reviews', async () => {
expect(within(reviews).getByLabelText('5 out of 5 stars')).toBeInTheDocument();
});

it.each([
['1', 'You'],
['2', 'Listener user-1'],
])('labels a review with own review ID %s as %s', async (ownReviewId, authorLabel) => {
render(
<MockedProvider
mocks={[
{
request: { query: ALBUM_DETAIL, variables },
result: {
data: {
album: {
...detail,
myReview: { id: ownReviewId, rating: 5, comment: 'My review.' },
},
},
},
},
]}
>
<AlbumDetailPage id="1" />
</MockedProvider>,
);

const reviews = await screen.findByRole('region', { name: 'Reviews' });
const review = within(reviews).getByRole('article');
expect(within(review).getByText(authorLabel)).toBeInTheDocument();
expect(
within(review).queryByText(authorLabel === 'You' ? 'Listener user-1' : 'You'),
).not.toBeInTheDocument();
});

it('shows a useful error state when an album cannot be loaded', async () => {
window.history.replaceState({}, '', '/album/1?q=Abbey&sort=TITLE_ASC');
render(
Expand All @@ -86,9 +118,11 @@ it('shows a useful error state when an album cannot be loaded', async () => {
);
});

it('loads the next page of reviews on request', async () => {
it('loads the next page of reviews and labels an own review as You', async () => {
const myReview = { id: '2', rating: 4, comment: 'Still brilliant.' };
const firstPage = {
...detail,
myReview,
reviewCount: 2,
reviews: {
...detail.reviews,
Expand All @@ -98,6 +132,7 @@ it('loads the next page of reviews on request', async () => {
};
const secondPage = {
...detail,
myReview,
reviewCount: 2,
reviews: {
edges: [
Expand Down Expand Up @@ -137,10 +172,17 @@ it('loads the next page of reviews on request', async () => {
);

await screen.findByRole('heading', { name: 'Abbey Road' });
expect(screen.getByText('Listener user-1')).toBeInTheDocument();
expect(screen.queryByText('You')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Load more reviews' }));

expect(await screen.findByText('Still brilliant.')).toBeInTheDocument();
expect(await screen.findByText('You')).toBeInTheDocument();
const articles = screen.getAllByRole('article');
expect(articles).toHaveLength(2);
expect(within(articles[1]!).getByText('Still brilliant.')).toBeInTheDocument();
expect(screen.getByText('A classic.')).toBeInTheDocument();
expect(screen.getByText('Listener user-1')).toBeInTheDocument();
expect(screen.queryByText('Listener user-2')).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: 'Load more reviews' }),
).not.toBeInTheDocument();
Expand Down
6 changes: 5 additions & 1 deletion client/src/pages/AlbumDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,11 @@ export default function AlbumDetailPage({ id }: { id: string }) {
<li key={review.id}>
<article>
<header>
<strong>{review.user.displayName}</strong>
<strong>
{review.id === album.myReview?.id
? 'You'
: review.user.displayName}
</strong>
<span role="img" aria-label={`${review.rating} out of 5 stars`}>
{'★'.repeat(review.rating)}
</span>
Expand Down
13 changes: 9 additions & 4 deletions docs/VM-setup.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# VM setup

How to deploy the Crate application on the group VM and verify that it works.
How to update and verify the Crate application deployed on the group VM.

## Deployment setup

Expand All @@ -27,6 +27,8 @@ pnpm --filter @t19/server build
sudo /usr/bin/systemctl restart crate-api
```

To populate the catalog initially or import an updated MusicBrainz snapshot, run `pnpm --filter @t19/server db:import:musicbrainz`. Existing reviews and crate items are preserved.

The database and role must already exist before migrations are run. The API
runs on port 3001 and needs the repository's `schema.graphql` file at startup.

Expand Down Expand Up @@ -60,6 +62,7 @@ curl -fsS -o /dev/null -w '%{http_code}\n' http://localhost/project2/

Then run the smoke tests below against the API and, if needed, through Apache.
You can also open <http://it2810-19.idi.ntnu.no/project2/> and try an album search.
Open an album detail URL directly and reload the page to verify that routing works correctly.

### Optional sample data

Expand All @@ -84,9 +87,11 @@ endpoint, set `VITE_GRAPHQL_URL` in `client/.env.local`.

## Smoke suite

Run these commands on the VM after deployment. The expected counts below assume
the sample catalog from `db:seed`; counts may differ if the database contains
other data. Check each response for GraphQL `errors`.
The smoke tests below were originally written for the sample catalog created by `db:seed`. Some expected album names, counts and genre IDs do not match the deployed MusicBrainz catalog.

**TODO (M4):** Update the smoke tests and expected results to use the MusicBrainz catalog.

Until then, the tests can be used to check API functionality, but sample-specific results should not be treated as expected values on the VM. Check each response for GraphQL `errors`.

```bash
API=http://localhost:3001/graphql
Expand Down
Loading