diff --git a/README.md b/README.md
index 31ee238a..6b09525d 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,7 @@
# I <3 Plants
-> **Live version:** _TODO: add link to the deployed app on the VM_
-
I <3 Plants offers a fun way of finding plants and reading about them! Instead of scrolling through a long catalogue, you set your preferences and get shown one plant at a time. You like the plants you want and skip the ones you don't, and your matches are saved so you can come back to them later. If you already know what you are looking for, you can also search and filter the full plant collection.
-The full project description and specification are in [docs/Specifications for project 2.pdf](docs/Specifications%20for%20project%202.pdf).
-
## Link to VM
http://it2810-03.idi.ntnu.no/project2/
@@ -14,11 +10,14 @@ http://it2810-03.idi.ntnu.no/project2/
- **Plant Match:** Shows plants one at a time. Click ✿ to like a plant or ✖ to skip it.
- **Preferences:** Choose what kind of plants you want, for example indoor, outdoor, flowering, pet friendly or succulent. Your preferences are remembered between visits.
-- **My Matches:** A list of all the plants you have matched with or have added as matches.
-- **Explore Plants:** Search the plant collection and filter by watering needs, sunlight, location (indoor/outdoor) and edibility.
+- **My Matches:** A list of all the plants you have matched with or have added as matches. Can also delet plants from my matches.
+- **Explore Plants:** Search athe plant collection and filter by watering needs, sunlight, location (indoor/outdoor) and edibility. Sort the plants by; alphabetical order, watering and care. Can also add plants to my matches from here.
- **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level).
-- **Profile:** Your preferences and saved plants in one place.
-- **Language and theme:** The app is available in English and Norwegian, and has a light and a dark theme.
+- **Profile:** Your preferences, description, name and plant avtar is saved.
+- **Language:** The app is available in English and Norwegian.
+- **Theme:** has a light and a dark theme.
+- **Plant Owner Test:** TODO exlusive picture
+- **Plant Card** read about the plant and its prefernaces. Add the plant to my matches and remove it from my matches
## Tech stack
@@ -91,6 +90,7 @@ The application is tested on three levels:
- **Backend:** The database connection and the GraphQL server are tested with **Vitest** against a real MongoDB that runs in memory (**mongodb-memory-server**). The tests never use the database on the VM, so they do not need the VPN or the SSH tunnel. MongoDB is downloaded once the first time the backend tests run.
- **End-to-end:** Longer user journeys and the GraphQL API are tested with **Playwright**, against the real backend and a built frontend with a separate in-memory test database. The tests run on both desktop and mobile, and check all pages against WCAG 2.1 AA with **axe**.
+
See [tests.md](docs/tests.md) for what the test files cover, the e2e setup, the scenarios and what the tests found.
### Run the tests
@@ -132,6 +132,7 @@ The coverage table is printed in the terminal. A detailed report is saved in `fr
+
### Continuous integration
GitHub Actions ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, runs lint and tests for both the backend and the frontend, and runs the Playwright e2e and API tests. If an e2e test fails, the HTML report with traces can be downloaded from the workflow run.
@@ -142,6 +143,6 @@ See [quality.md](docs/quality.md) for Lighthouse results, testing, accessibility
and work practices.
## Known issues
-
-TODO!
If you type and switch pages within half a second after updating your profile, the last few letters are not saved, because the debounce didn't have time to send.
+
+Information on plant card does not translate to Norwegian.
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 032c780f..7a6a90a5 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -340,6 +340,11 @@ const resolvers = {
if (args.watering) {
filter.watering = new RegExp(`^${normalize(args.watering)}$`, "i");
}
+ if (args.sunlight) {
+ // sunlight is a list, and a value can be combined, e.g. "part sun/part shade".
+ // A regex on a list matches if any of the values contain the filter.
+ filter.sunlight = new RegExp(normalize(args.sunlight), "i");
+ }
if (args.careLevel) {
const level = normalize(args.careLevel);
// "Medium" and "Moderate" both exist in the data and mean the same
diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts
index d4434880..fc4d025e 100644
--- a/backend/tests/server.test.ts
+++ b/backend/tests/server.test.ts
@@ -196,17 +196,37 @@ describe("starting the server", () => {
describe("plants", () => {
// Made-up plants with the same spellings as the real data, e.g. both "Medium" and "Moderate"
const PLANTS = [
- { commonName: "Aloe", watering: "Minimum", careLevel: "Low" },
- { commonName: "Basil", watering: "Frequent", careLevel: "Moderate" },
+ {
+ commonName: "Aloe",
+ watering: "Minimum",
+ careLevel: "Low",
+ sunlight: ["full sun"],
+ },
+ {
+ commonName: "Basil",
+ watering: "Frequent",
+ careLevel: "Moderate",
+ sunlight: ["Full sun", "part shade"],
+ },
{ commonName: "Cactus", watering: "minimum", careLevel: "High" },
- { commonName: "Daisy", watering: "Average", careLevel: "Medium" },
- { commonName: "Fern", watering: null, careLevel: null },
- { commonName: "Fern (giant)", watering: "Average", careLevel: "Medium" },
+ {
+ commonName: "Daisy",
+ watering: "Average",
+ careLevel: "Medium",
+ sunlight: ["part sun/part shade"],
+ },
+ { commonName: "Fern", watering: null, careLevel: null, sunlight: null },
+ {
+ commonName: "Fern (giant)",
+ watering: "Average",
+ careLevel: "Medium",
+ sunlight: ["filtered shade"],
+ },
];
const EXPLORE = `
- query ($search: String, $watering: String, $careLevel: String, $sort: String, $limit: Int, $offset: Int) {
- explorePlants(search: $search, watering: $watering, careLevel: $careLevel, sort: $sort, limit: $limit, offset: $offset) {
+ query ($search: String, $sunlight: String, $watering: String, $careLevel: String, $sort: String, $limit: Int, $offset: Int) {
+ explorePlants(search: $search, sunlight: $sunlight, watering: $watering, careLevel: $careLevel, sort: $sort, limit: $limit, offset: $offset) {
totalCount
plants { name }
}
@@ -297,35 +317,19 @@ describe("plants", () => {
expect((await explore({ careLevel: "high" })).names).toEqual(["Cactus"]);
});
- it("filters on sunlight in any of a plant's sunlight values, without caring about case", async () => {
- // Replaces the plants from beforeEach with plants that have sunlight values
- await db.collection("plants").deleteMany({});
- await insertPlants(
- { commonName: "Aloe", sunlight: ["full sun"] },
- { commonName: "Basil", sunlight: ["full sun", "part shade"] },
- { commonName: "Cactus", sunlight: ["Full sun"] },
- { commonName: "Daisy", sunlight: ["part shade"] },
- { commonName: "Fern" },
- );
-
- const bySunlight = async (sunlight: string) => {
- const result = await execute<{ explorePlants: Page }>(
- `query ($sunlight: String) {
- explorePlants(sunlight: $sunlight) { totalCount plants { name } }
- }`,
- { sunlight },
- );
- expect(result.errors).toBeUndefined();
- return result.data!.explorePlants.plants.map((p) => p.name);
- };
- // "full_sun" from the frontend matches "full sun" and "Full sun" in the database,
- // also when the plant has several sunlight values
- expect(await bySunlight("full_sun")).toEqual(["Aloe", "Basil", "Cactus"]);
- expect(await bySunlight("part_shade")).toEqual(["Basil", "Daisy"]);
- // The whole value must match, so part of a word gives no plants
- expect(await bySunlight("sun")).toEqual([]);
- });
+ it("filters on sunlight, matching any value in the list", async () => {
+ expect((await explore({ sunlight: "full_sun" })).names).toEqual([
+ "Aloe",
+ "Basil",
+ ]);
+ expect((await explore({ sunlight: "part_shade" })).names).toEqual([
+ "Basil",
+ "Daisy",
+ ]);
+ expect((await explore({ sunlight: "part_sun" })).names).toEqual([
+ "Daisy",
+ ]);
it("returns one page at a time with the total count", async () => {
expect(await explore({ limit: 2, offset: 2 })).toEqual({
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index a56311d1..791586bc 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,22 +1,34 @@
# Architecture
-TODO: updated with new arciture
-
-This document describes how the data flows from the API to the frontend, how the frontend, backend and database fit together. It also describes the plant data and the Perenual API and why we chose GraphQL and MongoDB.
+This document describes how the frontend, backend and database fit together, how data flows between them, and what is stored in each MongoDB collection. It also describes the plant data from the Perenual API, why we chose GraphQL and MongoDB, and where the app keeps state (database, `localStorage` or `sessionStorage`).
The folder structure is shown at the end of this document.
-## Data flow
+## Overview
```text
-Perenual API → seedDataFetch.js → MongoDB → Apollo Server (GraphQL) → Frontend
+ (once, offline)
+Perenual API → seedDataFetch.js ─┐
+ ▼
+ MongoDB (database "iloveplants")
+ ├── plants (read-only for the app)
+ └── users (read and written by the app)
+ ▲
+ │ MongoDB driver (db.ts)
+ │
+ Apollo Server, GraphQL (server.ts, port 3001)
+ ▲
+ │ GraphQL over HTTP (/graphql)
+ │
+ Frontend: React + Apollo Client
+ (localStorage: userId, sessionStorage: explore filters)
```
-The plant data is fetched from the Perenual API once and stored in our own database. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend:
+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. The frontend never talks to the database directly. All data goes through the GraphQL API in the backend:
-1. The frontend sends a GraphQL request to the backend (for example the `getPlants` query with `limit` and `offset`).
-2. Apollo Server runs the matching resolver, which reads from the `plants` collection in MongoDB.
-3. The resolver maps the database documents to the `Plant` type (for example `commonName` becomes `name`) and returns only the fields the frontend asked for.
-4. The frontend receives the data as JSON and renders it.
+1. The frontend sends a GraphQL request to the backend (for example `explorePlants` with search, filters and pagination, or `addUserMatch` when the user likes a plant).
+2. Apollo Server runs the matching resolver, which reads from or writes to the `plants` or `users` collection in MongoDB.
+3. The resolver maps the database documents to the GraphQL types (for example `commonName` becomes `name`, and `_id` becomes `id`) and returns only the fields the frontend asked for.
+4. The frontend receives the data as JSON, stores it in the Apollo cache and renders it.
The sections below describe each part in more detail.
@@ -24,40 +36,171 @@ The sections below describe each part in more detail.
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`; `BrowserRouter` uses the same value through `import.meta.env.BASE_URL`, including the trailing slash for home links.
-- **Reusable logic in hooks:** Logic without UI is kept in hooks. `useDebounce` delays updates while the user is typing, and `useSessionState` stores state in `sessionStorage`.
+- **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`; `BrowserRouter` uses the same value through `import.meta.env.BASE_URL`. All pages except the start page are lazy-loaded.
+
+ | 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 |
+
+- **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), and `useSessionState` stores state in `sessionStorage`.
- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next).
-- **Shared types and helpers:** `Plant` and `Preference` are defined in `types/`, and helper functions such as `isPreferenceMatch` in `utils/`.
+- **Shared types:** `Plant` and `Preference` are defined in `types/`.
### Communication with the backend
-The frontend uses Apollo Client, which is set up in `main.tsx` with an in-memory cache. During development, requests to `/graphql` are proxied by Vite to the backend on port 3001 (see [vite.config.ts](../frontend/vite.config.ts)).
+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.
## Backend: GraphQL with Apollo Server
The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks for exactly the fields each view needs. A plant card needs more fields than a list item, and both are served by the same `Plant` type without extra endpoints. The schema also gives us one typed contract between frontend and backend.
-- `db.ts` connects to MongoDB using the connection string in `.env` (see `.env.example`).
-- `server.ts` defines the schema and resolvers. The `getPlants(limit, offset)` query returns plants with pagination. The resolver maps database documents to the GraphQL type (for example `commonName` becomes `name`), so the database structure is not exposed to the frontend.
-- `seedDataFetch.js` fills the database with plant data (see [Data source](#data-source-the-perenual-api) below).
+- `db.ts` connects to MongoDB using `MONGODB_URI` and `DB_NAME` from `.env` (see `.env.example`). The database name defaults to `iloveplants`.
+- `server.ts` defines the schema and resolvers, and starts Apollo Server on `PORT` (default 3001).
+- `seedDataFetch.js` fills the `plants` collection with plant data (see [Data source](#data-source-the-perenual-api) below).
+
+### Schema
+
+**Queries**
+
+| Query | Description |
+| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `getPlants(limit = 50, offset = 0): [Plant]` | Returns `limit` random plants (MongoDB `$sample`). Used by the match page. `offset` is accepted but has no effect, since the plants are random. |
+| `explorePlants(search, sunlight, watering, careLevel, sort, limit = 12, offset = 0): PlantPage!` | Search on 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. |
+
+**Mutations**
+
+| Mutation | Description |
+| -------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
+| `createUser: User!` | Creates an empty user with default values. |
+| `updateUserProfile(userId, name, description, profilePicture)` | Updates only the fields that are sent. Text is trimmed and length-checked; empty text is stored as `null`. |
+| `updateUserPreferences(userId, preferences)` | Replaces the preference list. Unknown preferences are rejected and duplicates removed. |
+| `addUserMatch(userId, plantId)` | Adds a plant to the user's matches (`$addToSet`, so never twice). Unknown plants are rejected. |
+| `removeUserMatch(userId, plantId)` | Removes a plant from the user's matches (`$pull`). |
+
+**Types**
+
+- `Plant`: `id`, `name`, `imageURL`, `scientificName`, `description`, `watering`, `sunlight`, `careLevel`
+- `PlantPage`: `plants`, `totalCount`
+- `User`: `id`, `name`, `description`, `profilePicture`, `preferences`, `matchedPlants`, `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.
+
+Invalid input from the client gives a GraphQL error with the code `BAD_USER_INPUT` instead of crashing the server.
## Database: MongoDB
-We store the plants in MongoDB, a document database. It is a good fit for this data:
+The database `iloveplants` has two collections: `plants` and `users`. Both the plant and user information was chosen to be stored in MongoDB to make the app scalable. This means that more plants and users can be added, and each of these objects can have more attributes than if other storage options, such as local and session storage, had been chosen. MongoDB was also chosen because of its flexible schema.
+
+### The `plants` collection
+
+One document per plant species. The documents were written by `seedDataFetch.js` with data fetched from the Perenual API. The running app only reads them. There is a unique index on `perenualId`.
+
+| Field | Type | Source / description | Exposed in GraphQL as |
+| --------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------ | -------------------------- |
+| `_id` | ObjectId | Set by MongoDB | `id` |
+| `perenualId` | number | Plant id in Perenual, used as the key when the seed script updates a plant | – |
+| `commonName` | string | Species list | `name` |
+| `scientificName` | string[] | Species list | `scientificName` |
+| `otherNames` | string[] | Species list | – |
+| `family` | string | Species list | – |
+| `genus` | string | Species list | – |
+| `imageData` | string | The plant image downloaded and stored as a base64 data URI | `imageURL` |
+| `imageLicense` | string | Licence name of the image | – |
+| `createdAt` | Date | When the plant was first inserted | – |
+| `description` | string | Species details | `description` |
+| `type` | string | Species details (e.g. tree, herb) | – |
+| `cycle` | string | Species details (e.g. perennial) | – |
+| `watering` | string | Species details: `Minimum`, `Average` or `Frequent` | `watering` |
+| `sunlight` | string[] | Species details (e.g. `full sun`, `part shade`) | `sunlight` |
+| `careLevel` | string | Species details: `Low`, `Medium`/`Moderate` or `High` | `careLevel` |
+| `growthRate` | string | Species details | – |
+| `maintenance` | string | Species details | – |
+| `origin` | string[] | Species details | – |
+| `hardiness` | `{ min, max }` | Species details (hardiness zones) | – |
+| `indoor` | boolean | Species details | – |
+| `droughtTolerant` | boolean | Species details | – |
+| `poisonousToHumans` | boolean | Species details | – |
+| `poisonousToPets` | boolean | Species details | – |
+| `detailsFetchedAt` | Date | Set when the details were fetched, so the seed script skips the plant next time | – |
+| `detailsUnavailable` | boolean | Set when Perenual has no details for the plant, so the seed script does not retry it | – |
+
+All fields except `_id`, `perenualId` and `createdAt` can be missing or `null`, because Perenual does not have every field for every plant, and details are only available for plants with a Perenual id up to 3000. The resolver also accepts an older `imageURL` field as a fallback if `imageData` is missing. Fields marked with – are stored for possible later use but are not part of the GraphQL schema yet.
+
+Note: the image URLs from the Perenual API expire after 24 hours. That is why each image was downloaded and stored as base64 in `imageData` when the data was loaded, so the images are still available after the URLs have expired.
+
+### The `users` collection
+
+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) |
+
+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 `server.ts` and must match the ids used in the frontend (`Profile.tsx` and `plantownertest.ts`).
+
+Matches only store the plant id, not a copy of the plant. That keeps user documents small and means the user always sees the current plant data.
+
+### Why MongoDB
+
+We store the data in MongoDB, a document database. It is a good fit for this data:
- **The data is already documents.** Perenual returns JSON with nested objects and lists (such as sunlight requirements and scientific names). Each plant becomes one document with almost the same shape, so there is no need to split it into several tables and join them back together. This limits the cleaning needed.
- **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`).
+- **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.
+
+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 |
+| `sessionStorage` | Explore page search, filters and sort (`ExplorePlants.*` keys, via `useSessionState`) | The view is restored when the user navigates away and back, but starts fresh in a new tab or 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 |
-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 the way a relational database does. That matters little here, because the plant collection is mostly read-only, and user data such as saved matches only needs to refer to a plant by its ID.
+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.
-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).
+When the app starts, `UserProvider` reads `userId` from `localStorage` and runs `getUser`. If there is no id, or the id no longer exists in the database, it runs `createUser` and saves the new id. If the backend cannot be reached, it does not create a new user, and the app still works without saved data.
+
+## Scalability
+
+- **Use of MongoDB over local storage.** Local storage is only used for the `userId`, while the rest of the user information is stored in MongoDB. This makes it easy to add more user information later. Local storage is limited to about 5 MB per site and only exists in that one browser, where the server cannot use it. By storing user data in MongoDB, there is no practical limit to how many plants a user can save, and the data can be used by the backend.
+- **Plant data does not depend on Perenual.** The number of users does not affect the number of requests to Perenual, since the app only reads from our own database. It also makes it possible to fetch more plants later if one wants to.
+- **The server does the heavy work.** Searching, filtering, sorting and pagination run as MongoDB queries, so the frontend only receives one page of plants at a time (12 by default) together with the total count. This works the same whether the collection has a hundred or many thousand plants, and keeps responses small so pages load faster.
+- **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.
+- **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
The plant data comes from the [Perenual API](https://perenual.com/docs/api), which has information about thousands of plant species, including images, care information and plant traits.
-The app does **not** call Perenual while it is running. Instead, the script [backend/seedDataFetch.js](../backend/seedDataFetch.js) fetched the data once, cleaned it and stored it in our own MongoDB database on the VM. We have kept the seedDataFetch file so you can see how this has been done. The app only talks to our own GraphQL backend. We chose this approach for these reasons:
+The app does **not** call Perenual while it is running. Instead, the script [backend/seedDataFetch.js](../backend/seedDataFetch.js) fetched the data once, cleaned it and stored it in our own MongoDB database on the VM. We have kept the script so you can see how this has been done. It runs in two phases:
+
+1. **Species list:** fetches the plant list, upserts one document per plant (keyed on `perenualId`), and downloads each image and stores it as a base64 data URI in `imageData`. The image URLs from Perenual expire after 24 hours, which is why the image itself is stored.
+2. **Details:** fetches `species/details/{id}` for every plant that is missing details and adds the detail fields to the same document.
+
+The raw detail responses are cached in `backend/data/raw/`, and the script stops before it uses up the daily quota, so it can be run again (for example over several days) and continue where it left off. `npm run seed:reset` drops the collection and starts over.
+
+We chose this approach for these reasons:
- **Rate limits:** The free tier on the Perenual API allows about 100 requests per day, and only returns details for plants with an ID up to 3000. If the app called Perenual directly, a handful of users would use up the daily limit in minutes. By fetching the data once and serving it from our own database, the number of users no longer affects the number of requests to Perenual.
- **Fewer requests:** Because the data is fetched only once, and the raw responses are cached locally so the script never requests the same data twice, we avoid unnecessary network traffic and resource use.
@@ -72,8 +215,8 @@ T03-Project-2/
├── backend/
│ ├── src/
│ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env)
-│ │ └── server.ts # Apollo Server with GraphQL schema and resolvers (getPlants query)
-│ ├── tests/ # Backend tests (none written yet)
+│ │ └── server.ts # Apollo Server with GraphQL schema and resolvers for plants and users
+│ ├── tests/ # Backend tests against an in-memory MongoDB (db, server)
│ ├── seedDataFetch.js # Script that fetches plant data from the Perenual API and stores it in MongoDB
│ └── .env.example # Template for required environment variables
├── docs/ # Project documentation (architecture, tests, ...)
@@ -81,14 +224,15 @@ T03-Project-2/
│ ├── src/
│ │ ├── assets/ # Static images
│ │ ├── components/ # Reusable UI components, each in its own folder with a matching .css file
-│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useSessionState)
+│ │ ├── context/ # UserProvider and the GraphQL queries and mutations for the user
+│ │ ├── hooks/ # Reusable logic without UI (useDebounce, useSessionState, useProfile, useMatchedPlants)
│ │ ├── 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)
│ │ ├── types/ # Shared TypeScript types (Plant, Preference)
-│ │ ├── utils/ # Helper functions (e.g. matching plant traits against user preferences)
│ │ ├── AppRoutes.tsx # Route definitions
-│ │ └── main.tsx # Application entry point
+│ │ └── main.tsx # Application entry point (Apollo Client, UserProvider, router)
+│ ├── .env.production # GraphQL URL for the deployed app
│ └── vite.config.ts # Vite and Vitest configuration, including proxy to the backend
└── README.md # Project overview and how to run the application
```
diff --git a/docs/Specifications for project 2.pdf b/docs/Specifications for project 2.pdf
deleted file mode 100644
index fa72b851..00000000
Binary files a/docs/Specifications for project 2.pdf and /dev/null differ
diff --git a/docs/ai-usage.md b/docs/ai-usage.md
index 27bc63fd..c62f9f1d 100644
--- a/docs/ai-usage.md
+++ b/docs/ai-usage.md
@@ -5,6 +5,10 @@ AI was used as an assistant throughout the development of the web application. I
- **Setup and configuration** — setting up the project in VS Code, Vitest, and project structure with backend and database
- **Explaining technical concepts** — how the database, backend and frontend are related, and how to implement debounce
- **Writing and reviewing tests** — drafting test files with mocked dependencies, and explaining the reasoning behind test structure and snapshot testing. AI also came up with suggestions regarding what should be tested to get a better test coverage
+- **Writing code** - Wrote code suggestions which was reviewed by the team
- **Writing documentation** — drafting and refining documentation and comments in the code
+- **Picture generation** - made the avtar pictures for the profile page
All AI-generated suggestions were reviewed, tested, and adapted by the team before being committed. Design and architectural decisions were made by the team.
+
+The AI modeles used where: Claud, ChatGPT and co-pilot.
\ No newline at end of file
diff --git a/docs/quality.md b/docs/quality.md
index 9fbf7b4d..7eb1ceda 100644
--- a/docs/quality.md
+++ b/docs/quality.md
@@ -10,6 +10,12 @@ This document describes how we have worked to ensure the quality of the applicat
- Sustainable web development: [Sustainable web development](#sustainable-web-development)
- Design choices: [Design choices](#design-choices)
+
+### Continuous integration
+
+GitHub Actions ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on every pull request and on every push to `main`. It checks the formatting with Prettier, and runs lint, tests for both the backend and the frontend.
+
+
## Work practices
- Before development began, the group created a prototype in Figma to establish a shared visual understanding of the application and agree on the design before writing code.
diff --git a/docs/tests.md b/docs/tests.md
index 5653c670..182b780f 100644
--- a/docs/tests.md
+++ b/docs/tests.md
@@ -107,6 +107,9 @@ The coverage only counts the Vitest tests. Code that is only run by the end-to-e
The tests are in `frontend/src/tests`. Snapshot tests are used for the explore page, the language switcher and the profile page.
+
+- `Sidebar.test.tsx`
+ - Tests the sidebar, including the title, navigation links to all pages, and that the language switcher and theme toggle are displayed. Also verifies that the sidebar closes when a link or the close button is clicked, that the open state is reflected in the `data-open` attribute, and that the navigation landmark is accessible and only the current page is marked as active.
- `App.test.tsx`
- Shows the right page for each route, and opens and closes the sidebar from the header.
- `ExplorePage.test.tsx`
@@ -134,11 +137,17 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- `PlantPreferences.test.tsx`
- Saved preferences are marked, preferences can be added and removed, the page does not crash when saving fails, and nothing is saved before the user exists.
- `Profile.test.tsx`
+
+ - Tests the profile page, including the name and image, that the preferences tab is shown by default, and that the user can switch to the saved plants tab and see the saved plants. Also includes a snapshot test.
+- `LanguageSwitcher.test.tsx`
+ - Tests the language switcher button in both Norwegian and English, and verifies that it shows the correct label and accessible name, and that clicking it switches to the other language.
+
- The name, the image alt text and a screen reader prefix for the description, the preferences tab by default, the labelled fields and avatar chooser in the edit tab, saving name, description and avatar, the saved avatar, that a picture from the plant owner test is shown but not offered in the chooser, and a snapshot.
- `Sidebar.test.tsx`
- The title, links to all pages, the language switcher and theme toggle, that the sidebar closes when a link or the close button is clicked, that the open state is shown in the `data-open` attribute, an accessible navigation landmark, and that only the current page is marked as active.
- `ThemeToggle.test.tsx`
- Switching between dark and light mode, restoring the saved mode on load, falling back to light mode for an invalid saved theme, and switching when browser storage is blocked.
+
- `Translation.test.tsx`
- The Norwegian and English translation files have exactly the same keys, so no text is missing in either language.
- `UserContext.test.tsx`
diff --git a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.css b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.css
index c93396c8..f432bbcf 100644
--- a/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.css
+++ b/frontend/src/components/PlantPreferenceChips/PlantPreferenceChips.css
@@ -18,7 +18,7 @@
font-size: 14px;
font-weight: 700;
- border: 2px solid transparent;
+ border: 2px solid var(--dark-pink);
transition: transform 0.2s ease;
}
diff --git a/frontend/src/components/plantCard/PlantCard.css b/frontend/src/components/plantCard/PlantCard.css
index 25b1866d..30d0e00b 100644
--- a/frontend/src/components/plantCard/PlantCard.css
+++ b/frontend/src/components/plantCard/PlantCard.css
@@ -321,10 +321,23 @@
font-size: 1.25rem;
}
- .plant-card-image,
- .plant-card-image-missing {
+ /* The card has a fixed height, so the image only gets the space left
+ after the name, button and preferences. Otherwise a tall image pushes
+ the preferences out of the card. */
+ .plant-card-front .plant-card-panel {
+ flex: 1 1 auto;
+ min-height: 0;
+ }
+
+ .plant-card-front .plant-card-name {
+ flex: none;
+ }
+
+ .plant-card-front .plant-card-image,
+ .plant-card-front .plant-card-image-missing {
width: 100%;
- flex: 1;
+ height: auto;
+ flex: 1 1 0;
min-height: 0;
object-fit: cover;
}
diff --git a/frontend/src/pages/explorePlants/ExplorePlants.css b/frontend/src/pages/explorePlants/ExplorePlants.css
index 490350bd..862c8061 100644
--- a/frontend/src/pages/explorePlants/ExplorePlants.css
+++ b/frontend/src/pages/explorePlants/ExplorePlants.css
@@ -159,6 +159,11 @@
transform-origin: top left;
}
+/* Sets the card apart from the pink background */
+.explore-plant-item .plant-card {
+ border: 3px solid var(--dark-green);
+}
+
.pagination {
display: flex;
flex-wrap: wrap;
diff --git a/frontend/src/pages/profile/Profile.css b/frontend/src/pages/profile/Profile.css
index 509526a2..bc7740e4 100644
--- a/frontend/src/pages/profile/Profile.css
+++ b/frontend/src/pages/profile/Profile.css
@@ -110,6 +110,10 @@
font: inherit;
}
+.edit-profile-form input::placeholder {
+ color: var(--text-dark);
+}
+
.edit-profile-form h3 {
margin-top: 35px;
}
diff --git a/frontend/src/pages/profile/Profile.tsx b/frontend/src/pages/profile/Profile.tsx
index 75fbb692..9e428c35 100644
--- a/frontend/src/pages/profile/Profile.tsx
+++ b/frontend/src/pages/profile/Profile.tsx
@@ -116,7 +116,7 @@ export default function Profile() {
setName(event.target.value)}
maxLength={40}
placeholder={t("profile.placeholderName")}
@@ -126,7 +126,7 @@ export default function Profile() {
setDescription(event.target.value)}
maxLength={100}
placeholder={t("profile.placeholderAbout")}
diff --git a/frontend/src/tests/Profile.test.tsx b/frontend/src/tests/Profile.test.tsx
index 28b57019..f9646a2d 100644
--- a/frontend/src/tests/Profile.test.tsx
+++ b/frontend/src/tests/Profile.test.tsx
@@ -92,12 +92,20 @@ describe("Profile page", () => {
expect(
screen.getByRole("heading", { name: /profile.editProfile/ }),
).toBeInTheDocument();
- expect(
- screen.getByRole("textbox", { name: "profile.enterName" }),
- ).toHaveValue("profile.name");
- expect(
- screen.getByRole("textbox", { name: "profile.aboutYou" }),
- ).toHaveValue("profile.description");
+ // Empty fields, so the placeholder shows and there is nothing to delete
+ const nameInput = screen.getByRole("textbox", {
+ name: "profile.enterName",
+ });
+ expect(nameInput).toHaveValue("");
+ expect(nameInput).toHaveAttribute("placeholder", "profile.placeholderName");
+ const descriptionInput = screen.getByRole("textbox", {
+ name: "profile.aboutYou",
+ });
+ expect(descriptionInput).toHaveValue("");
+ expect(descriptionInput).toHaveAttribute(
+ "placeholder",
+ "profile.placeholderAbout",
+ );
expect(
screen.getByRole("heading", { name: "profile.avatarChooser" }),
).toBeInTheDocument();