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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ http://it2810-03.idi.ntnu.no/project2/
- **Plant Match:** Shows random plants one at a time. 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, but the preferences do not change which plants are shown.
- **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.
- **Explore Plants:** Search the plant collection by 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 results are split into pages. You can also add plants to My Matches from here.
- **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 results are split into pages. The search, filters, sorting, and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. You 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). 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.
- **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.
Expand Down Expand Up @@ -93,9 +93,9 @@ Browser ──> Apache (port 80, /project2) serves the built frontend

The backend runs with pm2, which keeps it running in the background and restarts it if it crashes or the VM reboots. The backend reads `MONGODB_URI=mongodb://localhost:27017`, `DB_NAME=iloveplants` and `PORT=3001` from `backend/.env` on the VM (see `.env.example`). If the backend stops, see [How to start the backend if it stops](../T03-Project-2/docs/architecture.md) .


### Frontend
The frontend runs on the VM by using Apache serves. It was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM.

The frontend runs on the VM by using Apache serves. It was copied to the folder Apache serves for `/project2`. The build reads `VITE_GRAPHQL_URL` from [frontend/.env.production](frontend/.env.production), so the deployed app sends its requests to the backend on port 3001 on the VM.

### Database

Expand Down
8 changes: 4 additions & 4 deletions backend/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ export const buildExploreFilter = (
): Filter<PlantDoc> => {
const filter: Filter<PlantDoc> = {};
if (args.search?.trim()) {
filter.commonName = {
$regex: escapeRegex(args.search.trim()),
$options: "i",
};
const search = { $regex: escapeRegex(args.search.trim()), $options: "i" };
// Match on the common name or any of the scientific names (a list,
// so a regex matches if any of the values contain the search)
filter.$or = [{ commonName: search }, { scientificName: search }];
}
if (args.watering) {
filter.watering = new RegExp(`^${normalize(args.watering)}$`, "i");
Expand Down
11 changes: 10 additions & 1 deletion backend/tests/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ describe("plants", () => {
},
{
commonName: "Basil",
scientificName: ["Ocimum basilicum"],
watering: "Frequent",
careLevel: "Moderate",
sunlight: ["Full sun", "part shade"],
Expand Down Expand Up @@ -304,6 +305,12 @@ describe("plants", () => {
expect((await explore({ search: ".*" })).totalCount).toBe(0);
});

it("searches by scientific name", async () => {
expect((await explore({ search: "ocimum basilicum" })).names).toEqual([
"Basil",
]);
});

it("filters on watering and care level, with Medium and Moderate as the same", async () => {
expect((await explore({ watering: "minimum" })).names).toEqual([
"Aloe",
Expand All @@ -326,7 +333,9 @@ describe("plants", () => {
"Basil",
"Daisy",
]);
expect((await explore({ sunlight: "part_sun" })).names).toEqual(["Daisy"]);
expect((await explore({ sunlight: "filtered_shade" })).names).toEqual([
"Fern (giant)",
]);
});

it("returns one page at a time with the total count", async () => {
Expand Down
2 changes: 1 addition & 1 deletion backend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
"resolveJsonModule": true,
"sourceMap": true
},
"include": ["src"]
"include": ["src", "test", "globalSetup.ts"]
}
33 changes: 17 additions & 16 deletions docs/architecture.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Architecture

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`).
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`, URL parameters or `sessionStorage`).
The folder structure is shown at the end of this document.

## Overview
Expand All @@ -20,7 +20,7 @@ Perenual API → seedDataFetch.js ─┐
│ GraphQL over HTTP (/graphql)
│
Frontend: React + Apollo Client
(localStorage: userId, sessionStorage: explore filters)
(localStorage: userId, URL: Explore state)
```

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:
Expand All @@ -36,7 +36,7 @@ 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`. All pages except the start page are lazy-loaded.
- **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.

| Route | Page | Purpose |
| ----------------- | ---------------- | -------------------------------------------------------------- |
Expand All @@ -47,7 +47,7 @@ The frontend is built with React and TypeScript (Vite).
| `/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`.
- **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), `useSearchParams` keeps Explore search, filters, sorting and page in the URL, and `useSessionState` stores state in `sessionStorage` for features that still use it.
- **Internationalisation:** Text is stored in translation files for Norwegian and English (i18next).
- **Shared types:** `Plant` and `Preference` are defined in `types/`.

Expand All @@ -73,11 +73,11 @@ The backend exposes a single GraphQL endpoint. With GraphQL, the frontend asks f

**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. |
| 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 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. |

**Mutations**

Expand Down Expand Up @@ -172,13 +172,14 @@ MongoDB runs on the course VM and only listens on `127.0.0.1`, so it cannot be r

## 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 |
| 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`) | 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 |

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.

Expand Down
6 changes: 3 additions & 3 deletions docs/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p
- Shows the right page for each route, and opens and closes the sidebar from the header.
- `ExplorePage.test.tsx`
- Loading, error and empty results: a loading message, an error message when the query fails, and a message without page navigation when nothing matches.
- Search, filters and sorting: the search text is only sent after the debounce delay, the chosen filters and sort order are sent in the query, and the sort menu closes with Escape and with a click outside.
- Search, filters and sorting: the search text is only sent after the debounce delay, the chosen filters and sort order are sent in the query, the selected sort is visible and included in the sort button's accessible name, and the sort menu closes with Escape and with a click outside.
- Pagination: moving between pages, disabled buttons at the ends, and going back to page 1 when a filter or the search text changes.
- Reset and session: reset clears the search and all filters, and the filters are remembered when the page is opened again in the same session.
- URL state: search, filters, sorting and page are restored from the URL, changes are written to the URL, and reset clears the Explore parameters.
- Accessibility: a search landmark, a heading and labelled controls.
- Snapshots of the page with results, with no results and with the sort menu open.
- `Header.test.tsx`
Expand Down Expand Up @@ -167,7 +167,7 @@ The tests are in `backend/tests`. They use a real MongoDB in memory, started in
- Connecting to the database in `MONGODB_URI` and `DB_NAME`, using `iloveplants` when `DB_NAME` is not set, and the error messages when `MONGODB_URI` is missing or empty, is not a MongoDB address, or MongoDB cannot be reached (for example when the SSH tunnel is down).
- `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: random plants from `getPlants`, stored image data before the image URL, and in `explorePlants` the default sorting, case-insensitive search 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.
- Plants: random plants from `getPlants`, 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.
- 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.

Expand Down
2 changes: 1 addition & 1 deletion e2e/uiExplorePlants.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ test("user pages, filters, searches, opens a plant, sorts and resets", async ({
await jadeCard.locator(".plant-card-front .plant-card-info-button").click();
await expect(details).toHaveAttribute("aria-hidden", "false");
await expect(details).toContainText("Crassula ovata");
await expect(details).toContainText("Minimum");
await expect(details).toContainText("Low");
await expect(details).toContainText(
"A succulent with round, glossy leaves.",
);
Expand Down
Loading
Loading