Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ http://it2810-03.idi.ntnu.no/project2/

- **Plant Match:** Shows plants one at a time, best matches for your preferences first. Click ✿ to like a plant or ✖ to skip it.
- **Preferences:** Choose what you want from a plant: how much water it needs (minimum, average, frequent), how much sun it needs (full sun, part shade, filtered shade) and how much care it needs (easy, medium, hard). The preferences are saved in the database. Plant cards highlight the traits that match your preferences, and Plant Match shows the plants that match the most of your preferences first. Without preferences, the plants come in random order.
- **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants. You can also remove plants from the list.
- **My Matches:** A list of all the plants you have liked in Plant Match or added from Explore Plants, with the number of matches shown above. Sort them by newest, oldest or name (A–Z or Z–A), and move between pages when there are many. The sort order and page are stored in the URL, so they are kept on refresh. You can also remove plants from the list.
- **Explore Plants:** Search the plant collection by common or scientific name and filter by watering, sunlight and care level. Sort the plants alphabetically (A–Z or Z–A), by watering or by care level. Search, filtering and sorting run in the backend on the whole collection, and the number of results is shown above the plants. The results are split into pages, and you can jump straight to any page. The search, filters, sorting and current page are stored in the URL, so an Explore view can be refreshed or shared as a link. Add a plant to My Matches with the ✿ button, and click it again to remove it.
- **Plant details:** Each plant card shows an image, the scientific name, a description and care information (watering, sunlight and care level). Flip the card to read more about the plant.
- **Profile:** Your name, description, avatar and preferences are saved in the database, and your matched plants are shown here.
- **Profile:** Your name, description, avatar and preferences are saved in the database.
- **Plant Owner Test:** A short quiz that tells you what kind of plant owner you are. Each result has its own picture, which you can only get through the test, and you can save it as your profile picture.
- **Language:** The app is available in English and Norwegian.
- **Theme:** The app has a light and a dark theme.
Expand Down
32 changes: 31 additions & 1 deletion backend/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Document, Filter } from "mongodb";
import type { Document, Filter, ObjectId } from "mongodb";
import type { ExplorePlantsArgs, PlantDoc } from "./types.js";

// Helpers for searching, filtering and sorting plants
Expand Down Expand Up @@ -62,6 +62,36 @@ export const buildSortStages = (sort?: string): Document[] => {
}
};

// Builds the aggregation stages that sort the user's matched plants on My Matches.
// matchedPlantIds is in the order the plants were matched, so a plant's
// position in it tells how new the match is.
export const buildMatchSortStages = (
sort: string | undefined,
matchedPlantIds: ObjectId[],
): Document[] => {
const byMatchOrder = (direction: 1 | -1): Document[] => [
{
$addFields: {
matchOrder: { $indexOfArray: [matchedPlantIds, "$_id"] },
},
},
{ $sort: { matchOrder: direction } },
];

switch (sort) {
case "oldest":
return byMatchOrder(1);
case "name_asc":
return [{ $sort: { commonName: 1, _id: 1 } }];
case "name_desc":
return [{ $sort: { commonName: -1, _id: -1 } }];
default:
// Newest first is the default, since those are usually
// the ones the user wants to see
return byMatchOrder(-1);
}
};

// Builds the MongoDB filter for the search and filters on Explore Plants
export const buildExploreFilter = (
args: ExplorePlantsArgs,
Expand Down
51 changes: 38 additions & 13 deletions backend/src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import type { Document, WithId } from "mongodb";
import { db } from "./db.js";
import {
buildExploreFilter,
buildMatchSortStages,
buildSortStages,
matchScore,
PREFERENCE_MATCHERS,
} from "./helpers.js";
import type {
ExplorePlantsArgs,
GetPlantsArgs,
MyMatchesArgs,
Plant,
PlantDoc,
UpdateUserPreferencesArgs,
Expand Down Expand Up @@ -200,6 +202,37 @@ export const resolvers = {
const doc = await users.findOne({ _id });
return doc ? toUser(doc) : null;
},

// One page of the user's matched plants, sorted. Only the ids are stored on
// the user, so the plants are looked up and sorted in the plants collection.
// An unknown or malformed user id gives an empty page.
myMatches: async (
_parent: unknown,
args: MyMatchesArgs,
): Promise<{ plants: Plant[]; totalCount: number }> => {
const _id = toObjectId(args.userId);
const user = _id
? await users.findOne({ _id }, { projection: { matchedPlantIds: 1 } })
: null;
const matchedPlantIds = user?.matchedPlantIds ?? [];
if (matchedPlantIds.length === 0) return { plants: [], totalCount: 0 };

// Only plants that still exist are shown and counted (e.g. after a reseed)
const filter = { _id: { $in: matchedPlantIds } };
const [docs, totalCount] = await Promise.all([
plants
.aggregate<WithId<PlantDoc>>([
{ $match: filter },
...buildMatchSortStages(args.sort, matchedPlantIds),
{ $skip: args.offset },
{ $limit: args.limit },
])
.toArray(),
plants.countDocuments(filter),
]);

return { plants: docs.map(toPlant), totalCount };
},
},

Mutation: {
Expand Down Expand Up @@ -282,18 +315,10 @@ export const resolvers = {
},

User: {
// Looks up the matched plants, in the order they were matched.
// Ids of plants that no longer exist (e.g. after a reseed) are skipped.
matchedPlants: async (user: User): Promise<Plant[]> => {
if (user.matchedPlantIds.length === 0) return [];
const docs = await plants
.find({ _id: { $in: user.matchedPlantIds } })
.toArray();
const byId = new Map(docs.map((doc) => [doc._id.toString(), doc]));
return user.matchedPlantIds.flatMap((id) => {
const doc = byId.get(id.toString());
return doc ? [toPlant(doc)] : [];
});
},
// Only the ids of the matched plants, so pages that just need to know
// whether a plant is matched don't fetch the whole plants with images.
// My Matches gets the plants themselves from the myMatches query.
matchedPlantIds: (user: User): string[] =>
user.matchedPlantIds.map((id) => id.toString()),
},
};
8 changes: 7 additions & 1 deletion backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export const typeDefs = `
offset: Int = 0
): PlantPage!
getUser(userId: ID!): User
myMatches(
userId: ID!
sort: String
limit: Int = 12
offset: Int = 0
): PlantPage!
}
type Mutation {
Expand Down Expand Up @@ -49,7 +55,7 @@ export const typeDefs = `
description: String
profilePicture: String!
preferences: [String!]!
matchedPlants: [Plant!]!
matchedPlantIds: [ID!]!
createdAt: String!
}
`;
13 changes: 10 additions & 3 deletions backend/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,14 @@ export interface UserDoc {
description: string | null;
profilePicture: string;
preferences: string[];
// Only the plant ids are stored, the plants are looked up in User.matchedPlants
// Only the plant ids are stored, in the order the plants were matched.
// The plants themselves are looked up by the myMatches query.
matchedPlantIds: ObjectId[];
createdAt: Date;
}

// The shape of a User in the GraphQL API. matchedPlantIds is not in the schema,
// it is only passed on to the User.matchedPlants resolver.
// The shape of a User in the GraphQL API. matchedPlantIds is turned into
// strings by the User.matchedPlantIds resolver.
export interface User {
id: string;
name: string | null;
Expand Down Expand Up @@ -85,3 +86,9 @@ export interface UpdateUserPreferencesArgs extends UserIdArgs {
export interface UserMatchArgs extends UserIdArgs {
plantId: string;
}

export interface MyMatchesArgs extends UserIdArgs {
sort?: string;
limit: number;
offset: number;
}
119 changes: 93 additions & 26 deletions backend/tests/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ const USER_FIELDS = `
description
profilePicture
preferences
matchedPlants { id name }
matchedPlantIds
createdAt
`;

Expand All @@ -105,7 +105,7 @@ type User = {
description: string | null;
profilePicture: string;
preferences: string[];
matchedPlants: { id: string; name: string }[];
matchedPlantIds: string[];
createdAt: string;
};

Expand Down Expand Up @@ -444,7 +444,7 @@ describe("users", () => {
description: null,
profilePicture: "default",
preferences: [],
matchedPlants: [],
matchedPlantIds: [],
});
expect((await getUser(user.id)).data?.getUser).toEqual(user);
});
Expand Down Expand Up @@ -539,41 +539,108 @@ describe("users", () => {
await addMatch(id, fern);
await addMatch(id, orchid);
const added = await addMatch(id, orchid);
expect(added.data?.addUserMatch?.matchedPlants).toEqual([
{ id: fern, name: "Fern" },
{ id: orchid, name: "Orchid" },
]);
expect(added.data?.addUserMatch?.matchedPlantIds).toEqual([fern, orchid]);

const removed = await removeMatch(id, fern);
expect(removed.data?.removeUserMatch?.matchedPlants).toEqual([
{ id: orchid, name: "Orchid" },
]);
expect(removed.data?.removeUserMatch?.matchedPlantIds).toEqual([orchid]);
});

it("skips matched plants that were deleted from the database", async () => {
it.each([
["an id that does not exist", new ObjectId().toString()],
["a malformed id", "not-an-id"],
])("returns null without an error for %s", async (_, userId) => {
expect(await getUser(userId)).toEqual({ data: { getUser: null } });
expect((await updateProfile({ userId, name: "Nina" })).data).toEqual({
updateUserProfile: null,
});
});
});

describe("my matches", () => {
const MY_MATCHES = `
query ($userId: ID!, $sort: String, $limit: Int, $offset: Int) {
myMatches(userId: $userId, sort: $sort, limit: $limit, offset: $offset) {
totalCount
plants { name }
}
}
`;

type Page = { totalCount: number; plants: { name: string }[] };

// The names on one page of My Matches, and the total number of matches
async function myMatches(variables: Record<string, unknown>) {
const result = await execute<{ myMatches: Page }>(MY_MATCHES, variables);
expect(result.errors).toBeUndefined();
const page = result.data!.myMatches;
return {
names: page.plants.map((p) => p.name),
totalCount: page.totalCount,
};
}

// Matches Basil, Cactus and Aloe in that order, so that newest, oldest,
// A–Z and Z–A all give a different order
async function userWithMatches() {
const { id } = await createUser();
const [orchid, fern] = await insertPlants(
{ commonName: "Orchid" },
{ commonName: "Fern" },
const [aloe, basil, cactus] = await insertPlants(
{ commonName: "Aloe" },
{ commonName: "Basil" },
{ commonName: "Cactus" },
);
await addMatch(id, orchid);
await addMatch(id, fern);
await db.collection("plants").deleteOne({ _id: new ObjectId(orchid) });
for (const plantId of [basil, cactus, aloe]) {
await addMatch(id, plantId);
}
return { id, aloe };
}

const result = await getUser(id);
it.each([
["no sort (newest first)", undefined, ["Aloe", "Cactus", "Basil"]],
["oldest", "oldest", ["Basil", "Cactus", "Aloe"]],
["name_asc", "name_asc", ["Aloe", "Basil", "Cactus"]],
["name_desc", "name_desc", ["Cactus", "Basil", "Aloe"]],
])("sorts with %s", async (_, sort, expected) => {
const { id } = await userWithMatches();

expect(await myMatches({ userId: id, sort })).toEqual({
names: expected,
totalCount: 3,
});
});

expect(result.data?.getUser?.matchedPlants).toEqual([
{ id: fern, name: "Fern" },
]);
it("returns one page at a time with the total count", async () => {
const { id } = await userWithMatches();

expect(await myMatches({ userId: id, limit: 2 })).toEqual({
names: ["Aloe", "Cactus"],
totalCount: 3,
});
expect(await myMatches({ userId: id, limit: 2, offset: 2 })).toEqual({
names: ["Basil"],
totalCount: 3,
});
});

it("leaves out and does not count matched plants that were deleted", async () => {
const { id, aloe } = await userWithMatches();
await db.collection("plants").deleteOne({ _id: new ObjectId(aloe) });

expect(await myMatches({ userId: id })).toEqual({
names: ["Cactus", "Basil"],
totalCount: 2,
});
});

it.each([
["a user without matches", null],
["an id that does not exist", new ObjectId().toString()],
["a malformed id", "not-an-id"],
])("returns null without an error for %s", async (_, userId) => {
expect(await getUser(userId)).toEqual({ data: { getUser: null } });
expect((await updateProfile({ userId, name: "Nina" })).data).toEqual({
updateUserProfile: null,
])("returns an empty page for %s", async (_, userId) => {
const id = userId ?? (await createUser()).id;

expect(await myMatches({ userId: id })).toEqual({
names: [],
totalCount: 0,
});
});
});
Expand Down Expand Up @@ -641,7 +708,7 @@ describe("error messages", () => {
message: `Unknown plant: ${plantId}`,
code: "BAD_USER_INPUT",
});
expect((await getUser(id)).data?.getUser?.matchedPlants).toEqual([]);
expect((await getUser(id)).data?.getUser?.matchedPlantIds).toEqual([]);
});

it("rejects removing a malformed plant id", async () => {
Expand Down
4 changes: 4 additions & 0 deletions docs/ai-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,7 @@ After the peer reviews, we used AI to help us split up `ExplorePlants.tsx`, whic
## How we kept control

All AI-generated suggestions were reviewed, tested and adapted by the team before they were committed. Every change went through a pull request that had to be approved by another group member (see [quality.md](quality.md#work-practices)), so no AI-generated code was merged without a review. Design and architectural decisions were made by the team.

### Being critical of a suggestion from AI

We did not always follow the suggestions from AI. For example, when My Matches was changed to fetch one page of plants at a time, the old `matchedPlants` field on the user was no longer used by the app. AI first suggested keeping the field because the tests used it, but we decided to remove it, since keeping unused code only for the tests made no sense. Before removing it, we searched the code for every place it was used, to make sure it was safe. Then we updated the tests to use the new field, and wrote new tests for the `myMatches` query.
Loading
Loading