diff --git a/README.md b/README.md index 80e51dfe..6cb8008c 100644 --- a/README.md +++ b/README.md @@ -10,10 +10,10 @@ http://it2810-03.idi.ntnu.no/project2/ - **Plant Match:** Shows plants one at a time, best matches for your preferences first. Click ✿ to like a plant or ✖ to skip it. - **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Without preferences, the plants come in random order. -- **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants. You can also remove plants from the list. +- **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants, with the number of matches shown above. Sort them by newest, oldest or name (A–Z or Z–A), and move between pages when there are many. The sort order is remembered for the session, also when you go to another page and back. You can also remove plants from the list. - **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the number of results is shown above the plants. The results are split into pages, and you can jump straight to any page. The search, filters, sorting and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. Add a plant to My Matches with the ✿ button, and click it again to remove it. - **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level). Flip the card to read more about the plant. -- **Profile:** Your name, description, avatar and preferences are saved in the database, and your matched plants are shown here. +- **Profile:** Your name, description, avatar and preferences are saved in the database. - **Plant Owner Test:** A short quiz that tells you what kind of plant owner you are. Each result has its own picture, which you can only get through the test, and you can save it as your profile picture. - **Language:** The app is available in English and Norwegian. - **Theme:** The app has a light and a dark theme. diff --git a/backend/src/helpers.ts b/backend/src/queryBuilders.ts similarity index 82% rename from backend/src/helpers.ts rename to backend/src/queryBuilders.ts index ee7cfc0e..edf376df 100644 --- a/backend/src/helpers.ts +++ b/backend/src/queryBuilders.ts @@ -1,4 +1,4 @@ -import type { Document, Filter } from "mongodb"; +import type { Document, Filter, ObjectId } from "mongodb"; import type { ExplorePlantsArgs, PlantDoc } from "./types.js"; // Helpers for searching, filtering and sorting plants @@ -62,6 +62,36 @@ export const buildSortStages = (sort?: string): Document[] => { } }; +// Builds the aggregation stages that sort the user's matched plants on My Matches. +// matchedPlantIds is in the order the plants were matched, so a plant's +// position in it tells how new the match is. +export const buildMatchSortStages = ( + sort: string | undefined, + matchedPlantIds: ObjectId[], +): Document[] => { + const byMatchOrder = (direction: 1 | -1): Document[] => [ + { + $addFields: { + matchOrder: { $indexOfArray: [matchedPlantIds, "$_id"] }, + }, + }, + { $sort: { matchOrder: direction } }, + ]; + + switch (sort) { + case "oldest": + return byMatchOrder(1); + case "name_asc": + return [{ $sort: { commonName: 1, _id: 1 } }]; + case "name_desc": + return [{ $sort: { commonName: -1, _id: -1 } }]; + default: + // Newest first is the default, since those are usually + // the ones the user wants to see + return byMatchOrder(-1); + } +}; + // Builds the MongoDB filter for the search and filters on Explore Plants export const buildExploreFilter = ( args: ExplorePlantsArgs, diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index 2bd63294..691f069f 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -4,13 +4,15 @@ import type { Document, WithId } from "mongodb"; import { db } from "./db.js"; import { buildExploreFilter, + buildMatchSortStages, buildSortStages, matchScore, PREFERENCE_MATCHERS, -} from "./helpers.js"; +} from "./queryBuilders.js"; import type { ExplorePlantsArgs, GetPlantsArgs, + MyMatchesArgs, Plant, PlantDoc, UpdateUserPreferencesArgs, @@ -200,6 +202,37 @@ export const resolvers = { const doc = await users.findOne({ _id }); return doc ? toUser(doc) : null; }, + + // One page of the user's matched plants, sorted. Only the ids are stored on + // the user, so the plants are looked up and sorted in the plants collection. + // An unknown or malformed user id gives an empty page. + myMatches: async ( + _parent: unknown, + args: MyMatchesArgs, + ): Promise<{ plants: Plant[]; totalCount: number }> => { + const _id = toObjectId(args.userId); + const user = _id + ? await users.findOne({ _id }, { projection: { matchedPlantIds: 1 } }) + : null; + const matchedPlantIds = user?.matchedPlantIds ?? []; + if (matchedPlantIds.length === 0) return { plants: [], totalCount: 0 }; + + // Only plants that still exist are shown and counted (e.g. after a reseed) + const filter = { _id: { $in: matchedPlantIds } }; + const [docs, totalCount] = await Promise.all([ + plants + .aggregate>([ + { $match: filter }, + ...buildMatchSortStages(args.sort, matchedPlantIds), + { $skip: args.offset }, + { $limit: args.limit }, + ]) + .toArray(), + plants.countDocuments(filter), + ]); + + return { plants: docs.map(toPlant), totalCount }; + }, }, Mutation: { @@ -282,18 +315,10 @@ export const resolvers = { }, User: { - // Looks up the matched plants, in the order they were matched. - // Ids of plants that no longer exist (e.g. after a reseed) are skipped. - matchedPlants: async (user: User): Promise => { - if (user.matchedPlantIds.length === 0) return []; - const docs = await plants - .find({ _id: { $in: user.matchedPlantIds } }) - .toArray(); - const byId = new Map(docs.map((doc) => [doc._id.toString(), doc])); - return user.matchedPlantIds.flatMap((id) => { - const doc = byId.get(id.toString()); - return doc ? [toPlant(doc)] : []; - }); - }, + // Only the ids of the matched plants, so pages that just need to know + // whether a plant is matched don't fetch the whole plants with images. + // My Matches gets the plants themselves from the myMatches query. + matchedPlantIds: (user: User): string[] => + user.matchedPlantIds.map((id) => id.toString()), }, }; diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 5fcc657b..f6d1f935 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -12,6 +12,12 @@ export const typeDefs = ` offset: Int = 0 ): PlantPage! getUser(userId: ID!): User + myMatches( + userId: ID! + sort: String + limit: Int = 12 + offset: Int = 0 + ): PlantPage! } type Mutation { @@ -49,7 +55,7 @@ export const typeDefs = ` description: String profilePicture: String! preferences: [String!]! - matchedPlants: [Plant!]! + matchedPlantIds: [ID!]! createdAt: String! } `; diff --git a/backend/src/types.ts b/backend/src/types.ts index e05cee7f..bfc6a0d9 100644 --- a/backend/src/types.ts +++ b/backend/src/types.ts @@ -51,13 +51,14 @@ export interface UserDoc { description: string | null; profilePicture: string; preferences: string[]; - // Only the plant ids are stored, the plants are looked up in User.matchedPlants + // Only the plant ids are stored, in the order the plants were matched. + // The plants themselves are looked up by the myMatches query. matchedPlantIds: ObjectId[]; createdAt: Date; } -// The shape of a User in the GraphQL API. matchedPlantIds is not in the schema, -// it is only passed on to the User.matchedPlants resolver. +// The shape of a User in the GraphQL API. matchedPlantIds is turned into +// strings by the User.matchedPlantIds resolver. export interface User { id: string; name: string | null; @@ -85,3 +86,9 @@ export interface UpdateUserPreferencesArgs extends UserIdArgs { export interface UserMatchArgs extends UserIdArgs { plantId: string; } + +export interface MyMatchesArgs extends UserIdArgs { + sort?: string; + limit: number; + offset: number; +} diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index 5e61a1ea..c99392c1 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -95,7 +95,7 @@ const USER_FIELDS = ` description profilePicture preferences - matchedPlants { id name } + matchedPlantIds createdAt `; @@ -105,7 +105,7 @@ type User = { description: string | null; profilePicture: string; preferences: string[]; - matchedPlants: { id: string; name: string }[]; + matchedPlantIds: string[]; createdAt: string; }; @@ -444,7 +444,7 @@ describe("users", () => { description: null, profilePicture: "default", preferences: [], - matchedPlants: [], + matchedPlantIds: [], }); expect((await getUser(user.id)).data?.getUser).toEqual(user); }); @@ -539,41 +539,108 @@ describe("users", () => { await addMatch(id, fern); await addMatch(id, orchid); const added = await addMatch(id, orchid); - expect(added.data?.addUserMatch?.matchedPlants).toEqual([ - { id: fern, name: "Fern" }, - { id: orchid, name: "Orchid" }, - ]); + expect(added.data?.addUserMatch?.matchedPlantIds).toEqual([fern, orchid]); const removed = await removeMatch(id, fern); - expect(removed.data?.removeUserMatch?.matchedPlants).toEqual([ - { id: orchid, name: "Orchid" }, - ]); + expect(removed.data?.removeUserMatch?.matchedPlantIds).toEqual([orchid]); }); - it("skips matched plants that were deleted from the database", async () => { + it.each([ + ["an id that does not exist", new ObjectId().toString()], + ["a malformed id", "not-an-id"], + ])("returns null without an error for %s", async (_, userId) => { + expect(await getUser(userId)).toEqual({ data: { getUser: null } }); + expect((await updateProfile({ userId, name: "Nina" })).data).toEqual({ + updateUserProfile: null, + }); + }); +}); + +describe("my matches", () => { + const MY_MATCHES = ` + query ($userId: ID!, $sort: String, $limit: Int, $offset: Int) { + myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) { + totalCount + plants { name } + } + } + `; + + type Page = { totalCount: number; plants: { name: string }[] }; + + // The names on one page of My Matches, and the total number of matches + async function myMatches(variables: Record) { + const result = await execute<{ myMatches: Page }>(MY_MATCHES, variables); + expect(result.errors).toBeUndefined(); + const page = result.data!.myMatches; + return { + names: page.plants.map((p) => p.name), + totalCount: page.totalCount, + }; + } + + // Matches Basil, Cactus and Aloe in that order, so that newest, oldest, + // A–Z and Z–A all give a different order + async function userWithMatches() { const { id } = await createUser(); - const [orchid, fern] = await insertPlants( - { commonName: "Orchid" }, - { commonName: "Fern" }, + const [aloe, basil, cactus] = await insertPlants( + { commonName: "Aloe" }, + { commonName: "Basil" }, + { commonName: "Cactus" }, ); - await addMatch(id, orchid); - await addMatch(id, fern); - await db.collection("plants").deleteOne({ _id: new ObjectId(orchid) }); + for (const plantId of [basil, cactus, aloe]) { + await addMatch(id, plantId); + } + return { id, aloe }; + } - const result = await getUser(id); + it.each([ + ["no sort (newest first)", undefined, ["Aloe", "Cactus", "Basil"]], + ["oldest", "oldest", ["Basil", "Cactus", "Aloe"]], + ["name_asc", "name_asc", ["Aloe", "Basil", "Cactus"]], + ["name_desc", "name_desc", ["Cactus", "Basil", "Aloe"]], + ])("sorts with %s", async (_, sort, expected) => { + const { id } = await userWithMatches(); + + expect(await myMatches({ userId: id, sort })).toEqual({ + names: expected, + totalCount: 3, + }); + }); - expect(result.data?.getUser?.matchedPlants).toEqual([ - { id: fern, name: "Fern" }, - ]); + it("returns one page at a time with the total count", async () => { + const { id } = await userWithMatches(); + + expect(await myMatches({ userId: id, limit: 2 })).toEqual({ + names: ["Aloe", "Cactus"], + totalCount: 3, + }); + expect(await myMatches({ userId: id, limit: 2, offset: 2 })).toEqual({ + names: ["Basil"], + totalCount: 3, + }); + }); + + it("leaves out and does not count matched plants that were deleted", async () => { + const { id, aloe } = await userWithMatches(); + await db.collection("plants").deleteOne({ _id: new ObjectId(aloe) }); + + expect(await myMatches({ userId: id })).toEqual({ + names: ["Cactus", "Basil"], + totalCount: 2, + }); }); it.each([ + ["a user without matches", null], ["an id that does not exist", new ObjectId().toString()], ["a malformed id", "not-an-id"], - ])("returns null without an error for %s", async (_, userId) => { - expect(await getUser(userId)).toEqual({ data: { getUser: null } }); - expect((await updateProfile({ userId, name: "Nina" })).data).toEqual({ - updateUserProfile: null, + ])("returns an empty page for %s", async (_, userId) => { + const id = userId ?? (await createUser()).id; + + expect(await myMatches({ userId: id })).toEqual({ + names: [], + totalCount: 0, }); }); }); @@ -641,7 +708,7 @@ describe("error messages", () => { message: `Unknown plant: ${plantId}`, code: "BAD_USER_INPUT", }); - expect((await getUser(id)).data?.getUser?.matchedPlants).toEqual([]); + expect((await getUser(id)).data?.getUser?.matchedPlantIds).toEqual([]); }); it("rejects removing a malformed plant id", async () => { diff --git a/docs/ai-usage.md b/docs/ai-usage.md index 87fe8f34..0bae9a17 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -39,3 +39,7 @@ After the peer reviews, we used AI to help us split up `ExplorePlants.tsx`, whic ## How we kept control All AI-generated suggestions were reviewed, tested and adapted by the team before they were committed. Every change went through a pull request that had to be approved by another group member (see [quality.md](quality.md#work-practices)), so no AI-generated code was merged without a review. Design and architectural decisions were made by the team. + +### Being critical of a suggestion from AI + +We did not always follow the suggestions from AI. For example, when My Matches was changed to fetch one page of plants at a time, the old `matchedPlants` field on the user was no longer used by the app. AI first suggested keeping the field because the tests used it, but we decided to remove it, since keeping unused code only for the tests made no sense. Before removing it, we searched the code for every place it was used, to make sure it was safe. Then we updated the tests to use the new field, and wrote new tests for the `myMatches` query. diff --git a/docs/architecture.md b/docs/architecture.md index 2772d244..ca184c05 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,8 @@ Perenual API → seedDataFetch.js ─┐ │ GraphQL over HTTP (/graphql) │ Frontend: React + Apollo Client - (localStorage: userId, URL: Explore state) + (localStorage: userId, URL: Explore state, + sessionStorage: My Matches sort order) ``` The plant data is fetched from the Perenual API once and stored in our own database. The data was loaded using the seedDataFetch.js file. About 120 plants where loaded. The number is an estimate as we have not verified each plants response to the fetch operation. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend: @@ -38,17 +39,17 @@ The frontend is built with React and TypeScript (Vite). - **Routing:** Routes are defined in `AppRoutes.tsx` with React Router, and the app is served under the base path `/project2/`. Vite defines this base in `frontend/vite.config.ts`; `HashRouter` provides the client-side routes, including Explore query parameters after the hash. All pages except the start page are lazy-loaded. Any path that does not match a route shows the 404 page, and the header shows the "Page not found" title for it. - | Route | Page | Purpose | - | ----------------- | ---------------- | -------------------------------------------------------------- | - | `/` | `PlantMatchPage` | Swipe through random plants (`getPlants`) and match with them | - | `/explorePlants` | `ExplorePlants` | Search, filter, sort and paginate all plants (`explorePlants`) | - | `/my-matches` | `MyMatchesPage` | List and remove the user's matched plants | - | `/profile` | `Profile` | Edit name, description, profile picture and preferences | - | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | - | `*` | `NotFound` | 404 page for unknown paths, with a link back to Plant Match | + | Route | Page | Purpose | + | ----------------- | ---------------- | ---------------------------------------------------------------- | + | `/` | `PlantMatchPage` | Swipe through random plants (`getPlants`) and match with them | + | `/explorePlants` | `ExplorePlants` | Search, filter, sort and paginate all plants (`explorePlants`) | + | `/my-matches` | `MyMatchesPage` | List, sort, paginate and remove the user's matches (`myMatches`) | + | `/profile` | `Profile` | Edit name, description, profile picture and preferences | + | `/plantOwnerTest` | `PlantOwnerTest` | A quiz whose result can be set as the profile picture | + | `*` | `NotFound` | 404 page for unknown paths, with a link back to Plant Match | - **User state:** `UserProvider` (`context/UserContext.tsx`) loads the current user from the backend and makes it available through `useUser()`. The hooks `useProfile` and `useMatchedPlants` wrap the user mutations, so pages do not call GraphQL directly for user data. All user queries and mutations live in `context/userQueries.ts`. -- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text), `useExploreParams` keeps Explore search, filters, sorting and page in the URL (with React Router's `useSearchParams`) and sends the user back to page 1 when the search, a filter or the sort order changes, and `useSessionState` stores state in `sessionStorage` for features that still use it. +- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing (used for search and for saving the profile text). `useExploreParams` keeps the Explore search, filters, sort order and page in the URL, and sends the user back to page 1 when the search, a filter or the sort order changes. It uses `useUrlParams`, which reads the page number and updates the URL (with React Router's `useSearchParams`). `useSessionState` stores state in `sessionStorage`, for example the sort order on My Matches. - **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, and always shows the first and last page with "…" in between, so it works for any number of pages (`getPageItems`). `FilterSelect` is a labelled dropdown for one filter. `SortMenu` is a sort button that shows the selected option and opens a menu that can be used with the keyboard. All three take already translated texts, so they can be used on other pages. - **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next). - **Shared types:** `Plant` and `Preference` are defined in `types/`. @@ -57,7 +58,7 @@ The frontend is built with React and TypeScript (Vite). The frontend uses Apollo Client, which is set up in `main.tsx` with an in-memory cache. The GraphQL URL is read from `VITE_GRAPHQL_URL` (set in `frontend/.env.production` for the deployed app) and falls back to `/graphql`. During development, requests to `/graphql` are proxied by Vite to the backend on port 3001 (see [vite.config.ts](../frontend/vite.config.ts)). -All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. Adding and removing a match always returns the whole list of matches, so the cache replaces `matchedPlants` instead of merging it with the old list. +All user queries and mutations ask for the same `UserFields` fragment, so when one page changes the user (for example adds a match), Apollo's cache updates the user on every page at once. Changing the profile picture uses an optimistic response, so the new picture is shown before the server has answered. The fragment only has the ids of the matched plants (`matchedPlantIds`), so the user stays small however many matches there are. Adding and removing a match returns the whole list of ids, so the cache replaces it instead of merging it with the old list. My Matches fetches its plants with its own `myMatches` query, which is fetched again when a match is added or removed, and every time the page is opened. ## Backend: GraphQL with Apollo Server @@ -67,7 +68,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `server.ts` starts Apollo Server on `PORT` (default 3001) with the schema and resolvers below. - `schema.ts` defines the GraphQL schema (`typeDefs`). - `resolvers.ts` has the resolvers for plants and users, and validates user input. -- `helpers.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants. +- `queryBuilders.ts` builds the MongoDB filters and sort stages for searching, filtering and sorting plants on Explore Plants and My Matches. - `indexes.ts` creates the database indexes the app needs when the server starts (see [Scalability](#scalability)). - `types.ts` has the TypeScript types for the MongoDB documents, the GraphQL types and the resolver arguments. - `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below). @@ -81,6 +82,7 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f | `getPlants(limit = 50, excludeIds, preferences): [Plant]` | Returns up to `limit` plants for the match page, leaving out the plants in `excludeIds` so each batch only has new plants (malformed ids are ignored). Without `preferences` the order is random (MongoDB `$sample`). With `preferences`, each plant gets a score: the number of the preferences it matches on watering, sunlight and care level ("Low" counts as easy care, "Medium" and "Moderate" as medium care). The highest scores come first and plants with the same score are shuffled. Unknown preferences are ignored. | | `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on common or scientific name (case-insensitive), filter on sunlight, watering and care level, sort and paginate. Returns the plants on the page and `totalCount` for the whole result. Sort can be `name_desc`, `watering_asc` or `careLevel_asc`; the default is name A–Z. | | `getUser(userId): User` | Returns the user, or `null` if the id is unknown or malformed. | +| `myMatches(userId, sort, limit = 12, offset = 0): PlantPage!` | Returns one page of the user's matched plants and `totalCount`. Sort can be `oldest`, `name_asc` or `name_desc`; the default is newest first. The order of `matchedPlantIds` is the order the plants were matched, so no date is needed. An unknown or malformed user id gives an empty page. | **Mutations** @@ -96,9 +98,9 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f - `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel` - `PlantPage`: `plants`, `totalCount` -- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlants`, `createdAt` +- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlantIds`, `createdAt` -`User.matchedPlants` has its own resolver. It looks up the plants from the stored `matchedPlantIds` in one query and returns them in the order they were matched. Ids of plants that no longer exist (for example after a reseed) are skipped. +`User.matchedPlantIds` only returns the ids, so the pages that just need to know whether a plant is matched do not fetch the whole plants with images. The plants themselves are fetched one page at a time with `myMatches`, which only shows and counts plants that still exist (for example after a reseed). Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPUT` instead of crashing the server. @@ -147,15 +149,15 @@ Note: the image URLs from the Perenual API expire after 24 hours. That is why ea One document per user. There is no login: a user is created the first time someone opens the app, and the browser keeps the user id (see [Where state is kept](#where-state-is-kept)). The id is generated by MongoDB. -| Field | Type | Description | Exposed in GraphQL as | -| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | -| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | -| `description` | string/null | Short profile text, at most 100 characters | `description` | -| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snake-plant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | -| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | -| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlants` (resolved to full `Plant` objects) | -| `createdAt` | Date | When the user was created | `createdAt` (ISO string) | +| Field | Type | Description | Exposed in GraphQL as | +| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | +| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | +| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | +| `description` | string/null | Short profile text, at most 100 characters | `description` | +| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snake-plant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | +| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | +| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlantIds`, and the plants through `myMatches` | +| `createdAt` | Date | When the user was created | `createdAt` (ISO string) | A new user starts with `name: null`, `description: null`, `profilePicture: "default"`, and empty `preferences` and `matchedPlantIds`. The allowed picture and preference ids are listed in `resolvers.ts` and must match the ids used in the frontend (`Profile.tsx` and `plantownertest.ts`). @@ -169,20 +171,20 @@ We store the data in MongoDB, a document database. It is a good fit for this dat - **Plants have different fields.** Some plants have information that others lack. A document database handles optional fields naturally, without many empty columns. - **It is simple to update.** The seed script first inserts a basic entry for each plant, and later adds details to the same document (an upsert keyed on `perenualId`). User updates are single atomic operations such as `$set`, `$addToSet` and `$pull`. -The trade-off in using a NoSQL database such as MongoDB compared to a relational database such as MySQL is that it does not enforce relationships between collections. That matters little here: the plant collection is read-only for the app, and the only reference between the collections is `users.matchedPlantIds`. `addUserMatch` checks that the plant exists before storing the id, and the `matchedPlants` resolver skips ids that no longer point to a plant. +The trade-off in using a NoSQL database such as MongoDB compared to a relational database such as MySQL is that it does not enforce relationships between collections. That matters little here: the plant collection is read-only for the app, and the only reference between the collections is `users.matchedPlantIds`. `addUserMatch` checks that the plant exists before storing the id, and `myMatches` skips ids that no longer point to a plant. MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be reached directly from the internet. During development, it is reached through an SSH tunnel (see [Run the project locally](../README.md#run-the-project-locally) in the README). The backend tests use an in-memory MongoDB (`mongodb-memory-server`), so they never touch the database on the VM. ## Where state is kept -| Where | What | Why | -| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | -| `localStorage` | Only the key `userId` | Lets the browser find its user again on the next visit, without a login | -| URL parameters | Explore page search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`), via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | -| `sessionStorage` | Features that still use `useSessionState`, such as the language switcher | The value is kept for the kurrent browser session | -| Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | -| React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | +| Where | What | Why | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| MongoDB `users` | Profile (name, description, picture), preferences and matched plants | Persistent user data that should survive closing the browser | +| `localStorage` | Only the key `userId` | Lets the browser find its user again on the next visit, without a login | +| URL parameters | Explore search, filters, sort and page (`search`, `watering`, `sunlight`, `careLevel`, `sort`, `page`) via `useExploreParams` | The view survives navigation and refresh and can be shared as a link | +| `sessionStorage` | The sort order on My Matches (`myMatches.sort`), and other features that use `useSessionState`, such as the language switcher | The value is kept for the current browser session, also when the user goes to another page and back. The page on My Matches always starts at 1, so new matches are seen first | +| Apollo in-memory cache | Query results (plants and the current user) | Avoids asking the backend again for data the app already has, and keeps all pages in sync | +| React state | Short-lived UI state, such as the current plant on the match page and unsaved profile text | Only matters while the component is shown | User data used to be stored in `localStorage`. `UserProvider` now removes the old keys (`plantPreferences`, `matchedPlants`, `profileName`, `description`, `profileAvatar`) on start-up, so old data does not lie around in the browser. @@ -200,7 +202,7 @@ When the app starts, `UserProvider` reads `userId` from `localStorage` and runs - **Sorting by watering and care level:** These use a calculated rank, since the values cannot be sorted alphabetically (Minimum, Average, Frequent), and plants without a value are put last. A calculated rank cannot use an index. If the collection grows much larger, the rank could be calculated once when the data is loaded, stored on each plant and indexed. - **Offset-based pagination.** We use offset-based pagination (`$skip` and `$limit`) instead of cursor-based pagination, because it lets the user jump to any page and works with all our sort orders, including the ones on calculated values. Offset pagination gets slower for very deep pages, but that only matters for collections far larger than ours. - **Small responses.** GraphQL returns only the requested fields, and fields we do not use are kept out of the schema. -- **Small user documents.** Matches are stored as plant ids, and user updates only touch one document. +- **Small user documents and responses.** Matches are stored as plant ids, and user updates only touch one document. Only the ids are sent with the user, and My Matches fetches one page of plants at a time, so the responses do not grow with the number of matches. - **Less traffic from the client.** Search input is debounced, results are cached by Apollo, and pages other than the start page are lazy-loaded. ## Data source: the Perenual API @@ -229,7 +231,7 @@ T03-Project-2/ ├── backend/ │ ├── src/ │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) -│ │ ├── helpers.ts # Filters and sort stages for searching, filtering and sorting plants +│ │ ├── queryBuilders.ts # Filters and sort stages for searching, filtering and sorting plants │ │ ├── indexes.ts # Database indexes, created when the server starts │ │ ├── resolvers.ts # GraphQL resolvers for plants and users │ │ ├── schema.ts # GraphQL schema @@ -245,7 +247,7 @@ T03-Project-2/ │ │ ├── assets/ # Static images │ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file │ │ ├── context/ # UserProvider and the GraphQL queries and mutations for the user -│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck) +│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useUrlParams, useExploreParams, useSessionState, useProfile, useMatchedPlants, usePlantDeck) │ │ ├── i18n/ # Translation setup and locale files (no, en) │ │ ├── pages/ # One folder per page/route with a matching .css file │ │ ├── tests/ # Unit and component tests, including test setup (see tests.md) diff --git a/docs/quality.md b/docs/quality.md index df075da1..b7907117 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -45,7 +45,7 @@ The app includes the following accessibility features: - **Forms and images:** Search, filters and profile inputs have associated labels. Plant images use the plant name as alternative text, and profile and avatar images also include alternative text. -- **Control states:** The sort menu exposes its expanded state, and sort and avatar choices expose their selected state with ARIA attributes. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants, the number of results is also announced when the search or filters change. The ✿ button's accessible name and tooltip say whether a click adds the plant to My Matches or removes it. +- **Control states:** The sort menu exposes its expanded state, and sort and avatar choices expose their selected state with ARIA attributes. Pagination marks the current page with `aria-current="page"` and announces page changes through an `aria-live="polite"` region. On Explore Plants and My Matches, the number of results or matches is also announced when it changes. The ✿ button's accessible name and tooltip say whether a click adds the plant to My Matches or removes it. - **Plant cards:** The inactive side of a flipped card is hidden from assistive technology with `aria-hidden`, and its information button is removed from the keyboard tab order. @@ -76,7 +76,7 @@ and our approach to data handling. - **Data fetching and storage:** Plant data is fetched from the Perenual API once and stored in our own MongoDB database. The application retrieves data through our GraphQL backend rather than repeatedly requesting data from the external API. This reduces unnecessary external requests and avoids repeatedly transferring the same data from Perenual. -- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request. +- **Efficient data transfer:** GraphQL allows the frontend to request only the fields it needs. The backend also supports pagination, allowing the frontend to retrieve plants in smaller batches instead of requesting the entire dataset. Sorting by name uses a database index, so the server does not have to sort the whole collection for every request. Only the ids of the user's matches are sent with the user, and My Matches fetches one page of plants at a time, so the plant images are only sent when they are shown. - **Debouncing:** On the Explore Plants page, the search waits 300 ms after the user stops typing before sending a request, so results still feel instant without a request per keystroke, reducing unnecessary search operations. Profile text is saved after 500 ms, since the text is shown right away and the save happens in the background, and a longer delay only means fewer writes to the database. The profile is also saved immediately when a field loses focus or the user leaves the page, so no text is lost. @@ -86,7 +86,7 @@ and our approach to data handling. - **Colour palette and contrast:** We used a limited colour palette to maintain a consistent visual identity across the application. We also checked the contrast between our chosen colours to help ensure that text and other interface elements remain distinguishable. -- **Reusable components:** We used reusable React components to maintain a consistent interface and avoid duplicating code. For example, the Header and Sidebar are shared across pages, while components such as plant cards are used to present plant information consistently. The page navigation (`Pagination`), the filter dropdowns (`FilterSelect`) and the sort menu (`SortMenu`) are separate components that can be reused on other pages, and the filters on Explore Plants are defined in one list, so a new filter only needs one new line. This makes the application easier to maintain and allows changes to be made in one place. +- **Reusable components:** We used reusable React components to maintain a consistent interface and avoid duplicating code. For example, the Header and Sidebar are shared across pages, while components such as plant cards are used to present plant information consistently. The page navigation (`Pagination`) and the sort menu (`SortMenu`) are separate components used on both Explore Plants and My Matches, so the two pages look and work the same way. The filter dropdowns (`FilterSelect`) are also a separate component, and the filters on Explore Plants are defined in one list, so a new filter only needs one new line. This makes the application easier to maintain and allows changes to be made in one place. - **Responsive design:** We designed the application for both desktop and mobile screens. The layout adapts to different screen sizes to ensure that the content and navigation remain usable across devices. diff --git a/docs/tests.md b/docs/tests.md index f0aa11c6..19f73b89 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -133,7 +133,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `LanguageSwitcher.test.tsx` - The button text and accessible name in both languages, that clicking switches to the other language, and snapshots for both languages. - `MyMatchesPage.test.tsx` - - A message when there are no matches, the loading state instead of that message, and that saved matches are shown and can be removed. + - Loading and empty state: a message when there are no matches (without the count, sorting or pages), and the loading state while the user or the matches are fetched. + - Fetching: the first page with the newest first by default, fetched again each time the page is opened, the sort order saved earlier in the session used while the page starts at 1, and saved matches shown and removed. + - Sorting and pages: the number of matches next to the sort menu in an `aria-live` region, moving between pages, a new sort order saved in `sessionStorage` and going back to page 1, and going to the last page when the current page no longer exists. - `NotFound.test.tsx` - An unknown path shows the 404 page, with a link back to Plant Match. - `PlantCard.test.tsx` @@ -178,7 +180,8 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in - `server.test.ts` - Starting the server: the default port 3001, the port in `PORT`, and stopping with the error when the port is in use. - Plants: `getPlants` returns the plants that match the most of the user's preferences first, also when they are fetched in batches ("Low" counts as easy care), random plants when there are no preferences or only unknown ones, and leaves out the plants in `excludeIds` (returning none when all are excluded). Also stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search across common and scientific names with special characters read as text, the watering, care level and sunlight filters ("Medium" and "Moderate" count as the same care level), pagination with the total count, and all sort orders. - - Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, adding and removing matches in order, and skipping matched plants that were deleted. + - Users: creating and fetching users, updating the profile (trimming text, storing empty text and `null` as `null`, and only changing the sent fields), the plant owner test results as profile pictures, preferences without duplicates, and adding and removing matches in order. + - My matches: `myMatches` sorts by newest (the default), oldest, A–Z and Z–A, returns one page at a time with the total count, leaves out and does not count matched plants that were deleted, and returns an empty page for a user without matches and for an unknown or malformed user id. - Error messages: invalid input gives the right message and the code `BAD_USER_INPUT` and saves nothing (too long name or description, unknown profile picture, unknown preferences, unknown or malformed plant ids), invalid GraphQL requests give the right error, and the server passes on a database error and keeps running. - `indexes.test.ts` - The index for sorting by name is created, and creating it again on the next start does not fail. @@ -222,7 +225,7 @@ Each file covers one scenario, and API and UI tests for the same feature come in | ----------------------------------------- | ------------------------ | ----------------------- | | Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` | | Profile and avatar | `apiUserProfile` | `uiUserProfile` | -| Matching and removing plants | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` | +| Matching, removing, sorting and paging | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` | | Accessibility on all pages | – | `uiAccessibility` | **ExplorePlants (`uiExplorePlants`):** one continuous user journey that tests pagination, filtering, search, the detail view, sorting and reset, and that changing a filter on page 2 takes the user back to page 1. @@ -231,6 +234,7 @@ Each file covers one scenario, and API and UI tests for the same feature come in - Liking a plant on PlantMatch adds it to MyMatches, where it can be removed. - Adding a plant from ExplorePlants adds it to MyMatches and marks its ✿ button as matched. Clicking the button again on ExplorePlants removes the plant from MyMatches. +- Matching 13 plants from ExplorePlants gives two pages in MyMatches: the count, the newest first on page 1 and the oldest on page 2, sorting A–Z going back to page 1, and the sort order remembered when going to another page and back, and after a reload. The test user has no preferences, so PlantMatch shows the plants in random order. The test therefore remembers the name of the liked plant and checks that it is the same plant that ends up in MyMatches. @@ -242,7 +246,7 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh - **explorePlants**: default sorting and page size, `offset`, case-insensitive search, regex characters treated as plain text, the watering, care level and sunlight filters, the sort orders, and that plants without a care level are sorted last. - **User profile**: a new user's default values, updating and reading back the profile and preferences, that only the sent fields change, that duplicate preferences are removed, and that too long names and descriptions, unknown profile pictures, unknown preferences and invalid user ids are rejected or return `null` without crashing. -- **Matches**: adding, reading back and removing a match, that matches keep the order they were added in, that the same plant is only matched once, and that unknown or malformed plant ids are rejected. +- **Matches**: adding, reading back and removing a match, that matches keep the order they were added in, that the same plant is only matched once, and that unknown or malformed plant ids are rejected. Also that `myMatches` returns the whole plant, sorts by newest, oldest and name, returns one page at a time with the total count, and returns an empty page for a user without matches or an unknown user. #### Accessibility diff --git a/e2e/apiMatchAndRemovePlant.spec.ts b/e2e/apiMatchAndRemovePlant.spec.ts index f9c4e21b..990630f3 100644 --- a/e2e/apiMatchAndRemovePlant.spec.ts +++ b/e2e/apiMatchAndRemovePlant.spec.ts @@ -1,14 +1,15 @@ import { test, expect, type APIRequestContext } from "@playwright/test"; import { graphql, createUser, GET_USER } from "./helpers/graphql"; -// Tests matching a plant and removing the match in the API, and that the -// matches are stored on the user in the database. +// Tests matching a plant and removing the match in the API, that the matches +// are stored on the user in the database, and that My Matches returns them +// sorted and in pages. const ADD_MATCH = ` mutation AddMatch($userId: ID!, $plantId: ID!) { addUserMatch(userId: $userId, plantId: $plantId) { id - matchedPlants { id name } + matchedPlantIds } } `; @@ -17,7 +18,16 @@ const REMOVE_MATCH = ` mutation RemoveMatch($userId: ID!, $plantId: ID!) { removeUserMatch(userId: $userId, plantId: $plantId) { id - matchedPlants { id name } + matchedPlantIds + } + } +`; + +const MY_MATCHES = ` + query MyMatches($userId: ID!, $sort: String, $limit: Int, $offset: Int) { + myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) { + totalCount + plants { id name } } } `; @@ -36,6 +46,19 @@ async function firstPlants(request: APIRequestContext, limit: number) { return result.data.explorePlants.plants as { id: string; name: string }[]; } +// The names of the plants on one page of My Matches, and the total count +async function myMatchNames( + request: APIRequestContext, + variables: Record, +) { + const result = await graphql(request, MY_MATCHES, variables); + expect(result.errors).toBeUndefined(); + return { + names: result.data.myMatches.plants.map((p: { name: string }) => p.name), + totalCount: result.data.myMatches.totalCount, + }; +} + test.describe("typical use", () => { test("a matched plant is stored and can be removed", async ({ request }) => { const userId = await createUser(request); @@ -46,27 +69,29 @@ test.describe("typical use", () => { userId, plantId: plant.id, }); - expect(added.data.addUserMatch.matchedPlants).toEqual([ - { id: plant.id, name: plant.name }, - ]); + expect(added.data.addUserMatch.matchedPlantIds).toEqual([plant.id]); // Fetches the user again to check that the match is stored in the database const persisted = await graphql(request, GET_USER, { userId }); - expect(persisted.data.getUser.matchedPlants).toEqual([ - { id: plant.id, name: plant.name }, - ]); + expect(persisted.data.getUser.matchedPlantIds).toEqual([plant.id]); + + // My Matches returns the whole plant + expect(await myMatchNames(request, { userId })).toEqual({ + names: ["Aloe Vera"], + totalCount: 1, + }); const removed = await graphql(request, REMOVE_MATCH, { userId, plantId: plant.id, }); - expect(removed.data.removeUserMatch.matchedPlants).toEqual([]); + expect(removed.data.removeUserMatch.matchedPlantIds).toEqual([]); const afterRemove = await graphql(request, GET_USER, { userId }); - expect(afterRemove.data.getUser.matchedPlants).toEqual([]); + expect(afterRemove.data.getUser.matchedPlantIds).toEqual([]); }); - test("matches are returned in the order they were added", async ({ + test("matches are stored in the order they were added", async ({ request, }) => { const userId = await createUser(request); @@ -77,9 +102,68 @@ test.describe("typical use", () => { await graphql(request, ADD_MATCH, { userId, plantId: first.id }); const user = await graphql(request, GET_USER, { userId }); + expect(user.data.getUser.matchedPlantIds).toEqual([second.id, first.id]); + }); +}); + +test.describe("My Matches", () => { + // Three plants matched in the order B, C, A, so that newest, oldest, + // A–Z and Z–A all give a different order + async function userWithThreeMatches(request: APIRequestContext) { + const userId = await createUser(request); + const [a, b, c] = await firstPlants(request, 3); + for (const plant of [b, c, a]) { + await graphql(request, ADD_MATCH, { userId, plantId: plant.id }); + } + return { userId, a: a.name, b: b.name, c: c.name }; + } + + test("sorts by newest, oldest and name", async ({ request }) => { + const { userId, a, b, c } = await userWithThreeMatches(request); + + // Newest first is the default + expect((await myMatchNames(request, { userId })).names).toEqual([a, c, b]); + expect( + (await myMatchNames(request, { userId, sort: "oldest" })).names, + ).toEqual([b, c, a]); expect( - user.data.getUser.matchedPlants.map((p: { name: string }) => p.name), - ).toEqual([second.name, first.name]); + (await myMatchNames(request, { userId, sort: "name_asc" })).names, + ).toEqual([a, b, c]); + expect( + (await myMatchNames(request, { userId, sort: "name_desc" })).names, + ).toEqual([c, b, a]); + }); + + test("returns one page at a time with the total count", async ({ + request, + }) => { + const { userId, a, b, c } = await userWithThreeMatches(request); + + expect(await myMatchNames(request, { userId, limit: 2 })).toEqual({ + names: [a, c], + totalCount: 3, + }); + expect( + await myMatchNames(request, { userId, limit: 2, offset: 2 }), + ).toEqual({ names: [b], totalCount: 3 }); + }); + + test("returns an empty page for a user without matches or an unknown user", async ({ + request, + }) => { + const userId = await createUser(request); + + expect(await myMatchNames(request, { userId })).toEqual({ + names: [], + totalCount: 0, + }); + expect( + await myMatchNames(request, { userId: "000000000000000000000000" }), + ).toEqual({ names: [], totalCount: 0 }); + expect(await myMatchNames(request, { userId: "abc" })).toEqual({ + names: [], + totalCount: 0, + }); }); }); @@ -95,7 +179,7 @@ test.describe("atypical use", () => { }); expect(second.errors).toBeUndefined(); - expect(second.data.addUserMatch.matchedPlants).toHaveLength(1); + expect(second.data.addUserMatch.matchedPlantIds).toEqual([plant.id]); }); test("rejects a plant that does not exist", async ({ request }) => { @@ -134,8 +218,6 @@ test.describe("atypical use", () => { }); expect(result.errors).toBeUndefined(); - expect(result.data.removeUserMatch.matchedPlants).toEqual([ - { id: matched.id, name: matched.name }, - ]); + expect(result.data.removeUserMatch.matchedPlantIds).toEqual([matched.id]); }); }); diff --git a/e2e/apiUserProfile.spec.ts b/e2e/apiUserProfile.spec.ts index 3c12cd5d..9fc67922 100644 --- a/e2e/apiUserProfile.spec.ts +++ b/e2e/apiUserProfile.spec.ts @@ -43,7 +43,7 @@ test.describe("typical use", () => { description: null, profilePicture: "default", preferences: [], - matchedPlants: [], + matchedPlantIds: [], }); }); diff --git a/e2e/helpers/graphql.ts b/e2e/helpers/graphql.ts index 72d12817..ebd6095e 100644 --- a/e2e/helpers/graphql.ts +++ b/e2e/helpers/graphql.ts @@ -12,7 +12,7 @@ export const CREATE_USER = ` description profilePicture preferences - matchedPlants { id name } + matchedPlantIds } } `; @@ -25,7 +25,7 @@ export const GET_USER = ` description profilePicture preferences - matchedPlants { id name } + matchedPlantIds } } `; diff --git a/e2e/uiMatchAndRemovePlant.spec.ts b/e2e/uiMatchAndRemovePlant.spec.ts index b70d6435..f7bf9bbf 100644 --- a/e2e/uiMatchAndRemovePlant.spec.ts +++ b/e2e/uiMatchAndRemovePlant.spec.ts @@ -2,8 +2,8 @@ import { test, expect } from "@playwright/test"; import { openSidebar } from "./helpers/navigation"; // User journeys for matching plants: from PlantMatch and from ExplorePlants, -// and that matches show up in MyMatches and can be removed from both MyMatches -// and ExplorePlants. +// that matches show up in MyMatches and can be removed from both MyMatches +// and ExplorePlants, and that MyMatches can be sorted and paged. // Each test gets a new browser and therefore a new user with no matches. test("user can like a plant in PlantMatch, find it in MyMatches and remove the match", async ({ @@ -71,3 +71,54 @@ test("user can add a plant from ExplorePlants, find it in MyMatches and remove i await page.locator('a[href$="/my-matches"]').click(); await expect(matchCards).toHaveCount(0); }); + +test("user can sort the matches in MyMatches and move between pages", async ({ + page, +}) => { + // Matches the 12 plants on the first Explore page (Aloe Vera first) and then + // the first plant on the second page (Monstera), so MyMatches gets 2 pages + await page.goto("#/explorePlants"); + const exploreCards = page.locator(".plant-grid > li"); + await expect(exploreCards).toHaveCount(12); + for (let i = 0; i < 12; i++) { + const button = exploreCards.nth(i).locator(".add-match-button"); + await button.click(); + await expect(button).toHaveClass(/add-match-button--matched/); + } + await page.locator(".pagination").getByRole("button").last().click(); + await expect(exploreCards.first()).toContainText("Monstera"); + const lastButton = exploreCards.first().locator(".add-match-button"); + await lastButton.click(); + await expect(lastButton).toHaveClass(/add-match-button--matched/); + + await openSidebar(page); + await page.locator('a[href$="/my-matches"]').click(); + const matchCards = page.locator(".plant-card-match"); + + // 13 matches: the count, and 12 on the first page with the newest first + await expect(page.locator(".my-matches-count")).toContainText("13"); + await expect(matchCards).toHaveCount(12); + await expect(matchCards.first()).toContainText("Monstera"); + + // The second page has the oldest match + await page.locator(".pagination").getByRole("button").last().click(); + await expect(matchCards).toHaveCount(1); + await expect(matchCards.first()).toContainText("Aloe Vera"); + + // Sorting A–Z goes back to page 1 (option 3: newest, oldest, A–Z, Z–A) + await page.locator(".sort-button").click(); + await page.locator(".sort-option").nth(2).click(); + await expect(matchCards).toHaveCount(12); + await expect(matchCards.first()).toContainText("Aloe Vera"); + + // The sort order is remembered when going to another page and back + await openSidebar(page); + await page.locator('a[href$="/explorePlants"]').click(); + await openSidebar(page); + await page.locator('a[href$="/my-matches"]').click(); + await expect(matchCards.first()).toContainText("Aloe Vera"); + + // ... and after a reload + await page.reload(); + await expect(matchCards.first()).toContainText("Aloe Vera"); +}); diff --git a/frontend/src/components/sortMenu/SortMenu.css b/frontend/src/components/sortMenu/SortMenu.css index 4513cddd..c5b6bf27 100644 --- a/frontend/src/components/sortMenu/SortMenu.css +++ b/frontend/src/components/sortMenu/SortMenu.css @@ -9,9 +9,12 @@ gap: 0.5rem; height: 40px; padding: 0 0.75rem; + /* The same width on every page, so the button is easy to recognise. + It still grows if a label is longer. */ + min-width: 13rem; border: 1px solid var(--dark-pink); border-radius: 8px; - background-color: var(--light-pink); + background-color: var(--light-background); color: var(--text-dark); font-family: var(--font-ui); font-size: 15px; diff --git a/frontend/src/context/userQueries.ts b/frontend/src/context/userQueries.ts index 790921a9..757e8c14 100644 --- a/frontend/src/context/userQueries.ts +++ b/frontend/src/context/userQueries.ts @@ -10,16 +10,7 @@ const USER_FIELDS = gql` description profilePicture preferences - matchedPlants { - id - name - imageURL - scientificName - description - watering - sunlight - careLevel - } + matchedPlantIds } `; @@ -32,6 +23,26 @@ export const GET_USER = gql` ${USER_FIELDS} `; +// One page of the user's matched plants, sorted. Only My Matches uses this, +// so the other pages don't have to fetch the whole plants with images. +export const MY_MATCHES = gql` + query MyMatches($userId: ID!, $sort: String, $limit: Int, $offset: Int) { + myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) { + totalCount + plants { + id + name + imageURL + scientificName + description + watering + sunlight + careLevel + } + } + } +`; + export const CREATE_USER = gql` mutation CreateUser { createUser { @@ -96,10 +107,13 @@ export type User = { description: string | null; profilePicture: string; preferences: string[]; - matchedPlants: Plant[]; + matchedPlantIds: string[]; }; export type GetUserData = { getUser: User | null }; +export type MyMatchesData = { + myMatches: { totalCount: number; plants: Plant[] }; +}; export type CreateUserData = { createUser: User }; export type AddUserMatchData = { addUserMatch: User | null }; export type RemoveUserMatchData = { removeUserMatch: User | null }; diff --git a/frontend/src/hooks/useExploreParams.ts b/frontend/src/hooks/useExploreParams.ts index c2347bfc..2055ab97 100644 --- a/frontend/src/hooks/useExploreParams.ts +++ b/frontend/src/hooks/useExploreParams.ts @@ -1,4 +1,4 @@ -import { useSearchParams } from "react-router-dom"; +import { useUrlParams } from "./useUrlParams"; // The filters on Explore Plants, as they are named in the URL export type FilterParam = "watering" | "sunlight" | "careLevel"; @@ -9,32 +9,7 @@ const DEFAULT_SORT = "name_asc"; // so it survives refresh and can be shared as a link. The page only gets the // values and functions to change them, and does not need to know about the URL. export function useExploreParams() { - const [searchParams, setSearchParams] = useSearchParams(); - - const get = (key: string) => searchParams.get(key) ?? ""; - - // A missing or invalid page number (e.g. "abc" or "0") means page 1 - const parsedPage = Number.parseInt(get("page"), 10); - const page = Number.isInteger(parsedPage) && parsedPage > 0 ? parsedPage : 1; - - // Sets the given parameters, and removes the ones that are empty or null. - // replace: true, so changing a filter does not add a new step to the browser history. - const update = (updates: Record) => { - setSearchParams( - (currentParams) => { - const nextParams = new URLSearchParams(currentParams); - Object.entries(updates).forEach(([key, value]) => { - if (value) { - nextParams.set(key, value); - } else { - nextParams.delete(key); - } - }); - return nextParams; - }, - { replace: true }, - ); - }; + const { get, page, update } = useUrlParams(); return { search: get("search"), diff --git a/frontend/src/hooks/useMatchedPlants.ts b/frontend/src/hooks/useMatchedPlants.ts index f27d8e43..a1150583 100644 --- a/frontend/src/hooks/useMatchedPlants.ts +++ b/frontend/src/hooks/useMatchedPlants.ts @@ -8,15 +8,26 @@ import { } from "../context/userQueries"; import type { Plant } from "../types/Plant"; +// My Matches is fetched again after a match is added or removed, so the list +// there is always up to date, whichever page the change was made on +const refetchMyMatches = { refetchQueries: ["MyMatches"] }; + export function useMatchedPlants() { const { userId, user, loading } = useUser(); - const [addUserMatch] = useMutation(ADD_USER_MATCH); - const [removeUserMatch] = useMutation(REMOVE_USER_MATCH); + const [addUserMatch] = useMutation( + ADD_USER_MATCH, + refetchMyMatches, + ); + const [removeUserMatch] = useMutation( + REMOVE_USER_MATCH, + refetchMyMatches, + ); - const matches = user?.matchedPlants ?? []; + // Only the ids, which is all a page needs to show whether a plant is matched + const matchedPlantIds = user?.matchedPlantIds ?? []; const addMatch = (plant: Plant) => { - if (!userId || matches.some((m) => m.id === plant.id)) return; + if (!userId || matchedPlantIds.includes(plant.id)) return; addUserMatch({ variables: { userId, plantId: plant.id } }); }; @@ -25,5 +36,5 @@ export function useMatchedPlants() { removeUserMatch({ variables: { userId, plantId: id } }); }; - return { matches, loading, addMatch, removeMatch } as const; + return { matchedPlantIds, loading, addMatch, removeMatch } as const; } diff --git a/frontend/src/hooks/useUrlParams.ts b/frontend/src/hooks/useUrlParams.ts new file mode 100644 index 00000000..aae6f362 --- /dev/null +++ b/frontend/src/hooks/useUrlParams.ts @@ -0,0 +1,34 @@ +import { useSearchParams } from "react-router-dom"; + +// Shared helpers for keeping a page's state in the URL, used by +// useExploreParams. Kept separate so other pages can use the URL the same way later. +export function useUrlParams() { + const [searchParams, setSearchParams] = useSearchParams(); + + const get = (key: string) => searchParams.get(key) ?? ""; + + // A missing or invalid page number (e.g. "abc" or "0") means page 1 + const parsedPage = Number.parseInt(get("page"), 10); + const page = Number.isInteger(parsedPage) && parsedPage > 0 ? parsedPage : 1; + + // Sets the given parameters, and removes the ones that are empty or null. + // replace: true, so a change does not add a new step to the browser history. + const update = (updates: Record) => { + setSearchParams( + (currentParams) => { + const nextParams = new URLSearchParams(currentParams); + Object.entries(updates).forEach(([key, value]) => { + if (value) { + nextParams.set(key, value); + } else { + nextParams.delete(key); + } + }); + return nextParams; + }, + { replace: true }, + ); + }; + + return { get, page, update }; +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 1b27ba93..b3a4f046 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -81,7 +81,14 @@ "myMatchesPage": { "loading": "Loading your matches...", "noMatches": "You have no matches yet. Press the flower on the match page to match with a plant.", - "removeMatch": "Remove the match" + "removeMatch": "Remove the match", + "matchCount_one": "You have {{count}} match", + "matchCount_other": "You have {{count}} matches", + "sort": "Sort", + "newest": "Newest first", + "oldest": "Oldest first", + "name_asc": "Name (A-Z)", + "name_desc": "Name (Z-A)" }, "profile": { "name": "Name Surname", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index 6696bc25..0cb98629 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -81,7 +81,14 @@ "myMatchesPage": { "loading": "Laster matchene dine...", "noMatches": "Du har ingen matcher ennå. Trykk på blomsten på match-siden for å matche med en plante.", - "removeMatch": "Fjern matchen" + "removeMatch": "Fjern matchen", + "matchCount_one": "Du har {{count}} match", + "matchCount_other": "Du har {{count}} matches", + "sort": "Sorter", + "newest": "Nyeste først", + "oldest": "Eldste først", + "name_asc": "Navn (A-Z)", + "name_desc": "Navn (Z-A)" }, "profile": { "name": "Navn Etternavn", diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 6708c527..8f8ad395 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -14,9 +14,9 @@ const client = new ApolloClient({ typePolicies: { User: { fields: { - // The backend always returns the whole list of matches, so the new - // list should replace the old one in the cache, not be merged with it - matchedPlants: { merge: false }, + // The backend always returns the whole list of matched ids, so the + // new list should replace the old one in the cache, not be merged with it + matchedPlantIds: { merge: false }, }, }, }, diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index eb6b1a4d..897cada7 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -56,7 +56,7 @@ export default function ExplorePlants() { const debouncedSearch = useDebounce(search, 300); // Matches come from the user in the database, so every page sees the same list - const { matches, addMatch, removeMatch } = useMatchedPlants(); + const { matchedPlantIds, addMatch, removeMatch } = useMatchedPlants(); const { data, loading, error } = useQuery(EXPLORE_PLANTS, { variables: { @@ -145,7 +145,7 @@ export default function ExplorePlants() {
    {plants.map((plant) => { // The button adds the plant to My Matches, or removes it if it is already there - const isMatched = matches.some((match) => match.id === plant.id); + const isMatched = matchedPlantIds.includes(plant.id); const matchLabel = isMatched ? t("ExplorePlants.removeMatch") : t("ExplorePlants.addMatch"); diff --git a/frontend/src/pages/myMatches/MyMatchesPage.css b/frontend/src/pages/myMatches/MyMatchesPage.css index b9438cc1..2073326e 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.css +++ b/frontend/src/pages/myMatches/MyMatchesPage.css @@ -11,6 +11,27 @@ gap: 30px; } +/* The number of matches and the sort menu, on one line above the plants */ +.my-matches-header { + grid-column: 1 / -1; + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: 1rem; +} + +.my-matches-header .sort-menu { + align-self: center; +} + +/* Same style as the number of results on Explore Plants */ +.my-matches-count { + margin: 0; + font-size: 1.25rem; + color: var(--text-dark); +} + .matches-grid { display: grid; grid-template-columns: repeat( @@ -31,7 +52,6 @@ margin: 0; text-align: center; font-size: 20px; - text-align: center; } .plant-card-match { diff --git a/frontend/src/pages/myMatches/MyMatchesPage.tsx b/frontend/src/pages/myMatches/MyMatchesPage.tsx index 33aec4cd..d73b34eb 100644 --- a/frontend/src/pages/myMatches/MyMatchesPage.tsx +++ b/frontend/src/pages/myMatches/MyMatchesPage.tsx @@ -1,23 +1,89 @@ +import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; +import { useQuery } from "@apollo/client/react"; import "./MyMatchesPage.css"; import PlantCard from "../../components/plantCard/PlantCard.tsx"; +import Pagination from "../../components/pagination/Pagination.tsx"; +import SortMenu from "../../components/sortMenu/SortMenu.tsx"; import { useMatchedPlants } from "../../hooks/useMatchedPlants.ts"; +import { useSessionState } from "../../hooks/useSessionState.ts"; +import { useUser } from "../../context/UserContext"; +import { MY_MATCHES, type MyMatchesData } from "../../context/userQueries"; + +const PAGE_SIZE = 12; + +const SORT_OPTIONS = ["newest", "oldest", "name_asc", "name_desc"]; function MyMatchesPage() { const { t } = useTranslation(); + const { userId, loading: userLoading } = useUser(); + const { removeMatch } = useMatchedPlants(); + + // The sort order is remembered for the session, also when the user goes to + // another page and back. The page always starts at 1, so new matches, which + // come first with the newest first, are seen right away. + const [sort, setSortState] = useSessionState("myMatches.sort", "newest"); + const [page, setPage] = useState(1); + + // A new sort order goes back to page 1 + const setSort = (value: string) => { + setSortState(value); + setPage(1); + }; + + const { data, loading: matchesLoading } = useQuery( + MY_MATCHES, + { + variables: { + userId, + sort, + limit: PAGE_SIZE, + offset: (page - 1) * PAGE_SIZE, + }, + skip: !userId, + // Fetch again every time the page is opened, since matches can be + // added on other pages. The cached list is shown in the meantime. + fetchPolicy: "cache-and-network", + }, + ); - const { matches, loading, removeMatch } = useMatchedPlants(); + const plants = data?.myMatches.plants ?? []; + const totalCount = data?.myMatches.totalCount ?? 0; + const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE)); + // Only show the loading text when there is nothing to show yet + const loading = userLoading || (matchesLoading && !data); + + // If the last plant on the last page is removed, or the URL points to a page + // that does not exist, go to the last page that has plants + useEffect(() => { + if (totalCount > 0 && page > totalPages) setPage(totalPages); + }, [totalCount, page, totalPages, setPage]); return (
    - {/* Without the loading check, "no matches" flashes while the user is fetched */} - {loading &&

    {t("myMatchesPage.loading")}

    } - {!loading && matches.length === 0 && ( -

    {t("myMatchesPage.noMatches")}

    + {/* Without the loading check, "no matches" flashes while the matches are fetched */} + {totalCount > 0 && ( +
    + {/* aria-live so screen readers hear the new count when a match is removed */} +

    + {t("myMatchesPage.matchCount", { count: totalCount })} +

    + ({ + value: option, + label: t(`myMatchesPage.${option}`), + }))} + onChange={setSort} + /> +
    )} + {loading &&

    {t("myMatchesPage.loading")}

    } + {!loading && totalCount === 0 &&

    {t("myMatchesPage.noMatches")}

    } - {matches.map((plant) => ( + {plants.map((plant) => (
    + + {totalCount > 0 && ( + + )}
    ); } diff --git a/frontend/src/tests/ExplorePage.test.tsx b/frontend/src/tests/ExplorePage.test.tsx index e2fa1786..67363b40 100644 --- a/frontend/src/tests/ExplorePage.test.tsx +++ b/frontend/src/tests/ExplorePage.test.tsx @@ -33,7 +33,7 @@ vi.mock("../components/plantCard/PlantCard", () => ({ // Tests can set `matches` to decide which plants are already matched. const { matchedPlants } = vi.hoisted(() => ({ matchedPlants: { - matches: [] as { id: string }[], + matchedPlantIds: [] as string[], addMatch: vi.fn(), removeMatch: vi.fn(), }, @@ -138,7 +138,7 @@ describe("ExplorePlants", () => { beforeEach(() => { // shouldAdvanceTime keeps userEvent and findBy* from hanging with fake timers vi.useFakeTimers({ shouldAdvanceTime: true }); - matchedPlants.matches = []; + matchedPlants.matchedPlantIds = []; matchedPlants.addMatch.mockReset(); matchedPlants.removeMatch.mockReset(); }); @@ -516,7 +516,7 @@ describe("ExplorePlants", () => { }); it("removes a plant that is already matched", async () => { - matchedPlants.matches = [{ id: "Plant-1" }]; + matchedPlants.matchedPlantIds = ["Plant-1"]; const { user } = setup([mockResponse({})]); await screen.findAllByTestId("plant-card"); diff --git a/frontend/src/tests/MyMatchesPage.test.tsx b/frontend/src/tests/MyMatchesPage.test.tsx index 553be19d..5e05659c 100644 --- a/frontend/src/tests/MyMatchesPage.test.tsx +++ b/frontend/src/tests/MyMatchesPage.test.tsx @@ -1,14 +1,17 @@ -import { fireEvent, render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { beforeEach, describe, it, expect, vi } from "vitest"; import MyMatchesPage from "../pages/myMatches/MyMatchesPage"; import type { Plant } from "../types/Plant"; -const { removeUserMatch, useUser } = vi.hoisted(() => ({ +const { removeUserMatch, useQuery, useUser } = vi.hoisted(() => ({ removeUserMatch: vi.fn(), + useQuery: vi.fn(), useUser: vi.fn(), })); vi.mock("@apollo/client/react", () => ({ useMutation: () => [removeUserMatch], + useQuery, })); vi.mock("../context/UserContext", () => ({ useUser })); vi.mock("react-i18next", () => ({ @@ -28,7 +31,8 @@ const orchid: Plant = { careLevel: "Easy", }; -function mockUser(matchedPlants: Plant[], loading = false) { +// A loaded user. userLoading is true while the user itself is being fetched. +function mockUser(userLoading = false) { useUser.mockReturnValue({ userId: "user-1", user: { @@ -37,44 +41,167 @@ function mockUser(matchedPlants: Plant[], loading = false) { description: null, profilePicture: "default", preferences: [], - matchedPlants, + matchedPlantIds: [], }, - loading, + loading: userLoading, }); } +// What the myMatches query returns. Without plants, the query is still loading. +// totalCount can be higher than the plants on the page, to test pagination. +function mockMatches(plants: Plant[] | null, totalCount = plants?.length ?? 0) { + useQuery.mockReturnValue( + plants + ? { data: { myMatches: { totalCount, plants } }, loading: false } + : { data: undefined, loading: true }, + ); +} + +// The variables the page sent with its last myMatches query +const lastVariables = () => useQuery.mock.lastCall?.[1].variables; + +const nextPage = () => screen.getByRole("button", { name: "pagination.next" }); + beforeEach(() => { removeUserMatch.mockClear(); + useQuery.mockReset(); + sessionStorage.clear(); + mockUser(); }); describe("myMatchesPage", () => { - it("shows a message when there are no matches", () => { - mockUser([]); - render(); + describe("loading and empty state", () => { + it("shows a message when there are no matches, without the count, sorting or pages", () => { + mockMatches([]); + render(); - expect(screen.getByText("myMatchesPage.noMatches")).toBeInTheDocument(); + expect(screen.getByText("myMatchesPage.noMatches")).toBeInTheDocument(); + expect( + screen.queryByText("myMatchesPage.matchCount"), + ).not.toBeInTheDocument(); + expect(screen.queryByRole("navigation")).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: /myMatchesPage.sort/ }), + ).not.toBeInTheDocument(); + }); + + it("shows the loading state instead of the no matches message", () => { + mockMatches(null); + render(); + + expect(screen.getByText("myMatchesPage.loading")).toBeInTheDocument(); + expect( + screen.queryByText("myMatchesPage.noMatches"), + ).not.toBeInTheDocument(); + }); + + it("shows the loading state while the user is being fetched", () => { + mockUser(true); + mockMatches([]); + render(); + + expect(screen.getByText("myMatchesPage.loading")).toBeInTheDocument(); + }); }); - it("shows the loading state instead of the no matches message", () => { - mockUser([], true); - render(); + describe("fetching the matches", () => { + it("fetches the first page, newest first, and again each time the page is opened", () => { + mockMatches([]); + render(); + + expect(useQuery.mock.lastCall?.[1]).toMatchObject({ + variables: { userId: "user-1", sort: "newest", limit: 12, offset: 0 }, + skip: false, + fetchPolicy: "cache-and-network", + }); + }); + + it("uses the sort order saved earlier in the session, and starts on page 1", () => { + sessionStorage.setItem("myMatches.sort", "oldest"); + mockMatches([orchid], 30); + render(); + + expect(lastVariables()).toMatchObject({ sort: "oldest", offset: 0 }); + }); + + it("shows the saved matches and removes one", () => { + mockMatches([orchid]); + render(); - expect(screen.getByText("myMatchesPage.loading")).toBeInTheDocument(); - expect( - screen.queryByText("myMatchesPage.noMatches"), - ).not.toBeInTheDocument(); + expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); + fireEvent.click( + screen.getByRole("button", { name: "myMatchesPage.removeMatch" }), + ); + expect(removeUserMatch).toHaveBeenCalledWith({ + variables: { userId: "user-1", plantId: "1" }, + }); + }); }); - it("shows the saved matches and removes one", () => { - mockUser([orchid]); - render(); + describe("sorting and pages", () => { + it("shows the number of matches next to the sort menu", () => { + mockMatches([orchid], 30); + render(); + + expect(screen.getByText("myMatchesPage.matchCount")).toHaveAttribute( + "aria-live", + "polite", + ); + expect( + screen.getByRole("button", { + name: "myMatchesPage.sort: myMatchesPage.newest", + }), + ).toBeInTheDocument(); + }); + + it("moves to another page with the page navigation", async () => { + const user = userEvent.setup(); + // 30 matches with 12 per page gives 3 pages + mockMatches([orchid], 30); + render(); + + await user.click(nextPage()); + + expect(lastVariables()).toMatchObject({ offset: 12 }); + }); + + it("saves a new sort order for the session and goes back to page 1", async () => { + const user = userEvent.setup(); + mockMatches([orchid], 30); + render(); + await user.click(nextPage()); + expect(lastVariables()).toMatchObject({ offset: 12 }); + + await user.click( + screen.getByRole("button", { + name: "myMatchesPage.sort: myMatchesPage.newest", + }), + ); + await user.click( + screen.getByRole("button", { name: "myMatchesPage.name_asc" }), + ); + + expect(lastVariables()).toMatchObject({ sort: "name_asc", offset: 0 }); + expect(sessionStorage.getItem("myMatches.sort")).toBe("name_asc"); + }); + + it("goes to the last page when the current page no longer exists", async () => { + const user = userEvent.setup(); + // 30 matches give 3 pages. Go to page 3. + mockMatches([orchid], 30); + const { rerender } = render(); + await user.click(nextPage()); + await user.click(nextPage()); + expect(lastVariables()).toMatchObject({ offset: 24 }); + + // Now there are only 13 matches, for example after plants were removed, + // so there are only 2 pages + mockMatches([orchid], 13); + rerender(); - expect(screen.getAllByText("Orchid").length).toBeGreaterThan(0); - fireEvent.click( - screen.getByRole("button", { name: "myMatchesPage.removeMatch" }), - ); - expect(removeUserMatch).toHaveBeenCalledWith({ - variables: { userId: "user-1", plantId: "1" }, + await waitFor(() => + expect(lastVariables()).toMatchObject({ offset: 12 }), + ); }); }); }); diff --git a/frontend/src/tests/PlantMatchPage.test.tsx b/frontend/src/tests/PlantMatchPage.test.tsx index 55346d0f..b4c84aba 100644 --- a/frontend/src/tests/PlantMatchPage.test.tsx +++ b/frontend/src/tests/PlantMatchPage.test.tsx @@ -63,7 +63,7 @@ function mockUser(preferences: string[] = []) { description: null, profilePicture: "default", preferences, - matchedPlants: [], + matchedPlantIds: [], }, loading: false, }); diff --git a/frontend/src/tests/PlantOwnerTest.test.tsx b/frontend/src/tests/PlantOwnerTest.test.tsx index c633919d..1b11bc50 100644 --- a/frontend/src/tests/PlantOwnerTest.test.tsx +++ b/frontend/src/tests/PlantOwnerTest.test.tsx @@ -27,7 +27,7 @@ function mockUser(profilePicture = "default") { description: null, profilePicture, preferences: [], - matchedPlants: [], + matchedPlantIds: [], }, loading: false, }); diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/Profile.test.tsx index b07f0e59..f9973eb9 100644 --- a/frontend/src/tests/Profile.test.tsx +++ b/frontend/src/tests/Profile.test.tsx @@ -36,7 +36,7 @@ describe("Profile page", () => { description: null, profilePicture, preferences: [], - matchedPlants: [], + matchedPlantIds: [], }, loading: false, }); diff --git a/frontend/src/tests/UserContext.test.tsx b/frontend/src/tests/UserContext.test.tsx index 969ad942..e8d9e375 100644 --- a/frontend/src/tests/UserContext.test.tsx +++ b/frontend/src/tests/UserContext.test.tsx @@ -16,7 +16,7 @@ function makeUser(id: string, name: string | null = null) { description: null, profilePicture: "default", preferences: [], - matchedPlants: [], + matchedPlantIds: [], }; }