diff --git a/.github/workflows/jest.yml b/.github/workflows/backend_tests.yml similarity index 92% rename from .github/workflows/jest.yml rename to .github/workflows/backend_tests.yml index 8fb2c7eaa..5beeddace 100644 --- a/.github/workflows/jest.yml +++ b/.github/workflows/backend_tests.yml @@ -1,4 +1,4 @@ -name: Jest run +name: Backend tests on: push: @@ -7,7 +7,7 @@ on: branches: ['**'] jobs: - jest-tests: + backend-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/frontend_tests.yml b/.github/workflows/frontend_tests.yml new file mode 100644 index 000000000..94b82e282 --- /dev/null +++ b/.github/workflows/frontend_tests.yml @@ -0,0 +1,19 @@ +name: Frontend tests + +on: + push: + branches: ['**'] + pull_request: + branches: ['**'] + +jobs: + frontend-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24.x + cache: 'yarn' + - run: yarn install --frozen-lockfile + - run: npx vitest run --root apps/frontend diff --git a/apps/backend/src/animals/animals.controller.spec.ts b/apps/backend/src/animals/animals.controller.spec.ts new file mode 100644 index 000000000..80a420593 --- /dev/null +++ b/apps/backend/src/animals/animals.controller.spec.ts @@ -0,0 +1,46 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { AnimalsController } from './animals.controller'; +import { AnimalsService } from './animals.service'; +import { Animal } from './animals.entity'; + +describe('AnimalsController', () => { + let controller: AnimalsController; + let service: { findAll: jest.Mock }; + + beforeEach(async () => { + service = { findAll: jest.fn() }; + + const module: TestingModule = await Test.createTestingModule({ + controllers: [AnimalsController], + providers: [{ provide: AnimalsService, useValue: service }], + }).compile(); + + controller = module.get(AnimalsController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); + + describe('getAnimals', () => { + it('returns the animals from the service', async () => { + const animals = [{ animalId: 1 }, { animalId: 2 }] as Animal[]; + service.findAll.mockResolvedValue(animals); + + await expect(controller.getAnimals()).resolves.toBe(animals); + expect(service.findAll).toHaveBeenCalledTimes(1); + }); + + it('returns an empty array when there are no animals', async () => { + service.findAll.mockResolvedValue([]); + + await expect(controller.getAnimals()).resolves.toEqual([]); + }); + + it('propagates service errors', async () => { + service.findAll.mockRejectedValue(new Error('db down')); + + await expect(controller.getAnimals()).rejects.toThrow('db down'); + }); + }); +}); diff --git a/apps/backend/src/animals/animals.controller.ts b/apps/backend/src/animals/animals.controller.ts new file mode 100644 index 000000000..9a16a70d6 --- /dev/null +++ b/apps/backend/src/animals/animals.controller.ts @@ -0,0 +1,25 @@ +import { Controller, Get, HttpStatus } from '@nestjs/common'; +import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { AnimalsService } from './animals.service'; +import { Animal } from './animals.entity'; + +@ApiTags('Animals') +@Controller('animals') +export class AnimalsController { + constructor(private animalsService: AnimalsService) {} + + @Get() + @ApiOperation({ + summary: 'Get all available animals', + description: + 'Returns every animal. All animals in the database are currently treated as available.', + }) + @ApiResponse({ + status: HttpStatus.OK, + description: 'The animals, or an empty array when none are available.', + type: [Animal], + }) + async getAnimals(): Promise { + return this.animalsService.findAll(); + } +} diff --git a/apps/backend/src/animals/animals.module.ts b/apps/backend/src/animals/animals.module.ts index 271ff80ce..b43bbd775 100644 --- a/apps/backend/src/animals/animals.module.ts +++ b/apps/backend/src/animals/animals.module.ts @@ -1,10 +1,12 @@ import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Animal } from './animals.entity'; +import { AnimalsController } from './animals.controller'; import { AnimalsService } from './animals.service'; @Module({ imports: [TypeOrmModule.forFeature([Animal])], + controllers: [AnimalsController], providers: [AnimalsService], exports: [AnimalsService], }) diff --git a/apps/backend/src/animals/animals.service.spec.ts b/apps/backend/src/animals/animals.service.spec.ts index dd6df1f83..182efe51e 100644 --- a/apps/backend/src/animals/animals.service.spec.ts +++ b/apps/backend/src/animals/animals.service.spec.ts @@ -45,6 +45,23 @@ describe('AnimalsService', () => { expect(service).toBeDefined(); }); + describe('findAll', () => { + it('returns every animal', async () => { + mockRepo.find.mockResolvedValue([mockAnimal]); + + const result = await service.findAll(); + + expect(result).toEqual([mockAnimal]); + expect(mockRepo.find).toHaveBeenCalledWith(); + }); + + it('returns an empty array when there are no animals', async () => { + mockRepo.find.mockResolvedValue([]); + + await expect(service.findAll()).resolves.toEqual([]); + }); + }); + describe('findByChameleonIdOrFail', () => { it('returns the animal when one with the Chameleon ID exists', async () => { mockRepo.findOneBy.mockResolvedValue(mockAnimal); diff --git a/apps/backend/src/animals/animals.service.ts b/apps/backend/src/animals/animals.service.ts index 2167a65b4..bcbf2525a 100644 --- a/apps/backend/src/animals/animals.service.ts +++ b/apps/backend/src/animals/animals.service.ts @@ -10,6 +10,18 @@ export class AnimalsService { private repo: Repository, ) {} + /** + * Fetches every available Animal. + * + * There is no availability tracking yet, so every Animal in the database is + * treated as available. + * + * @returns All Animals, or an empty array when there are none. + */ + async findAll(): Promise { + return this.repo.find(); + } + /** * Fetches an Animal by its Chameleon animal ID. * diff --git a/apps/backend/src/config/migrations.ts b/apps/backend/src/config/migrations.ts index f702dcdd8..9316b2a32 100644 --- a/apps/backend/src/config/migrations.ts +++ b/apps/backend/src/config/migrations.ts @@ -12,6 +12,7 @@ import { AddAnimalUpdatesAndFosterTypeArray1793163582751 } from '../migrations/1 import { AddFarmAnimalsToFosterType1793476100199 } from '../migrations/1793476100199-AddFarmAnimalsToFosterType'; import { RenameAdminUsersToOwners1793485161630 } from '../migrations/1793485161630-RenameAdminUsersToOwners'; import { AddFosterTypePreferences1793600000000 } from '../migrations/1793600000000-AddFosterTypePreferences'; +import { AddMatchAdditionalComments1794784721012 } from '../migrations/1794784721012-AddMatchAdditionalComments'; const schemaMigrations = [ InitialSchemas1789354568323, @@ -28,6 +29,7 @@ const schemaMigrations = [ AddFarmAnimalsToFosterType1793476100199, RenameAdminUsersToOwners1793485161630, AddFosterTypePreferences1793600000000, + AddMatchAdditionalComments1794784721012, ]; export default schemaMigrations; diff --git a/apps/backend/src/matches/dtos/create-match.dto.ts b/apps/backend/src/matches/dtos/create-match.dto.ts index 0d9c13491..236d1262b 100644 --- a/apps/backend/src/matches/dtos/create-match.dto.ts +++ b/apps/backend/src/matches/dtos/create-match.dto.ts @@ -1,4 +1,4 @@ -import { IsInt, IsPositive, MaxLength } from 'class-validator'; +import { IsInt, IsPositive, MaxLength, ValidateIf } from 'class-validator'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; export class CreateMatchDto { @@ -9,4 +9,8 @@ export class CreateMatchDto { @IsNonEmptyString() @MaxLength(255) chameleonAnimalId!: string; + + @ValidateIf((_, value) => value !== undefined && value !== null) + @IsNonEmptyString() + additionalComments?: string; } diff --git a/apps/backend/src/matches/matches.entity.ts b/apps/backend/src/matches/matches.entity.ts index b0e27fc28..096c7e78e 100644 --- a/apps/backend/src/matches/matches.entity.ts +++ b/apps/backend/src/matches/matches.entity.ts @@ -36,6 +36,9 @@ export class Match { @Column({ type: 'enum', enum: MatchStatus }) status!: MatchStatus; + @Column({ name: 'additional_comments', type: 'text', nullable: true }) + additionalComments!: string | null; + @Column({ name: 'denied_reason', type: 'text', nullable: true }) deniedReason!: string | null; } diff --git a/apps/backend/src/matches/matches.service.spec.ts b/apps/backend/src/matches/matches.service.spec.ts index 2bc506757..6c3427e2a 100644 --- a/apps/backend/src/matches/matches.service.spec.ts +++ b/apps/backend/src/matches/matches.service.spec.ts @@ -1,6 +1,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { getRepositoryToken } from '@nestjs/typeorm'; -import { BadRequestException, Logger, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + ConflictException, + Logger, + NotFoundException, +} from '@nestjs/common'; import { MatchesService } from './matches.service'; import { Match } from './matches.entity'; import { MatchStatus } from './matches.types'; @@ -11,6 +16,7 @@ import { VolunteersService } from '../volunteers/volunteers.service'; import { AnimalsService } from '../animals/animals.service'; import { EmailsService } from '../aws/ses/email.service'; import { SendEmailDTO } from '../aws/ses/sendEmail.dto'; +import { In } from 'typeorm'; const coordinator = { coordinatorId: 7, @@ -189,11 +195,91 @@ describe('MatchesService', () => { volunteerId: 1, chameleonAnimalId: 'A42', status: MatchStatus.PENDING, + additionalComments: null, deniedReason: null, }); expect(match.status).toEqual(MatchStatus.PENDING); }); + it('throws ConflictException when the volunteer already has a PENDING match for the animal', async () => { + volunteersService.findActiveOrFail.mockResolvedValue( + volunteerWithCoordinator, + ); + matchRepo.findOneBy.mockResolvedValue({ + matchId: 5, + volunteerId: 1, + chameleonAnimalId: 'A42', + status: MatchStatus.PENDING, + }); + + await expect( + service.create({ volunteerId: 1, chameleonAnimalId: 'A42' }), + ).rejects.toThrow(ConflictException); + expect(matchRepo.save).not.toHaveBeenCalled(); + expect(emailsService.sendEmail).not.toHaveBeenCalled(); + }); + + it('only treats PENDING and ACTIVE matches as duplicates', async () => { + volunteersService.findActiveOrFail.mockResolvedValue( + volunteerWithCoordinator, + ); + emailsService.sendEmail.mockResolvedValue(undefined); + const existingMatches = [ + { + matchId: 5, + volunteerId: 1, + chameleonAnimalId: 'A42', + status: MatchStatus.WITHDRAWN, + }, + ]; + matchRepo.findOneBy.mockImplementation( + async (where) => + existingMatches.find( + (m) => + m.volunteerId === where.volunteerId && + m.chameleonAnimalId === where.chameleonAnimalId && + where.status.value.includes(m.status), + ) ?? null, + ); + matchRepo.create.mockImplementation((attrs) => attrs); + matchRepo.save.mockImplementation((match) => + Promise.resolve({ matchId: 10, ...match }), + ); + + await service.create({ volunteerId: 1, chameleonAnimalId: 'A42' }); + + expect(matchRepo.findOneBy).toHaveBeenCalledWith({ + volunteerId: 1, + chameleonAnimalId: 'A42', + status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), + }); + expect(matchRepo.save).toHaveBeenCalled(); + }); + + it('saves additional comments when provided', async () => { + volunteersService.findActiveOrFail.mockResolvedValue( + volunteerWithCoordinator, + ); + emailsService.sendEmail.mockResolvedValue(undefined); + matchRepo.create.mockImplementation((attrs) => attrs); + matchRepo.save.mockImplementation((match) => + Promise.resolve({ matchId: 10, ...match }), + ); + + const match = await service.create({ + volunteerId: 1, + chameleonAnimalId: 'A42', + additionalComments: 'Can pick up on weekends', + }); + + expect(matchRepo.create).toHaveBeenCalledWith( + expect.objectContaining({ + additionalComments: 'Can pick up on weekends', + }), + ); + expect(match.additionalComments).toEqual('Can pick up on weekends'); + }); + it("emails the sender address with the volunteer's assigned coordinator cc'd", async () => { volunteersService.findActiveOrFail.mockResolvedValue( volunteerWithCoordinator, diff --git a/apps/backend/src/matches/matches.service.ts b/apps/backend/src/matches/matches.service.ts index c23cf47b6..b22f1fe85 100644 --- a/apps/backend/src/matches/matches.service.ts +++ b/apps/backend/src/matches/matches.service.ts @@ -1,5 +1,6 @@ import { BadRequestException, + ConflictException, Inject, Injectable, Logger, @@ -7,7 +8,7 @@ import { forwardRef, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; -import { Not, Repository } from 'typeorm'; +import { In, Not, Repository } from 'typeorm'; import { Match } from './matches.entity'; import { MatchStatus } from './matches.types'; import { CreateMatchDto } from './dtos/create-match.dto'; @@ -43,6 +44,7 @@ export class MatchesService { * @returns the created match * @throws NotFoundException if the volunteer or animal does not exist * @throws BadRequestException if the volunteer is not active + * @throws ConflictException if the volunteer already has a PENDING or ACTIVE match for the animal */ async create(dto: CreateMatchDto): Promise { const volunteer = await this.volunteersService.findActiveOrFail( @@ -50,11 +52,23 @@ export class MatchesService { ); await this.animalsService.findByChameleonIdOrFail(dto.chameleonAnimalId); + const existingMatch = await this.repo.findOneBy({ + volunteerId: dto.volunteerId, + chameleonAnimalId: dto.chameleonAnimalId, + status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), + }); + if (existingMatch) { + throw new ConflictException( + `Volunteer ${dto.volunteerId} already has a ${existingMatch.status} match for animal ${dto.chameleonAnimalId}`, + ); + } + const match = await this.repo.save( this.repo.create({ volunteerId: dto.volunteerId, chameleonAnimalId: dto.chameleonAnimalId, status: MatchStatus.PENDING, + additionalComments: dto.additionalComments ?? null, deniedReason: null, }), ); diff --git a/apps/backend/src/migrations/1794784721012-AddMatchAdditionalComments.ts b/apps/backend/src/migrations/1794784721012-AddMatchAdditionalComments.ts new file mode 100644 index 000000000..7429d9b96 --- /dev/null +++ b/apps/backend/src/migrations/1794784721012-AddMatchAdditionalComments.ts @@ -0,0 +1,17 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddMatchAdditionalComments1794784721012 + implements MigrationInterface +{ + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "matches" ADD COLUMN "additional_comments" text`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "matches" DROP COLUMN "additional_comments"`, + ); + } +} diff --git a/apps/frontend/src/api/apiClient.ts b/apps/frontend/src/api/apiClient.ts index 8f549b0a9..30f61ad94 100644 --- a/apps/frontend/src/api/apiClient.ts +++ b/apps/frontend/src/api/apiClient.ts @@ -2,6 +2,7 @@ import axios, { type AxiosInstance } from 'axios'; import { fetchAuthSession } from 'aws-amplify/auth'; import { isAuthEnabled } from '../auth/auth.config'; +import type { Animal, CreateMatchBody, Match, Volunteer } from '../types'; const defaultBaseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000'; @@ -45,6 +46,18 @@ export class ApiClient { }); } + public async getAnimals(): Promise { + return this.get('/api/animals') as Promise; + } + + public async getVolunteer(volunteerId: number): Promise { + return this.get(`/api/volunteers/${volunteerId}`) as Promise; + } + + public async createMatch(body: CreateMatchBody): Promise { + return this.post('/api/matches', body) as Promise; + } + public async getHello(): Promise { return this.get('/api') as Promise; } diff --git a/apps/frontend/src/app.spec.tsx b/apps/frontend/src/app.spec.tsx deleted file mode 100644 index 95caf44df..000000000 --- a/apps/frontend/src/app.spec.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { render } from '@testing-library/react'; - -import App from './app'; - -describe('App', () => { - it('should render successfully', () => { - const { baseElement } = render(); - expect(baseElement).toBeTruthy(); - }); - - it('should have a greeting as the title', () => { - const { getByText } = render(); - expect(getByText(/Welcome frontend/gi)).toBeTruthy(); - }); -}); diff --git a/apps/frontend/src/app.tsx b/apps/frontend/src/app.tsx index a51df65b5..50e2a746b 100644 --- a/apps/frontend/src/app.tsx +++ b/apps/frontend/src/app.tsx @@ -1,22 +1,41 @@ import { useEffect } from 'react'; -import { createBrowserRouter, RouterProvider } from 'react-router-dom'; +import { + createBrowserRouter, + RouterProvider, + type RouteObject, +} from 'react-router-dom'; import apiClient from '@api/apiClient'; import Root from '@containers/root'; +import Layout from '@containers/Layout'; import NotFound from '@containers/404'; -import Test from '@containers/test'; +import AnimalAvailability from '@pages/AnimalAvailability'; +import { ROUTES } from './routes'; -const router = createBrowserRouter([ +// Every page is a child of Layout so the navbar renders once, above all pages. +// Page errors are caught by the inner errorElement so the navbar stays put; +// the outer one only catches errors from the layout itself. +export const routes: RouteObject[] = [ { - path: '/', - element: , + element: , errorElement: , + children: [ + { + errorElement: , + children: [ + { path: '/', element: }, + { + path: ROUTES.ANIMAL_AVAILABILITY, + element: , + }, + { path: '*', element: }, + ], + }, + ], }, - { - path: '/test', - element: , - }, -]); +]; + +const router = createBrowserRouter(routes); export const App: React.FC = () => { useEffect(() => { diff --git a/apps/frontend/src/assets/cat.png b/apps/frontend/src/assets/cat.png new file mode 100644 index 000000000..64b29449c Binary files /dev/null and b/apps/frontend/src/assets/cat.png differ diff --git a/apps/frontend/src/assets/mspca-logo.png b/apps/frontend/src/assets/mspca-logo.png new file mode 100644 index 000000000..071f4a36d Binary files /dev/null and b/apps/frontend/src/assets/mspca-logo.png differ diff --git a/apps/frontend/src/components/AnimalCard.tsx b/apps/frontend/src/components/AnimalCard.tsx new file mode 100644 index 000000000..6e6f5a559 --- /dev/null +++ b/apps/frontend/src/components/AnimalCard.tsx @@ -0,0 +1,105 @@ +import { Box, Button, Flex, Icon, Image, Text } from '@chakra-ui/react'; +import { House } from 'lucide-react'; + +import type { Animal } from '../types'; +import { HOMEBASE_ADDRESSES, formatAge } from '@utils/animals'; +import RestrictionTag from './RestrictionTag'; +import catImage from '../assets/cat.png'; + +// TODO: swap for animal.picture once animal images are supported. +export const PLACEHOLDER_IMAGE = catImage; + +interface AnimalCardProps { + animal: Animal; + onSeeMore: (animal: Animal) => void; +} + +/** + * A summary card for one adoptable animal, shown in the grid on the Animal + * Availability page. + * + * Shows the animal's photo, name, breed, age, restriction tags and the address + * of the homebase it's at, with a "See More" button that calls `onSeeMore` so + * the page can open the animal's detail modal. The card holds no state of its + * own: everything it displays comes from the `animal` prop. + */ +const AnimalCard: React.FC = ({ animal, onSeeMore }) => ( + + {animal.name} + + + + + {animal.name} + + + {animal.breed.join(', ')} + + + + + + + + {formatAge(animal.ageYear, animal.ageMonth)} + + + {animal.restrictions.length > 0 && ( + + {animal.restrictions.map((label) => ( + + ))} + + )} + + {HOMEBASE_ADDRESSES[animal.location]} + + + + + +); + +export default AnimalCard; diff --git a/apps/frontend/src/components/AnimalFilters.tsx b/apps/frontend/src/components/AnimalFilters.tsx new file mode 100644 index 000000000..c48a51cf1 --- /dev/null +++ b/apps/frontend/src/components/AnimalFilters.tsx @@ -0,0 +1,388 @@ +import { useState } from 'react'; +import { + Box, + Button, + Checkbox, + Flex, + Icon, + Popover, + Portal, + Text, +} from '@chakra-ui/react'; +import { ChevronDown, ListFilter, X } from 'lucide-react'; + +import { + EMPTY_FILTERS, + HOMEBASE_LABELS, + RESTRICTIONS, + type AnimalFilterState, +} from '@utils/animals'; +import { FosterType, Homebase, type Restriction } from '../types'; + +type CategoryKey = keyof AnimalFilterState; + +interface AnimalFiltersProps { + value: AnimalFilterState; + onChange: (filters: AnimalFilterState) => void; +} + +interface FilterOption { + label: string; + displayLabel?: string; + color: string; +} + +interface FilterSectionProps { + title: string; + options: readonly FilterOption[]; + selected: string[]; + onToggle: (option: string) => void; +} + +/** + * One collapsible group of checkboxes inside the filters popover (e.g. "Animal + * Type"). Clicking the title expands or collapses its options; ticking one + * calls `onToggle` with that option's label. Each option's checkbox is filled + * with its own `color` when checked. + */ +const FilterSection: React.FC = ({ + title, + options, + selected, + onToggle, +}) => { + const [open, setOpen] = useState(false); + + return ( + + + setOpen((o) => !o)} + > + + {title} + + + + + + + + {open && ( + + {options.map((option) => { + const checked = selected.includes(option.label); + return ( + onToggle(option.label)} + alignSelf="stretch" + justifyContent="flex-start" + alignItems="center" + gap="2" + > + + + + + + {option.displayLabel ?? option.label} + + + ); + })} + + )} + + ); +}; + +/** Small grey action button used for "Cancel" and "Apply" in the popover footer. */ +const PanelButton: React.FC<{ + onClick: () => void; + children: React.ReactNode; +}> = ({ onClick, children }) => ( + +); + +/** + * The filter bar above the animal grid. + * + * A filter button opens a popover with collapsible sections for Animal Type, + * Restrictions and Location. Selections are held as a draft while the popover + * is open and only filter the grid once Apply is pressed (`onChange` is called + * with the new `AnimalFilterState`). Next to the button, "Clear Filters" resets + * everything, and each selected restriction or location is shown as a chip + * that removes itself when clicked. Animal type selections filter the grid + * but don't get a chip. + */ +const AnimalFilters: React.FC = ({ value, onChange }) => { + const [open, setOpen] = useState(false); + // Edits are held in a draft until Apply is pressed. + const [draft, setDraft] = useState(value); + + const handleOpenChange = (isOpen: boolean) => { + if (isOpen) setDraft(value); + setOpen(isOpen); + }; + + const toggleDraft = (key: CategoryKey, option: string) => + setDraft((prev) => { + const selected: string[] = prev[key]; + return { + ...prev, + [key]: selected.includes(option) + ? selected.filter((o) => o !== option) + : [...selected, option], + }; + }); + + // While the panel is open the chips mirror the draft selection, so they show + // up immediately as options are ticked. Apply is what filters the grid. + const shown = open ? draft : value; + + const removeChip = (key: CategoryKey, option: string) => { + const selected: string[] = shown[key]; + const next = { ...shown, [key]: selected.filter((o) => o !== option) }; + if (open) setDraft(next); + else onChange(next); + }; + + // Animal type selections filter the grid but don't get a chip. + const chips = (Object.keys(shown) as CategoryKey[]) + .filter((key) => key !== 'types') + .flatMap((key) => + shown[key].map((label) => ({ + key, + label, + color: + key === 'restrictions' + ? RESTRICTIONS[label as Restriction].color + : 'neutrals.black', + })), + ); + + return ( + + + handleOpenChange(e.open)} + positioning={{ placement: 'bottom-start' }} + > + + + + + + + + + + Filters + + + + ({ + label, + color: 'neutral.solid', + }))} + selected={draft.types} + onToggle={(o) => toggleDraft('types', o)} + /> + toggleDraft('restrictions', o)} + /> + ({ + label, + displayLabel: HOMEBASE_LABELS[label], + color: 'neutral.solid', + }))} + selected={draft.locations} + onToggle={(o) => toggleDraft('locations', o)} + /> + + + handleOpenChange(false)}> + Cancel + + { + onChange(draft); + setOpen(false); + }} + > + Apply + + + + + + + + + + + + {chips.map((chip) => ( + + ))} + + + + ); +}; + +export default AnimalFilters; diff --git a/apps/frontend/src/components/Navbar.tsx b/apps/frontend/src/components/Navbar.tsx new file mode 100644 index 000000000..c944ec82a --- /dev/null +++ b/apps/frontend/src/components/Navbar.tsx @@ -0,0 +1,96 @@ +import { useEffect, useState } from 'react'; +import { Button, Flex, Image, Text } from '@chakra-ui/react'; + +import apiClient from '@api/apiClient'; +import type { Volunteer } from '../types'; +import { getAvatarColor, getInitials, useVolunteerId } from '@utils/volunteer'; +import logo from '../assets/mspca-logo.png'; + +/** Site-wide header: MSPCA logo and the current volunteer's profile button. */ +const Navbar: React.FC = () => { + const volunteerId = useVolunteerId(); + const [loaded, setLoaded] = useState(null); + const volunteer = loaded?.volunteerId === volunteerId ? loaded : null; + + useEffect(() => { + if (volunteerId === null) return; + + let cancelled = false; + apiClient + .getVolunteer(volunteerId) + .then((result) => { + if (!cancelled) setLoaded(result); + }) + .catch((err: unknown) => { + console.warn(`Could not load volunteer ${volunteerId}`, err); + }); + return () => { + cancelled = true; + }; + }, [volunteerId]); + + return ( + + MSPCA - Kindness and Care for Animals + {/* TODO: link to the volunteer profile page once it exists. */} + + + ); +}; + +export default Navbar; diff --git a/apps/frontend/src/components/RestrictionTag.tsx b/apps/frontend/src/components/RestrictionTag.tsx new file mode 100644 index 000000000..0474dcd47 --- /dev/null +++ b/apps/frontend/src/components/RestrictionTag.tsx @@ -0,0 +1,31 @@ +import { Flex, Text } from '@chakra-ui/react'; + +import { RESTRICTIONS } from '@utils/animals'; +import type { Restriction } from '../types'; + +interface RestrictionTagProps { + label: Restriction; +} + +/** + * A small colored pill showing one animal restriction, e.g. "Dog-Free Home". + * + * The background color comes from the restriction's theme token (see + * `RESTRICTIONS` in `utils/animals.ts`), so each restriction always renders in + * the same color on the animal card, the modal and anywhere else it appears. + */ +const RestrictionTag: React.FC = ({ label }) => ( + + + {label} + + +); + +export default RestrictionTag; diff --git a/apps/frontend/src/components/modals/AnimalModal.tsx b/apps/frontend/src/components/modals/AnimalModal.tsx new file mode 100644 index 000000000..2643d94d5 --- /dev/null +++ b/apps/frontend/src/components/modals/AnimalModal.tsx @@ -0,0 +1,269 @@ +import { useState } from 'react'; +import { + Button, + Dialog, + Flex, + Icon, + Image, + Portal, + Text, + Textarea, +} from '@chakra-ui/react'; +import { ExternalLink, House } from 'lucide-react'; + +import apiClient from '@api/apiClient'; +import type { Animal } from '../../types'; +import { HOMEBASE_ADDRESSES, formatAge } from '@utils/animals'; +import { useVolunteerId } from '@utils/volunteer'; +import { PLACEHOLDER_IMAGE } from '../AnimalCard'; +import RestrictionTag from '../RestrictionTag'; + +interface AnimalModalProps { + animal: Animal | null; + onClose: () => void; +} + +/** + * Detail modal for one animal, opened from the "See More" button on an + * `AnimalCard`. + * + * Shows the animal's photo, the address of its homebase, name, breed, age, + * restriction tags and foster bio. At the bottom the volunteer can type + * optional comments and press Apply to submit a match request for the animal + * (`apiClient.createMatch`); the modal closes once the request succeeds, and + * Back closes it too. Pass `animal={null}` to keep it closed. The form resets + * whenever a different animal is opened. + */ +const AnimalModal: React.FC = ({ animal, onClose }) => { + const [comments, setComments] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + // TODO: remove after login implemented. + const volunteerId = useVolunteerId(); + + const handleClose = () => { + setComments(''); + setError(null); + onClose(); + }; + + const handleApply = async (selectedAnimal: Animal) => { + if (volunteerId === null) return; + setSubmitting(true); + setError(null); + try { + await apiClient.createMatch({ + volunteerId, + chameleonAnimalId: selectedAnimal.chameleonAnimalId, + additionalComments: comments.trim() || undefined, + }); + handleClose(); + } catch { + setError('Could not submit your request. Please try again.'); + } finally { + setSubmitting(false); + } + }; + + return ( + { + if (!e.open) handleClose(); + }} + placement="center" + scrollBehavior="inside" + lazyMount + unmountOnExit + > + + + + {animal && ( + + + + {animal.name} + {/* Space reserved for the map, which is out of scope for now. */} + + + + {HOMEBASE_ADDRESSES[animal.location]} + + + + + + + + + + + + + + {animal.name} + + + {animal.breed.join(', ')} + + + + + + + {/* TODO: Figma shows "5 Month Foster" (foster length), which + the schema doesn't have. Showing the animal's age. */} + + {formatAge(animal.ageYear, animal.ageMonth)} + + + + {animal.restrictions && animal.restrictions.length > 0 && ( + + {animal.restrictions.map((label) => ( + + ))} + + )} + + + {animal.fosterBioMemo} + + + + + +