diff --git a/README.md b/README.md
index 0d2f96aa..a9af8502 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,7 @@ http://it2810-03.idi.ntnu.no/project2/
- **Plant Match:** Plants matching the most preferences come first, otherwise the order is random. The deck is kept while the user visits other pages, so they can continue where they left off.
- **My Matches:** Collects liked plants from both Plant Match and Explore Plants. The user only stores plant ids, and the list is fetched one page at a time, so responses do not grow with the number of matches.
- **Explore Plants:** Search, filtering, sorting and pagination run in the backend, so the frontend only receives one page at a time, whatever the size of the collection. The state is kept in the URL, so a view survives a refresh and can be shared as a link. Each filter value shows how many plants it would give, and values that would give none can't be chosen, so filtering never ends in an empty list.
+- **Plant Owner Test:** Four questions give one of six plant owner types, whose picture can be used as profile picture. The result also suggests one preference each for watering, light and care level, based on the answers and the description of the type. The user chooses which of them to add, and they are added to the preferences they already have, so PlantMatch puts plants that suit them first right away.
- **Walkthrough:** A short guide opens on the first visit and explains what the user can do on each page. It can be reopened at any time with the ? button, starts at the current page (or at the welcome step on the home page), links to each page and lets the user change language without closing it.
## Tech stack
diff --git a/docs/architecture.md b/docs/architecture.md
index d6571ab8..baf05d3e 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -40,20 +40,27 @@ 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 preference-ranked plants (`getPlants`) and match with them |
- | `/explorePlants` | `ExplorePlantsPage` | Search, filter, sort and paginate all plants (`explorePlants`) |
- | `/myMatches` | `MyMatchesPage` | List, sort, paginate and remove the user's matches (`myMatches`) |
- | `/profile` | `ProfilePage` | Edit name, description, profile picture and preferences |
- | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture |
- | `*` | `NotFoundPage` | 404 page for unknown paths, with a link back to Plant Match |
+ | Route | Page | Purpose |
+ | ----------------- | -------------------- | ------------------------------------------------------------------------------------ |
+ | `/` | `PlantMatchPage` | Swipe through preference-ranked plants (`getPlants`) and match with them |
+ | `/explorePlants` | `ExplorePlantsPage` | Search, filter, sort and paginate all plants (`explorePlants`) |
+ | `/myMatches` | `MyMatchesPage` | List, sort, paginate and remove the user's matches (`myMatches`) |
+ | `/profile` | `ProfilePage` | Edit name, description, profile picture and preferences |
+ | `/plantOwnerTest` | `PlantOwnerTestPage` | A quiz whose result can be set as the profile picture, and that suggests preferences |
+ | `*` | `NotFoundPage` | 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. The user queries and mutations themselves live in `graphql/user/` (see [GraphQL operations](#graphql-operations-in-the-frontend)).
- **Error messages:** `ErrorMessageProvider` (`context/ErrorMessageContext.tsx`) wraps the app and makes `showError()` available through `useErrorMessage()`. `useMatchedPlants` uses it to show an error message when adding or removing a match fails.
- **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.
- `usePlantDeck` keeps the remaining Plant Match cards in `sessionStorage` while the user visits another page. It sends the saved preferences with each batch, and changing the preferences clears the current deck and fetches a new first batch so the order reflects the new preferences. Stale responses from the previous deck are ignored.
- **Reusable components:** Shared UI is kept in `components/`. `Pagination` shows previous/next and numbered pages, `FilterSelect` is a labelled dropdown for one filter, and `SortMenu` is a sort button with a menu that can be used with the keyboard. `MatchButton` adds a plant to My Matches (✿) or removes it (✖), `ErrorMessage` shows a short error message, and `LanguageSwitcher` is used both in the sidebar and in the walkthrough. The components take already translated texts, so they can be used on other pages.
+- **Plant Owner Test:** The questions, results and suggestions are data in `pages/plantOwnerTest/plantOwnerTest.ts`, so the page only shows them. `getPlantOwnerResult()` gives the result from the location and watering answers. `getSuggestedPreferences()` gives three preference ids from the answers and the result:
+ - **Watering** from the result: the minimalists get `minimumWater`, the average gardeners `averageWater`, and the dreaming city gardener and the garden expert `frequentWater`.
+ - **Light** from the light answer. There is no preference for partial sun, so it suggests `partShade`, since those plants are listed as "part sun/part shade" in the data and match the part shade preference.
+ - **Care level** from the result where its description says something about care: `easyCare` for the minimalists ("hardy plants") and `hardCare` for the dreaming city gardener and the garden expert ("a lot of attention"). The average gardeners get it from the time answer (10 minutes: `easyCare`, 30 minutes or 1 hour: `mediumCare`, 1 day: `hardCare`).
+
+ `SuggestedPreferences.tsx` shows the suggestions that the user does not already have as toggle buttons, all chosen from the start. Nothing is saved until the user clicks "Add to my preferences", which runs `updateUserPreferences` with the saved preferences plus the chosen suggestions, so no preference is removed. It uses an optimistic response like the buttons on the profile page, so the profile and Plant Match are updated at once. The suggestions are shown above "Use as profile picture", since that button takes the user to the profile page.
+
- **Walkthrough:** The guide for new users is in `components/walkthrough/`, and is made up of three parts:
- **The steps are data:** `walkthroughSteps.ts` lists the steps in order. Each step has an `id`, a picture (one of the avatars) and, if it is about a page, the `route` of that page. The texts are in the translation files under `walkthrough.steps.`. A step can also have a `mobileHint`, a sentence that is only shown on small screens, such as how to open the menu with ☰, since the sidebar is always visible on large screens. It is hidden with CSS at the same breakpoint as the sidebar. A new step therefore only needs one line in the list and a title and text in each language. `stepForPath()` finds the step for the current page.
- **`App.tsx` decides when it is open:** The walkthrough opens by itself when `walkthroughSeen` is not in `localStorage`, and the key is set when it is closed, so it is only shown once. The ? button in the `Header` opens it again at the step for the current page (`stepForPath`). When it closes, focus goes back to the ? button, except when the "Go to" link has moved the user to another page, where focus moves to the start of the new page like for any other navigation.
@@ -312,7 +319,7 @@ T03-Project-2/
│ │ │ ├── myMatches/ # MyMatchesPage
│ │ │ ├── notFound/ # NotFoundPage
│ │ │ ├── plantMatch/ # PlantMatchPage
-│ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, and plantOwnerTest.ts with the questions and results
+│ │ │ ├── plantOwnerTest/ # PlantOwnerTestPage, SuggestedPreferences, and plantOwnerTest.ts with the questions, results and suggestions
│ │ │ └── profile/ # ProfilePage
│ │ ├── tests/ # Unit and component tests, including test setup (see tests.md)
│ │ ├── types/ # Shared TypeScript types (Plant, User, Preference)
diff --git a/docs/tests.md b/docs/tests.md
index 1da5243c..d5f8b3a5 100644
--- a/docs/tests.md
+++ b/docs/tests.md
@@ -154,7 +154,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are only used for small co
- Preferences and edge cases: the user's saved preferences are sent with the request so the best matches come first, changing preferences starts a new deck with the updated ordering, also when they were changed on the profile page while PlantMatch was closed (the saved deck remembers which preferences it was sorted by), nothing is fetched before the user has loaded, and the end card with disabled buttons is shown when there are no plants at all.
- `PlantOwnerTestPage.test.tsx`
- The result for all six combinations of answers, and that the time and light answers do not change it.
+ - The suggested preferences for every result: watering and, for the minimalists and the plant lovers, care level from the result, care level from the time answer for the average gardeners, and partial sun suggesting part shade.
- Going on is only possible with an answer, an earlier answer is shown when going back, the result is shown with its picture, the result can be saved as profile picture, an error is shown when saving fails, the page says so when the result already is the profile picture, and the test can be taken again with no answers.
+ - Suggested preferences: all are chosen from the start, those already saved are not suggested again, the chosen ones are added to the saved preferences, nothing is saved before the user clicks the add button (which is disabled when nothing is chosen), the page says so when all suggestions already are preferences, an error is shown when saving fails or the user is not found, and saving can be tried again.
- `PlantPreferences.test.tsx`
- Saved preferences are marked, also with `aria-pressed` for screen readers, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists.
- `ProfilePage.test.tsx`
@@ -230,19 +232,20 @@ Other choices in the config:
#### Scenarios
-Each file covers one scenario. Most features have both an API test and a UI test. The **API tests** check the backend logic over HTTP, including atypical input that is hard to reach through the UI. The **UI tests** check that the frontend is correctly connected to the backend and that the user journeys work from start to finish. Some UI tests have no API test of their own: accessibility and pictures are only about the frontend, and saving preferences is already covered by `apiUserProfile`, while the order of the plants is tested in the backend tests.
+Each file covers one scenario. Most features have both an API test and a UI test. The **API tests** check the backend logic over HTTP, including atypical input that is hard to reach through the UI. The **UI tests** check that the frontend is correctly connected to the backend and that the user journeys work from start to finish. Some UI tests have no API test of their own: accessibility and pictures are only about the frontend, and saving preferences, also from the plant owner test, is already covered by `apiUserProfile`, while the order of the plants is tested in the backend tests.
The UI tests find elements the way a user or a screen reader would: by role, label and accessible name (`getByRole`, `getByLabel`), not by CSS classes or ids. A test then only breaks when something changes that the user notices, not when the styling is refactored, and an element without an accessible name cannot be found, so the tests also check that the controls are labelled. The app can run in Norwegian and English, so the names are written once in both languages in `e2e/helpers/names.ts`. Elements without a natural role, such as the plant cards in a list, the avatar pictures (decorative, `alt=""`) and the placeholder picture (a CSS background), have a `data-testid`.
-| Feature | API test | UI test |
-| ------------------------------------------ | ------------------------ | ----------------------- |
-| Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` |
-| Profile and avatar | `apiUserProfile` | `uiUserProfile` |
-| Matching, removing, sorting and paging | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` |
-| Accessibility on all pages | – | `uiAccessibility` |
-| Pictures load | – | `uiImages` |
-| Preferences decide the order in PlantMatch | – | `uiPreferences` |
-| Walkthrough | – | `uiWalkthrough` |
+| Feature | API test | UI test |
+| --------------------------------------------- | ------------------------ | ----------------------- |
+| Search, filter, sort, pagination, details | `apiExplorePlants` | `uiExplorePlants` |
+| Profile and avatar | `apiUserProfile` | `uiUserProfile` |
+| Matching, removing, sorting and paging | `apiMatchAndRemovePlant` | `uiMatchAndRemovePlant` |
+| Accessibility on all pages | – | `uiAccessibility` |
+| Pictures load | – | `uiImages` |
+| Preferences decide the order in PlantMatch | – | `uiPreferences` |
+| Walkthrough | – | `uiWalkthrough` |
+| Preferences suggested by the plant owner test | – | `uiPlantOwnerTest` |
**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.
@@ -256,6 +259,15 @@ The test user has no preferences, so PlantMatch shows the plants in random order
**Preferences (`uiPreferences`):** the core feature of the app, from start to finish. A new user lands on PlantMatch, the start page, where the order is random. The user then chooses three preferences on the profile page, and back on PlantMatch the deck starts over with a plant that matches all three, which the card also says to screen readers on each matching chip. The order and the marked chips are the same after a reload, so the preferences are stored in the database and the deck in `sessionStorage`. When the user changes the preferences, PlantMatch starts over with the plant that matches the new ones. The test data has only one or two plants that match each set of preferences, so the expected plants are known. The other UI tests use a new user without preferences, where PlantMatch is random.
+**Plant owner test (`uiPlantOwnerTest`):** the user takes the test from the sidebar with answers that give "Average country gardener", which suggests average watering, part shade and medium care, all chosen from the start.
+
+- The user leaves out part shade and adds the others. The test waits for the request that saves exactly `averageWater` and `mediumCare` and checks that `partShade` is not in it, and the page says that the preferences were added.
+- On the profile page, average watering and medium care are chosen and part shade is not, also after a reload, so the preferences are stored in the database.
+- Taking the test again only suggests part shade, since the others are saved. Adding it keeps the saved preferences, and when all three are saved, the next result says so instead of showing the add button.
+- A second test takes the test without adding anything, and checks that no preferences are sent to the backend and none are chosen on the profile page.
+
+Saving preferences is already covered by `apiUserProfile`, and how preferences decide the order in PlantMatch by `uiPreferences`, so the test does not have an API test of its own.
+
**Profile (`uiUserProfile`):** changing name, description and avatar is shown at once and is still there after a reload, so the changes are stored in the database.
Saving the profile is debounced by 500 ms, and the text is also saved at once when a field loses focus. The test waits until the save request has reached the backend before reloading, instead of waiting a fixed time, so it does not depend on the length of the debounce.
@@ -284,7 +296,7 @@ Saving the profile is debounced by 500 ms, and the text is also saved at once wh
`uiAccessibility.spec.ts` runs **axe** through `@axe-core/playwright` against WCAG 2.1 level A and AA, the level required for the public sector in Norway. It checks:
- all six pages (PlantMatch, ExplorePlants, MyMatches, Profile, PlantOwnerTest and the 404 page), in both light and dark mode, since colour contrast has to meet the WCAG 2.1 requirements in both themes
-- content that only appears after an interaction: a flipped plant card, the edit tab on the profile page, MyMatches with a matched plant, the result of the plant owner test, and the open walkthrough
+- content that only appears after an interaction: a flipped plant card, the edit tab on the profile page, MyMatches with a matched plant, the result of the plant owner test with the suggested preferences (whose buttons are also checked for non-text contrast), and the open walkthrough
The tests run on both desktop and mobile, since the layout, and the elements that are visible, differ between them. A failing test lists each element that breaks a rule, with axe's explanation (for contrast: the colours and the ratio).
diff --git a/e2e/helpers/names.ts b/e2e/helpers/names.ts
index 8b4cb122..e3af2041 100644
--- a/e2e/helpers/names.ts
+++ b/e2e/helpers/names.ts
@@ -41,10 +41,12 @@ export const names = {
// Profile
profile: /^(profile|profil)$/i,
- // Preferences, as they are named on the buttons on the profile page
+ // Preferences, as they are named on the buttons on the profile page and
+ // in the suggestions after the plant owner test
averageWater: /^(average watering|middels vannbehov)$/i,
frequentWater: /^(frequent watering|trenger mye vann)$/i,
fullSun: /^(full sun|full sol)$/i,
+ partShade: /^(part shade|delvis skygge)$/i,
filteredShade: /^(filtered shade|filtrert skygge)$/i,
mediumCare: /^(medium care|middels stell)$/i,
hardCare: /^(high care|krever mye stell)$/i,
@@ -56,4 +58,19 @@ export const names = {
descriptionField: /write something about you|skriv noe om deg selv/i,
// "Profile picture: "
profilePicture: /^(profile picture|profilbilde):/i,
+
+ // Plant owner test. The answers are the option buttons on each question.
+ plantOwnerTest: /^(plant owner test|planteeiertest)$/i,
+ oneHour: /^(1 hour a week|1 time i uken)$/i,
+ partSun: /^(partial sun|delvis sol)$/i,
+ countryside: /^(countryside|landet)$/i,
+ nowAndThen: /^(now and then|innimellom)$/i,
+ seeResult: /^(see my result|se resultatet mitt)$/i,
+ retakeTest: /^(retake test|ta testen på nytt)$/i,
+ averageCountryGardener:
+ /^(average country gardener|gjennomsnittlig landgartner)$/i,
+ suggestedPreferences: /^(suggested preferences|foreslåtte preferanser)$/i,
+ addSuggestions: /^(add to my preferences|legg til i preferansene mine)$/i,
+ suggestionsAdded: /preferences have been added|preferansene er lagt til/i,
+ suggestionsAlreadyAdded: /already have all of these|har allerede alle disse/i,
};
diff --git a/e2e/uiAccessibility.spec.ts b/e2e/uiAccessibility.spec.ts
index c13460d6..56224e61 100644
--- a/e2e/uiAccessibility.spec.ts
+++ b/e2e/uiAccessibility.spec.ts
@@ -82,6 +82,7 @@ const BOUNDARY_SELECTORS = [
".walkthrough__button",
".plant-preferences button",
".plant-owner-test-option",
+ ".plant-owner-test-suggestion-list button",
".sort-button",
".pagination button:not(:disabled)",
"input",
diff --git a/e2e/uiPlantOwnerTest.spec.ts b/e2e/uiPlantOwnerTest.spec.ts
new file mode 100644
index 00000000..e4e5e360
--- /dev/null
+++ b/e2e/uiPlantOwnerTest.spec.ts
@@ -0,0 +1,158 @@
+import { test, expect, type Page, type Response } from "@playwright/test";
+import { goToPage } from "./helpers/navigation";
+import { names } from "./helpers/names";
+
+// User journey: take the plant owner test, choose which of the suggested
+// preferences to add, and check that they are saved on the profile.
+// Each test gets a new browser and therefore a new user without preferences.
+
+// Countryside and "now and then" give the result "Average country gardener".
+// The average gardeners get the care level from the time they spend, so
+// "1 hour a week" suggests medium care, and "partial sun" suggests part shade.
+const ANSWERS = [names.oneHour, names.partSun, names.countryside];
+const LAST_ANSWER = names.nowAndThen;
+const SUGGESTIONS = [names.averageWater, names.partShade, names.mediumCare];
+
+// Matches the response to the request that saves exactly these preference ids
+const preferencesSaved = (ids: string[]) => (response: Response) => {
+ const body = response.request().postData() ?? "";
+ return (
+ response.url().includes("/graphql") &&
+ body.includes("updateUserPreferences") &&
+ ids.every((id) => body.includes(`"${id}"`))
+ );
+};
+
+// Answers the four questions like a user would and opens the result
+async function takeTest(page: Page) {
+ for (const answer of ANSWERS) {
+ await page.getByRole("button", { name: answer }).click();
+ await page.getByRole("button", { name: names.next }).click();
+ }
+ await page.getByRole("button", { name: LAST_ANSWER }).click();
+ await page.getByRole("button", { name: names.seeResult }).click();
+ await expect(
+ page.getByRole("heading", { name: names.averageCountryGardener }),
+ ).toBeVisible();
+}
+
+// The box with the suggested preferences on the result page
+const suggestionsBox = (page: Page) =>
+ page.getByRole("region", { name: names.suggestedPreferences });
+
+test("the user can add the suggested preferences from the plant owner test to the profile", async ({
+ page,
+}) => {
+ const suggestions = suggestionsBox(page);
+
+ await test.step("the result suggests preferences, all chosen from the start", async () => {
+ await page.goto("");
+ await goToPage(page, names.plantOwnerTest);
+ await takeTest(page);
+
+ for (const name of SUGGESTIONS) {
+ await expect(suggestions.getByRole("button", { name })).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ }
+ });
+
+ await test.step("the user leaves out part shade and adds the others", async () => {
+ await suggestions.getByRole("button", { name: names.partShade }).click();
+ await expect(
+ suggestions.getByRole("button", { name: names.partShade }),
+ ).toHaveAttribute("aria-pressed", "false");
+
+ const saved = page.waitForResponse(
+ preferencesSaved(["averageWater", "mediumCare"]),
+ );
+ await suggestions
+ .getByRole("button", { name: names.addSuggestions })
+ .click();
+ const response = await saved;
+ expect(response.request().postData()).not.toContain('"partShade"');
+
+ await expect(suggestions.getByRole("status")).toHaveText(
+ names.suggestionsAdded,
+ );
+ });
+
+ await test.step("the profile shows the added preferences, also after a reload", async () => {
+ await goToPage(page, names.profile);
+ for (const reload of [false, true]) {
+ if (reload) await page.reload();
+ await expect(
+ page.getByRole("button", { name: names.averageWater }),
+ ).toHaveAttribute("aria-pressed", "true");
+ await expect(
+ page.getByRole("button", { name: names.mediumCare }),
+ ).toHaveAttribute("aria-pressed", "true");
+ await expect(
+ page.getByRole("button", { name: names.partShade }),
+ ).toHaveAttribute("aria-pressed", "false");
+ }
+ });
+
+ await test.step("taking the test again only suggests what is not saved yet", async () => {
+ await goToPage(page, names.plantOwnerTest);
+ await takeTest(page);
+
+ await expect(
+ suggestions.getByRole("button", { name: names.partShade }),
+ ).toBeVisible();
+ await expect(
+ suggestions.getByRole("button", { name: names.averageWater }),
+ ).toHaveCount(0);
+ await expect(
+ suggestions.getByRole("button", { name: names.mediumCare }),
+ ).toHaveCount(0);
+
+ // Adding the last one keeps the preferences that were already saved
+ const saved = page.waitForResponse(
+ preferencesSaved(["averageWater", "mediumCare", "partShade"]),
+ );
+ await suggestions
+ .getByRole("button", { name: names.addSuggestions })
+ .click();
+ await saved;
+ await expect(suggestions.getByRole("status")).toHaveText(
+ names.suggestionsAdded,
+ );
+
+ // When everything is saved, the next result says so instead
+ await page.getByRole("button", { name: names.retakeTest }).click();
+ await takeTest(page);
+ await expect(suggestions.getByRole("status")).toHaveText(
+ names.suggestionsAlreadyAdded,
+ );
+ await expect(
+ suggestions.getByRole("button", { name: names.addSuggestions }),
+ ).toHaveCount(0);
+ });
+});
+
+test("nothing is saved when the user does not add the suggestions", async ({
+ page,
+}) => {
+ const preferenceRequests: string[] = [];
+ page.on("request", (request) => {
+ if ((request.postData() ?? "").includes("updateUserPreferences")) {
+ preferenceRequests.push(request.postData() ?? "");
+ }
+ });
+
+ await page.goto("#/plantOwnerTest");
+ await takeTest(page);
+ await expect(suggestionsBox(page)).toBeVisible();
+
+ // The user goes on without adding anything
+ await goToPage(page, names.profile);
+ for (const name of SUGGESTIONS) {
+ await expect(page.getByRole("button", { name })).toHaveAttribute(
+ "aria-pressed",
+ "false",
+ );
+ }
+ expect(preferenceRequests).toEqual([]);
+});
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 48bbd7b4..db7f21ed 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -209,6 +209,14 @@
"use": "Use as profile picture",
"saved": "This is now your profile picture!",
"failed": "Could not save the profile picture. Try again later."
+ },
+ "suggestions": {
+ "title": "Suggested preferences",
+ "info": "Based on your answers, these preferences could suit you. Choose the ones you want and add them to your profile.",
+ "add": "Add to my preferences",
+ "added": "The preferences have been added to your profile!",
+ "alreadyAdded": "You already have all of these preferences.",
+ "failed": "Could not save the preferences. Try again later."
}
},
"notFound": {
diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json
index 478c3b17..a9e7c6e7 100644
--- a/frontend/src/i18n/locales/no/translation.json
+++ b/frontend/src/i18n/locales/no/translation.json
@@ -209,6 +209,14 @@
"use": "Bruk som profilbilde",
"saved": "Dette er nå profilbildet ditt!",
"failed": "Kunne ikke lagre profilbildet. Prøv igjen senere."
+ },
+ "suggestions": {
+ "title": "Foreslåtte preferanser",
+ "info": "Basert på svarene dine kan disse preferansene passe deg. Velg de du vil ha og legg dem til i profilen din.",
+ "add": "Legg til i preferansene mine",
+ "added": "Preferansene er lagt til i profilen din!",
+ "alreadyAdded": "Du har allerede alle disse preferansene.",
+ "failed": "Kunne ikke lagre preferansene. Prøv igjen senere."
}
},
"notFound": {
diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css
index b6efdb98..b746d91d 100644
--- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css
+++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.css
@@ -220,3 +220,51 @@
transition: none;
}
}
+
+/* Suggested preferences on the result page */
+.plant-owner-test-suggestions {
+ margin: 0 auto 2rem;
+ padding: 1.5rem;
+ border: 2px solid var(--dark-green);
+ border-radius: 16px;
+}
+
+.plant-owner-test-suggestions h3 {
+ margin: 0 0 0.75rem;
+ font-size: 1.4rem;
+}
+
+.plant-owner-test-suggestions p {
+ margin: 0 0 1rem;
+ line-height: 1.6;
+}
+
+.plant-owner-test-suggestion-list {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 0.75rem;
+ margin-bottom: 1rem;
+}
+
+/* Same look as the preference buttons on the profile page */
+.plant-owner-test-suggestion-list button {
+ padding: 0.75rem 1.25rem;
+ border: 2px solid var(--dark-pink);
+ border-radius: 20px;
+ background: var(--light-pink);
+ color: var(--text-dark);
+ font-size: 1rem;
+ cursor: pointer;
+}
+
+.plant-owner-test-suggestion-list button.selected {
+ background: var(--dark-pink);
+ color: var(--text-light);
+ font-weight: 600;
+}
+
+.plant-owner-test-suggestion-list button:focus-visible {
+ outline: 3px solid var(--dark-green);
+ outline-offset: 3px;
+}
diff --git a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx
index a477bea6..d8b7b213 100644
--- a/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx
+++ b/frontend/src/pages/plantOwnerTest/PlantOwnerTestPage.tsx
@@ -7,8 +7,10 @@ import {
plantOwnerTest,
resultImages,
getPlantOwnerResult,
+ getSuggestedPreferences,
type PlantOwnerType,
} from "./plantOwnerTest";
+import SuggestedPreferences from "./SuggestedPreferences";
import "./PlantOwnerTestPage.css";
export default function PlantOwnerTestPage() {
@@ -84,6 +86,10 @@ export default function PlantOwnerTestPage() {
{t(`plantQuiz.results.${result}.description`)}
+
+
{isProfilePicture ? (
{t("plantQuiz.profilePicture.saved")}
diff --git a/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx
new file mode 100644
index 00000000..3058b111
--- /dev/null
+++ b/frontend/src/pages/plantOwnerTest/SuggestedPreferences.tsx
@@ -0,0 +1,128 @@
+import { useMutation } from "@apollo/client/react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useUser } from "../../context/UserContext.tsx";
+import {
+ UPDATE_USER_PREFERENCES,
+ type UpdateUserPreferencesData,
+} from "../../graphql/user/mutations.ts";
+
+type SuggestedPreferencesProps = {
+ // Preference ids suggested by the test
+ suggestions: string[];
+};
+
+// Shows the preferences suggested by the plant owner test. The user chooses
+// which of them to add, and nothing is saved until they click the add button.
+export default function SuggestedPreferences({
+ suggestions,
+}: SuggestedPreferencesProps) {
+ const { t } = useTranslation();
+ const { userId, user } = useUser();
+ const saved = user?.preferences ?? [];
+
+ const [updatePreferences] = useMutation(
+ UPDATE_USER_PREFERENCES,
+ );
+
+ // The suggestions the user wants to add. All are chosen to begin with.
+ const [chosen, setChosen] = useState(suggestions);
+ const [status, setStatus] = useState<"idle" | "added" | "failed">("idle");
+
+ // Suggestions that are not in the user's preferences yet
+ const newSuggestions = suggestions.filter((id) => !saved.includes(id));
+ const toAdd = chosen.filter((id) => newSuggestions.includes(id));
+
+ function toggle(id: string) {
+ setChosen((previous) =>
+ previous.includes(id)
+ ? previous.filter((item) => item !== id)
+ : [...previous, id],
+ );
+ }
+
+ async function addPreferences() {
+ if (!userId || toAdd.length === 0) return;
+
+ // Added to the preferences the user already has, none are removed
+ const updatedPreferences = [...saved, ...toAdd];
+ try {
+ const result = await updatePreferences({
+ variables: { userId, preferences: updatedPreferences },
+ // Updates the profile and plant cards right away
+ optimisticResponse: {
+ updateUserPreferences: {
+ __typename: "User",
+ id: userId,
+ preferences: updatedPreferences,
+ },
+ },
+ });
+ // null means the user was not found in the database
+ setStatus(result.data?.updateUserPreferences ? "added" : "failed");
+ } catch {
+ // Apollo rolls the preferences back if the server fails
+ setStatus("failed");
+ }
+ }
+
+ if (suggestions.length === 0) return null;
+
+ return (
+
+