From f21e0bb36d8a005728911e625aa155cba6d7fb0c Mon Sep 17 00:00:00 2001 From: Alexandra Date: Thu, 29 Oct 2026 10:42:11 +0100 Subject: [PATCH 1/5] Minor fixes and readMe issues fixed --- README.md | 51 ++++--- backend/.DS_Store | Bin 8196 -> 8196 bytes backend/README.md | 79 ----------- backend/src/server.ts | 3 - backend/tests/server.test.ts | 6 +- docs/ai-usage.md | 40 ++++-- docs/{ARCHITECTURE.md => architecture.md} | 130 ++++++++++-------- docs/quality.md | 6 +- docs/tests.md | 2 +- frontend/src/i18n/locales/en/translation.json | 1 + frontend/src/i18n/locales/no/translation.json | 1 + .../src/pages/explorePlants/ExplorePlants.tsx | 1 + frontend/src/tests/README.md | 0 .../__snapshots__/ExplorePage.test.tsx.snap | 15 ++ 14 files changed, 159 insertions(+), 176 deletions(-) delete mode 100644 backend/README.md rename docs/{ARCHITECTURE.md => architecture.md} (67%) delete mode 100644 frontend/src/tests/README.md diff --git a/README.md b/README.md index 6b09525d..a62a00f7 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,15 @@ http://it2810-03.idi.ntnu.no/project2/ ## Core features -- **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. 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, description, name and plant avtar is saved. +- **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. +- **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. - **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 +- **Theme:** The app has a light and a dark theme. ## Tech stack @@ -80,7 +79,27 @@ npm run dev This starts both the backend (http://localhost:3001) and the frontend. Open http://localhost:5173/project2/ in your browser. The frontend forwards `/graphql` requests to the backend, so both must be running. -See [backend/README.md](backend/README.md) for more details about the backend setup (in Norwegian). +## Deployment on the VM + +The deployed app runs on the VM `it2810-03.idi.ntnu.no`. Apache serves the frontend, and the backend and MongoDB run directly on the VM, not in Docker: + +```text +Browser ──> Apache (port 80, /project2) serves the built frontend + ──> Backend (port 3001, /graphql) run by pm2, Node.js + └──> MongoDB (127.0.0.1:27017) only reachable from the VM +``` + +### Backend + +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. + +### Database + +MongoDB is installed directly on the VM and only listens on `127.0.0.1`, so it cannot be reached from outside the VM. The plant data was loaded once with `npm run seed` in the backend (see [architecture.md](docs/architecture.md#data-source-the-perenual-api)). ## Testing @@ -90,7 +109,6 @@ 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 @@ -121,7 +139,7 @@ The coverage table is printed in the terminal. A detailed report is saved in `fr | Part | Statements | Branches | Functions | Lines | | -------- | ---------- | -------- | --------- | ------- | -| Frontend | 96.7 % | 94.73 % | 92.92 % | 98.33 % | +| Frontend | 96.7 % | 94.82 % | 92.92 % | 98.33 % | | Backend | 100 % | 100 % | 100 % | 100 % | - Frontend test coverage: @@ -132,17 +150,12 @@ The coverage table is printed in the terminal. A detailed report is saved in `fr Test coverage for the backend - -### 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. - ## Quality and design -See [quality.md](docs/quality.md) for Lighthouse results, testing, accessibility, design choices, sustainable web development -and work practices. +See [quality.md](docs/quality.md) for Lighthouse results, testing, accessibility, design choices, sustainable web development and work practices. ## Known issues + 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/.DS_Store b/backend/.DS_Store index 834e46ecd863f3eedbc134d5dc2066f512deaa73..ba02b014d9b3fc1148f0e5c0774fed72bfb7b4ff 100644 GIT binary patch delta 33 pcmZp1XmOa}&&atkU^hP_=VTs%t(!j!q%m(+=Xt=qnO)*9I{?793uyoV delta 64 zcmZp1XmOa}&&ahgU^hP_*JK`nt;(DXK@6@8jtnjgzCc=!A(tV=GbcYeDJMUPfq_AQ Tfq`+-=1l^n%$p-cR&xUY2saQC diff --git a/backend/README.md b/backend/README.md deleted file mode 100644 index 474fd160..00000000 --- a/backend/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Backend - -GraphQL-backend (Apollo Server) for I <3 Plants. Dataene ligger i MongoDB på VM-en `it2810-03.idi.ntnu.no`. - -Under utvikling kjører backenden på din egen maskin og kobler seg til MongoDB på VM-en gjennom en SSH-tunnel: - -``` -Din maskin VM (it2810-03) -backend (localhost:3001) ──tunnel──> MongoDB (port 27017) -``` - -MongoDB lytter bare på `127.0.0.1` på VM-en, så den kan ikke nås direkte utenfra. All tilgang går via SSH. - -## Kom i gang - -### 1. Koble til NTNU-nettet - -VM-en kan bare nås fra NTNU-nettet. Er du hjemme, må du koble til NTNU VPN først. - -### 2. Installer avhengigheter - -Inne i prosjekt i terminal kjør: - -```bash -cd backend -npm install -``` - -### 3. Lag `.env` - -```bash -cp .env.example .env -``` - -Du trenger ikke endre noe i den. `.env` står i `.gitignore` og skal aldri committes. - -### 4. Start SSH-tunnelen - -Åpne et **eget terminalvindu** på PCen din, bytt ut `` og kjør: - -```bash -ssh -N -L 27017:localhost:27017 @it2810-03.idi.ntnu.no -``` - -Når du har skrevet inn passordet, ser det ut som kommandoen henger. Det er riktig, og betyr at tunnelen er oppe. La vinduet stå åpent mens du jobber/ kjører prosjektet. Stopp tunnelen med `Ctrl+C` når du er ferdig med å kjøre prosjektet. - -Sjekk at tunnelen virker (i et annet vindu): - -```bash -nc -z localhost 27017 && echo "Tunnel OK" -``` - -### 5. Start backenden - -```bash -npm run dev -``` - -Du skal se: - -``` -Connected to MongoDB -Server Running at:http://localhost:3001/ -``` - -Da er DB koblingen satt opp riktig - -## Laste inn data på nytt - -`seedDataFetch.js` henter plantedata og bilder fra Perenual og lagrer det i MongoDB. Bildene fra Perenual er signerte lenker som går ut etter 24 timer, så scriptet laster ned bildet med en gang, base64-encoder det og lagrer det som data-URI i feltet `imageData` på hver plante. GraphQL returnerer dette som `imageURL`, og det kan brukes direkte i ``. - -Kjør med SSH-tunnelen oppe og `PERENUAL_API_KEY` satt i `.env`: - -```bash -npm run seed:reset # sletter plante databasen og laster alt inn på nytt -npm run seed # fyller bare inn det som mangler -``` - -Plantelisten hentes alltid fersk (ett API-kall per side, se `LIST_PAGES`). Svar fra `species/details` caches i `data/raw/` (ikke i git), så de bare hentes fra API-et første gang. Gratisnivået gir ca. 100 kall per dag. Stopper scriptet fordi kvoten er brukt opp, kjører du `npm run seed` igjen neste dag, så fortsetter det der det slapp. diff --git a/backend/src/server.ts b/backend/src/server.ts index 7a6a90a5..99a33ee7 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -334,9 +334,6 @@ const resolvers = { $options: "i", }; } - if (args.sunlight) { - filter.sunlight = new RegExp(`^${normalize(args.sunlight)}$`, "i"); - } if (args.watering) { filter.watering = new RegExp(`^${normalize(args.watering)}$`, "i"); } diff --git a/backend/tests/server.test.ts b/backend/tests/server.test.ts index fc4d025e..8c2b18bf 100644 --- a/backend/tests/server.test.ts +++ b/backend/tests/server.test.ts @@ -317,7 +317,6 @@ describe("plants", () => { expect((await explore({ careLevel: "high" })).names).toEqual(["Cactus"]); }); - it("filters on sunlight, matching any value in the list", async () => { expect((await explore({ sunlight: "full_sun" })).names).toEqual([ "Aloe", @@ -327,9 +326,8 @@ describe("plants", () => { "Basil", "Daisy", ]); - expect((await explore({ sunlight: "part_sun" })).names).toEqual([ - "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/ai-usage.md b/docs/ai-usage.md index c62f9f1d..a33d74c4 100644 --- a/docs/ai-usage.md +++ b/docs/ai-usage.md @@ -1,14 +1,36 @@ # AI usage -AI was used as an assistant throughout the development of the web application. It was mainly used for: +AI was used as an assistant throughout the development of the web application. The tools we used were Claude, ChatGPT and GitHub Copilot. -- **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 +## What AI was used for -All AI-generated suggestions were reviewed, tested, and adapted by the team before being committed. Design and architectural decisions were made by the team. +- **Setup and configuration:** setting up the project in VS Code, Vitest, and the project structure with backend and database. +- **Explaining technical concepts:** how the database, backend and frontend are related, and how to implement debounce. +- **Writing code:** suggestions for code, which were reviewed by the team before they were used. +- **Writing and reviewing tests:** drafting test files with mocked dependencies, and explaining the reasoning behind the test structure and snapshot testing. AI also suggested what should be tested to get better test coverage. +- **Writing documentation:** drafting and refining documentation and comments in the code. +- **Generating pictures:** the avatar pictures on the profile page were made with AI. -The AI modeles used where: Claud, ChatGPT and co-pilot. \ No newline at end of file +## Examples + +### The seed script + +AI helped us write [backend/seedDataFetch.js](../backend/seedDataFetch.js), which fetches the plant data from the Perenual API and stores it in MongoDB. This included: + +- downloading each image and storing it as a base64 data URI, because the image URLs from Perenual expire after 24 hours +- caching the raw responses locally, so the same plant is never requested twice +- stopping before the daily quota of about 100 requests is used up, so the script can be run again the next day and continue where it left off + +We decided which fields to keep and how they are mapped to the GraphQL schema, and we checked the data in the database after each run. + +### Avatar pictures + +The avatar pictures that the user can choose between on the profile page were generated with AI. We chose the plants and the style, and picked the pictures that fit the design of the app. + +### Tests and end-to-end tests + +AI drafted many of the Vitest tests and the Playwright e2e and API tests, and suggested atypical cases to test, such as special characters in the search, too long names and invalid ids. The team reviewed the tests, adjusted them, and ran them to check that they pass and fail for the right reasons. The accessibility tests found a real problem with the language button (see [tests.md](tests.md)), which we then fixed. + +## How we kept control + +All AI-generated suggestions were reviewed, tested and adapted by the team before they were committed. Every change went through a pull request that had to be approved by another group member (see [quality.md](quality.md#work-practices)), so no AI-generated code was merged without a review. Design and architectural decisions were made by the team. diff --git a/docs/ARCHITECTURE.md b/docs/architecture.md similarity index 67% rename from docs/ARCHITECTURE.md rename to docs/architecture.md index 791586bc..e1034c10 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/architecture.md @@ -69,21 +69,21 @@ 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. | +| 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. | +| `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. | +| 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`). | +| `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** @@ -103,34 +103,34 @@ The database `iloveplants` has two collections: `plants` and `users`. Both the p 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 | – | +| 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. @@ -140,15 +140,15 @@ Note: the image URLs from the Perenual API expire after 24 hours. That is why ea One document per user. There is no login: a user is created the first time someone opens the app, and the browser keeps the user id (see [Where state is kept](#where-state-is-kept)). The id is generated by MongoDB. -| Field | Type | Description | Exposed in GraphQL as | -| ----------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | -| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | -| `description` | string/null | Short profile text, at most 100 characters | `description` | -| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snake-plant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | -| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | -| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `matchedPlants` (resolved to full `Plant` objects) | -| `createdAt` | Date | When the user was created | `createdAt` (ISO string) | +| Field | Type | Description | Exposed in GraphQL as | +| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | +| `_id` | ObjectId | Set by MongoDB, and the id the browser stores | `id` | +| `name` | string/null | Display name, at most 40 characters. `null` means not chosen, and the frontend shows a translated default | `name` | +| `description` | string/null | Short profile text, at most 100 characters | `description` | +| `profilePicture` | string | Id of the chosen picture. One of the avatars (`default`, `monstera`, `pothos`, `snake-plant`, `anthurium`, `succulent`, `fern`, `orchid`) or a plant owner test result (`cityMinimalist`, `averageCityGardener`, `cityGardenerDreaming`, `countryMinimalist`, `averageCountryGardener`, `gardenExpert`) | `profilePicture` | +| `preferences` | string[] | Chosen plant preferences: `minimumWater`, `averageWater`, `frequentWater`, `fullSun`, `partShade`, `filteredShade`, `easyCare`, `mediumCare`, `hardCare` | `preferences` | +| `matchedPlantIds` | ObjectId[] | `_id`s of the plants the user has matched with, in the order they were matched | `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`). @@ -168,13 +168,13 @@ 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 | +| `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 | 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. @@ -211,7 +211,7 @@ We chose this approach for these reasons: ```text T03-Project-2/ -├── .github/ # CI workflow (lint, tests, build) and CODEOWNERS (required PR review) +├── .github/ # CI workflow (format, lint, tests, build, e2e) and CODEOWNERS (required PR review) ├── backend/ │ ├── src/ │ │ ├── db.ts # MongoDB connection (MongoDB driver, configured via .env) @@ -219,7 +219,8 @@ T03-Project-2/ │ ├── 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, ...) +├── docs/ # Project documentation (architecture, tests, quality, AI usage), media/ has the coverage images +├── e2e/ # Playwright e2e and API tests, test data (fixtures/) and the in-memory test database ├── frontend/ │ ├── src/ │ │ ├── assets/ # Static images @@ -234,5 +235,20 @@ T03-Project-2/ │ │ └── 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 +├── package.json # Scripts for running, testing and formatting the whole project from the root +├── playwright.config.ts # Playwright configuration: starts the test database, backend and frontend +└── README.md # Project overview, how to run, test and deploy the application ``` + +## How to start the backend if it stops + +On the VM, the backend runs in pm2 under the name `plants-backend`, as the user `alexajah`, from `/home/alexajah/T03-Project-2/backend`. pm2 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`). + +Log in with `ssh @it2810-03.idi.ntnu.no`. If you are not `alexajah` put `sudo -u alexajah` in front of the pm2 commands, since pm2 only shows the processes of the user who started them. + +```bash +pm2 list # is plants-backend online? +pm2 restart plants-backend # start it again if it is not +``` + +If the logs show that the backend cannot connect to MongoDB, the database has stopped, and must be started before the backend is restarted. diff --git a/docs/quality.md b/docs/quality.md index 7eb1ceda..09916052 100644 --- a/docs/quality.md +++ b/docs/quality.md @@ -10,11 +10,9 @@ 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. - +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 @@ -29,7 +27,7 @@ GitHub Actions ([.github/workflows/ci.yml](.github/workflows/ci.yml)) runs on ev - As part of our code review process, team members checked out pull requests locally and tested the new functionality before approving changes. This helped us verify that changes worked as expected in practice, rather than relying solely on code review. -## Testing +## Method behind testing Automated tests help ensure that the application works as intended and that new changes do not break existing functionality. The application is tested on three levels: component tests check each part of the frontend in isolation, backend tests check every GraphQL query and mutation against a real database, and end-to-end tests check that the whole application works together the way a user experiences it, on both desktop and mobile. diff --git a/docs/tests.md b/docs/tests.md index 182b780f..a967dc07 100644 --- a/docs/tests.md +++ b/docs/tests.md @@ -107,7 +107,6 @@ 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` @@ -139,6 +138,7 @@ The tests are in `frontend/src/tests`. Snapshot tests are used for the explore p - `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. diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 28a0377f..66ef2d0c 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -64,6 +64,7 @@ "part_sun": "Part sun", "part_shade": "Part shade", "careLevel": "Care level", + "low": "Low", "medium": "Medium", "high": "High", "pagination": "Page navigation", diff --git a/frontend/src/i18n/locales/no/translation.json b/frontend/src/i18n/locales/no/translation.json index ea5d77c1..62a40ed3 100644 --- a/frontend/src/i18n/locales/no/translation.json +++ b/frontend/src/i18n/locales/no/translation.json @@ -64,6 +64,7 @@ "part_sun": "Delvis sol", "part_shade": "Delvis skygge", "careLevel": "Stell", + "low": "Lav", "medium": "Middels", "high": "Høy", "pagination": "Sidenavigasjon", diff --git a/frontend/src/pages/explorePlants/ExplorePlants.tsx b/frontend/src/pages/explorePlants/ExplorePlants.tsx index 7a3c9c77..9690cd79 100644 --- a/frontend/src/pages/explorePlants/ExplorePlants.tsx +++ b/frontend/src/pages/explorePlants/ExplorePlants.tsx @@ -143,6 +143,7 @@ export default function ExplorePlants() { }} > + diff --git a/frontend/src/tests/README.md b/frontend/src/tests/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap b/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap index 35f7af01..ce9be46a 100644 --- a/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap +++ b/frontend/src/tests/__snapshots__/ExplorePage.test.tsx.snap @@ -115,6 +115,11 @@ exports[`ExplorePlants > snapshots > matches the snapshot of the page with no re > ExplorePlants.all + + +