diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..94f480de9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ee529b859..6c68e0afc 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1 @@ -* @maxn990 +* @mehanana @saumyapalk23 diff --git a/.nx/cache/terminalOutputs/9746092569333069633 b/.nx/cache/terminalOutputs/9746092569333069633 deleted file mode 100644 index e69de29bb..000000000 diff --git a/apps/backend/src/announcements/README.md b/apps/backend/src/announcements/README.md new file mode 100644 index 000000000..e98be452e --- /dev/null +++ b/apps/backend/src/announcements/README.md @@ -0,0 +1,24 @@ +# Announcements + +Stewards publish announcements (upcoming events, workdays, what is ripe, etc.). `GET /api/announcement/{site_id}` surfaces those posts on the public per-site detail page so visitors can stay informed. + +## `GET /api/announcement/{site_id}` + +**Auth:** `@Public()` — visitors can call this without a Bearer token (site detail page). + +**Path:** `site_id` must be a UUID. A non-UUID value is `400`. + +**Response:** JSON array, newest published date first (then `id` for a stable tie-break). Empty `[]` when the site exists but has no announcements — not `404`. Unknown `site_id` → `404`. + +Each element: + +| Field | Notes | +| --------- | ------------------------------------------ | +| `id` | Announcement UUID | +| `content` | Body text (`info` column) | +| `date` | Date published (`YYYY-MM-DD`) | +| `author` | Posting steward `{ id, name }` (no email) | + +Pruning old announcements is out of scope for this endpoint (later priority). + +Swagger: tag **Announcements**. Enable with `SWAGGER_ENABLED=true` and open `/api`. diff --git a/apps/backend/src/announcements/announcements.controller.spec.ts b/apps/backend/src/announcements/announcements.controller.spec.ts new file mode 100644 index 000000000..df7e5c604 --- /dev/null +++ b/apps/backend/src/announcements/announcements.controller.spec.ts @@ -0,0 +1,68 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { NotFoundException } from '@nestjs/common'; + +import { IS_PUBLIC_KEY } from '../aws/cognito/cognito.decorator'; +import { AnnouncementsController } from './announcements.controller'; +import { AnnouncementsService } from './announcements.service'; +import { AnnouncementResponseDto } from './dto/announcement-response.dto'; + +describe('AnnouncementsController', () => { + let controller: AnnouncementsController; + let mockService: { findAllBySiteId: jest.Mock }; + + const siteId = '1a3cc442-d41f-421d-af8e-311781e6c033'; + const sample: AnnouncementResponseDto[] = [ + { + id: 'ann-1', + content: 'Paw paws are ripe — come pick this weekend.', + date: '2026-10-12', + author: { id: 'steward-id', name: 'Jamie Chen' }, + }, + ]; + + beforeEach(async () => { + mockService = { findAllBySiteId: jest.fn() }; + + const module: TestingModule = await Test.createTestingModule({ + controllers: [AnnouncementsController], + providers: [{ provide: AnnouncementsService, useValue: mockService }], + }).compile(); + + controller = module.get(AnnouncementsController); + }); + + it('marks GET /announcement/:site_id as @Public()', () => { + const isPublic = Reflect.getMetadata( + IS_PUBLIC_KEY, + AnnouncementsController.prototype.getAnnouncementsBySite, + ); + expect(isPublic).toBe(true); + }); + + it('forwards site_id and returns the service result', async () => { + mockService.findAllBySiteId.mockResolvedValue(sample); + + await expect(controller.getAnnouncementsBySite(siteId)).resolves.toEqual( + sample, + ); + expect(mockService.findAllBySiteId).toHaveBeenCalledWith(siteId); + }); + + it('returns an empty array when the site has no announcements', async () => { + mockService.findAllBySiteId.mockResolvedValue([]); + + await expect(controller.getAnnouncementsBySite(siteId)).resolves.toEqual( + [], + ); + }); + + it('propagates NotFoundException when the site does not exist', async () => { + mockService.findAllBySiteId.mockRejectedValue( + new NotFoundException('Site not found'), + ); + + await expect( + controller.getAnnouncementsBySite('00000000-0000-0000-0000-000000000000'), + ).rejects.toThrow(NotFoundException); + }); +}); diff --git a/apps/backend/src/announcements/announcements.controller.ts b/apps/backend/src/announcements/announcements.controller.ts new file mode 100644 index 000000000..98131ccad --- /dev/null +++ b/apps/backend/src/announcements/announcements.controller.ts @@ -0,0 +1,43 @@ +import { Controller, Get, Param, ParseUUIDPipe } from '@nestjs/common'; +import { + ApiNotFoundResponse, + ApiOkResponse, + ApiOperation, + ApiParam, + ApiTags, +} from '@nestjs/swagger'; + +import { Public } from '../aws/cognito/cognito.decorator'; +import { AnnouncementsService } from './announcements.service'; +import { AnnouncementResponseDto } from './dto/announcement-response.dto'; + +@ApiTags('Announcements') +@Controller('announcement') +export class AnnouncementsController { + constructor(private readonly announcementsService: AnnouncementsService) {} + + /** + * Public site-page list of steward announcements for one site. + */ + @Get(':site_id') + @Public() + @ApiOperation({ + summary: 'List announcements for a site', + description: + 'Returns steward-published announcements for the given site, newest first. ' + + 'An empty array means the site exists but has no announcements. Unknown `site_id` is 404.', + }) + @ApiParam({ + name: 'site_id', + description: 'Site UUID', + type: 'string', + format: 'uuid', + }) + @ApiOkResponse({ type: [AnnouncementResponseDto] }) + @ApiNotFoundResponse({ description: 'Site not found' }) + getAnnouncementsBySite( + @Param('site_id', ParseUUIDPipe) siteId: string, + ): Promise { + return this.announcementsService.findAllBySiteId(siteId); + } +} diff --git a/apps/backend/src/announcements/announcements.module.ts b/apps/backend/src/announcements/announcements.module.ts new file mode 100644 index 000000000..f66b5e683 --- /dev/null +++ b/apps/backend/src/announcements/announcements.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; + +import { Announcement } from '../entities/announcement.entity'; +import { Site } from '../entities/site.entity'; +import { AnnouncementsController } from './announcements.controller'; +import { AnnouncementsService } from './announcements.service'; + +@Module({ + imports: [TypeOrmModule.forFeature([Announcement, Site])], + controllers: [AnnouncementsController], + providers: [AnnouncementsService], +}) +export class AnnouncementsModule {} diff --git a/apps/backend/src/announcements/announcements.service.spec.ts b/apps/backend/src/announcements/announcements.service.spec.ts new file mode 100644 index 000000000..07d1cca5f --- /dev/null +++ b/apps/backend/src/announcements/announcements.service.spec.ts @@ -0,0 +1,130 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { NotFoundException } from '@nestjs/common'; + +import { Announcement } from '../entities/announcement.entity'; +import { Site } from '../entities/site.entity'; +import { User, UserType } from '../entities/user.entity'; +import { AnnouncementsService } from './announcements.service'; + +const SITE_ID = '1a3cc442-d41f-421d-af8e-311781e6c033'; + +const steward = { + id: 'steward-uuid', + name: 'Jamie Chen', + email: 'jamie@example.com', + type: UserType.STEWARD, +} as User; + +function announcement( + overrides: Partial & { id: string; date: string }, +): Announcement { + return { + info: 'Announcement body', + steward, + site: { id: SITE_ID } as Site, + ...overrides, + } as Announcement; +} + +describe('AnnouncementsService', () => { + let service: AnnouncementsService; + let announcementRepo: { find: jest.Mock }; + let siteRepo: { exists: jest.Mock }; + + beforeEach(async () => { + announcementRepo = { find: jest.fn().mockResolvedValue([]) }; + siteRepo = { exists: jest.fn().mockResolvedValue(true) }; + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + AnnouncementsService, + { + provide: getRepositoryToken(Announcement), + useValue: announcementRepo, + }, + { provide: getRepositoryToken(Site), useValue: siteRepo }, + ], + }).compile(); + + service = module.get(AnnouncementsService); + }); + + describe('findAllBySiteId', () => { + it('throws NotFoundException when the site does not exist', async () => { + siteRepo.exists.mockResolvedValue(false); + + await expect(service.findAllBySiteId(SITE_ID)).rejects.toThrow( + NotFoundException, + ); + expect(announcementRepo.find).not.toHaveBeenCalled(); + }); + + it('returns an empty array when the site has no announcements', async () => { + announcementRepo.find.mockResolvedValue([]); + + await expect(service.findAllBySiteId(SITE_ID)).resolves.toEqual([]); + expect(siteRepo.exists).toHaveBeenCalledWith({ where: { id: SITE_ID } }); + }); + + it('maps content, date, and author without exposing steward email', async () => { + announcementRepo.find.mockResolvedValue([ + announcement({ + id: 'ann-ripe', + date: '2026-10-12', + info: 'Paw paws are ripe — come pick this weekend.', + }), + ]); + + const [result] = await service.findAllBySiteId(SITE_ID); + + expect(result).toEqual({ + id: 'ann-ripe', + content: 'Paw paws are ripe — come pick this weekend.', + date: '2026-10-12', + author: { id: steward.id, name: steward.name }, + }); + expect(result.author).not.toHaveProperty('email'); + }); + + it('queries announcements for the site newest-first', async () => { + await service.findAllBySiteId(SITE_ID); + + expect(announcementRepo.find).toHaveBeenCalledWith({ + where: { site: { id: SITE_ID } }, + relations: { steward: true }, + order: { date: 'DESC', id: 'DESC' }, + }); + }); + + it('returns announcements in most-recent-first order', async () => { + announcementRepo.find.mockResolvedValue([ + announcement({ + id: 'newer', + date: '2026-10-12', + info: 'Paw paws are ripe — come pick this weekend.', + }), + announcement({ + id: 'older', + date: '2026-09-20', + info: 'Path repairs scheduled for next week — expect partial closures.', + }), + ]); + + const results = await service.findAllBySiteId(SITE_ID); + expect(results.map((row) => row.id)).toEqual(['newer', 'older']); + }); + + it('normalizes TypeORM Date objects into YYYY-MM-DD', async () => { + announcementRepo.find.mockResolvedValue([ + announcement({ + id: 'date-obj', + date: new Date(2026, 9, 12) as unknown as string, + }), + ]); + + const [result] = await service.findAllBySiteId(SITE_ID); + expect(result.date).toBe('2026-10-12'); + }); + }); +}); diff --git a/apps/backend/src/announcements/announcements.service.ts b/apps/backend/src/announcements/announcements.service.ts new file mode 100644 index 000000000..e4058bef6 --- /dev/null +++ b/apps/backend/src/announcements/announcements.service.ts @@ -0,0 +1,61 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; + +import { Announcement } from '../entities/announcement.entity'; +import { Site } from '../entities/site.entity'; +import { AnnouncementResponseDto } from './dto/announcement-response.dto'; + +@Injectable() +export class AnnouncementsService { + constructor( + @InjectRepository(Announcement) + private readonly announcementRepo: Repository, + @InjectRepository(Site) + private readonly siteRepo: Repository, + ) {} + + /** + * All announcements for `siteId`, newest published date first. + * Unknown site → 404. Known site with none → `[]`. + */ + async findAllBySiteId(siteId: string): Promise { + const siteExists = await this.siteRepo.exists({ where: { id: siteId } }); + if (!siteExists) { + throw new NotFoundException(`Site with ID ${siteId} not found`); + } + + const announcements = await this.announcementRepo.find({ + where: { site: { id: siteId } }, + relations: { steward: true }, + order: { date: 'DESC', id: 'DESC' }, + }); + + return announcements.map((announcement) => this.mapToDto(announcement)); + } + + private mapToDto(announcement: Announcement): AnnouncementResponseDto { + return { + id: announcement.id, + content: announcement.info, + date: normalizeDate(announcement.date), + author: { + id: announcement.steward.id, + name: announcement.steward.name, + }, + }; + } +} + +function pad2(n: number): string { + return String(n).padStart(2, '0'); +} + +function normalizeDate(value: string | Date): string { + if (value instanceof Date) { + return `${value.getFullYear()}-${pad2(value.getMonth() + 1)}-${pad2( + value.getDate(), + )}`; + } + return String(value).slice(0, 10); +} diff --git a/apps/backend/src/announcements/dto/announcement-response.dto.ts b/apps/backend/src/announcements/dto/announcement-response.dto.ts new file mode 100644 index 000000000..ed5422918 --- /dev/null +++ b/apps/backend/src/announcements/dto/announcement-response.dto.ts @@ -0,0 +1,34 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class AnnouncementAuthorDto { + @ApiProperty({ format: 'uuid' }) + id: string; + + @ApiProperty({ description: 'Steward who published the announcement' }) + name: string; +} + +/** + * One steward announcement on a public site detail page. + * `content` is the stored `info` column; `author` is the posting steward + * (id + name only — email is never returned). + */ +export class AnnouncementResponseDto { + @ApiProperty({ format: 'uuid' }) + id: string; + + @ApiProperty({ + description: + 'Announcement body (upcoming events, workdays, what is ripe, etc.)', + }) + content: string; + + @ApiProperty({ + description: 'Date published (YYYY-MM-DD)', + example: '2026-10-12', + }) + date: string; + + @ApiProperty({ type: AnnouncementAuthorDto }) + author: AnnouncementAuthorDto; +} diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index df2d31bb0..90b565853 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -6,15 +6,29 @@ import { AppService } from './app.service'; import AppDataSource from './data-source'; import { CognitoModule } from './aws/cognito/cognito.module'; import { UsersModule } from './users/users.module'; +import { SitesModule } from './sites/sites.module'; +import { EventsModule } from './events/events.module'; +import { MediaModule } from './media/media.module'; +import { AnnouncementsModule } from './announcements/announcements.module'; +import { RecurringEventModule } from './recurring-event/recurring-event.module'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, }), - TypeOrmModule.forRoot(AppDataSource.options), + TypeOrmModule.forRoot({ + ...AppDataSource.options, + migrations: [], + migrationsRun: false, + }), CognitoModule, UsersModule, + SitesModule, + EventsModule, + AnnouncementsModule, + MediaModule, + RecurringEventModule, ], controllers: [AppController], providers: [AppService], diff --git a/apps/backend/src/aws/cognito/README.md b/apps/backend/src/aws/cognito/README.md index 52b6c8591..46b6398a4 100644 --- a/apps/backend/src/aws/cognito/README.md +++ b/apps/backend/src/aws/cognito/README.md @@ -159,3 +159,9 @@ in that allowlist instead of simply an equality check. - The most amazing explanation of authn (OAUTH 2.0) and authz (OIDC) you'll ever watch: https://www.youtube.com/watch?v=996OiexHze0&t=2126s - Difference between id and access tokens: https://auth0.com/blog/id-token-access-token-what-is-the-difference/ - Using AWS to verify JWT: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html + +## Managing users +`CognitoService` also wraps the Cognito admin APIs: `createUser`, `addUserToGroup`, `removeUserFromGroup`, `disableUser` and `enableUser`. +- Accounts are created with a verified email and Cognito's invite email suppressed. Site assignment stays in Postgres, not Cognito. +- The `admin` and `steward` roles map to the `admins` and `stewards` groups in the user pool. The mapping lives in `COGNITO_GROUPS` in `cognito.types.ts`. +- A duplicate email gives a 409, an unknown email a 404, and any other AWS failure a 500. diff --git a/apps/backend/src/aws/cognito/cognito.service.spec.ts b/apps/backend/src/aws/cognito/cognito.service.spec.ts index 276bf649c..2144a2eb5 100644 --- a/apps/backend/src/aws/cognito/cognito.service.spec.ts +++ b/apps/backend/src/aws/cognito/cognito.service.spec.ts @@ -1,4 +1,20 @@ import { Request } from 'express'; +import { + AdminAddUserToGroupCommand, + AdminCreateUserCommand, + AdminDeleteUserCommand, + AdminDisableUserCommand, + AdminEnableUserCommand, + AdminRemoveUserFromGroupCommand, + CognitoIdentityProviderClient, +} from '@aws-sdk/client-cognito-identity-provider'; +import { + ConflictException, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import { mockClient } from 'aws-sdk-client-mock'; +import { UserType } from '../../entities/user.entity'; import { AuthConfigurationError } from './cognito.config'; import { CognitoService } from './cognito.service'; @@ -122,3 +138,226 @@ describe('CognitoService', () => { }); }); }); + +describe('CognitoService admin functions', () => { + const cognitoMock = mockClient(CognitoIdentityProviderClient); + const POOL_ID = 'us-east-2_TestPool'; + let service: CognitoService; + + const awsError = (name: string) => Object.assign(new Error(name), { name }); + + beforeEach(() => { + cognitoMock.reset(); + delete process.env.AUTH_DISABLED; + process.env.COGNITO_USER_POOL_ID = POOL_ID; + process.env.COGNITO_CLIENT_ID = '4h57k9lmno1pqrstuv2wxyz3ab'; + process.env.COGNITO_REGION = 'us-east-2'; + service = new CognitoService(); + }); + + afterEach(() => { + restoreEnv(); + }); + + describe('createUser', () => { + it('creates a verified user with the invite email suppressed and adds them to the group', async () => { + cognitoMock.on(AdminCreateUserCommand).resolves({ + User: { + Enabled: true, + Attributes: [{ Name: 'sub', Value: 'abc-123' }], + }, + }); + cognitoMock.on(AdminAddUserToGroupCommand).resolves({}); + + const result = await service.createUser({ + email: ' Steward@Example.com ', + role: UserType.STEWARD, + }); + + expect(result).toEqual({ + username: 'steward@example.com', + sub: 'abc-123', + email: 'steward@example.com', + role: UserType.STEWARD, + enabled: true, + }); + expect( + cognitoMock.commandCalls(AdminCreateUserCommand)[0].args[0].input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'steward@example.com', + UserAttributes: [ + { Name: 'email', Value: 'steward@example.com' }, + { Name: 'email_verified', Value: 'true' }, + ], + MessageAction: 'SUPPRESS', + }); + expect( + cognitoMock.commandCalls(AdminAddUserToGroupCommand)[0].args[0].input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'steward@example.com', + GroupName: 'stewards', + }); + }); + + it('adds admins to the admins group', async () => { + cognitoMock.on(AdminCreateUserCommand).resolves({ User: {} }); + cognitoMock.on(AdminAddUserToGroupCommand).resolves({}); + + await service.createUser({ + email: 'a@example.com', + role: UserType.ADMIN, + }); + + expect( + cognitoMock.commandCalls(AdminAddUserToGroupCommand)[0].args[0].input + .GroupName, + ).toBe('admins'); + }); + + it('throws ConflictException when the email already exists', async () => { + cognitoMock + .on(AdminCreateUserCommand) + .rejects(awsError('UsernameExistsException')); + + await expect( + service.createUser({ email: 'a@example.com', role: UserType.STEWARD }), + ).rejects.toBeInstanceOf(ConflictException); + expect(cognitoMock.commandCalls(AdminAddUserToGroupCommand)).toHaveLength( + 0, + ); + }); + + it('throws InternalServerErrorException on an unexpected AWS error', async () => { + cognitoMock + .on(AdminCreateUserCommand) + .rejects(awsError('ServiceFailure')); + + await expect( + service.createUser({ email: 'a@example.com', role: UserType.STEWARD }), + ).rejects.toBeInstanceOf(InternalServerErrorException); + }); + + it('deletes the new user and throws when the group assignment fails', async () => { + cognitoMock.on(AdminCreateUserCommand).resolves({ User: {} }); + cognitoMock + .on(AdminAddUserToGroupCommand) + .rejects(awsError('ResourceNotFoundException')); + cognitoMock.on(AdminDeleteUserCommand).resolves({}); + + await expect( + service.createUser({ email: 'a@example.com', role: UserType.STEWARD }), + ).rejects.toBeInstanceOf(InternalServerErrorException); + expect(cognitoMock.commandCalls(AdminDeleteUserCommand)).toHaveLength(1); + }); + + it('throws InternalServerErrorException when Cognito is not configured', async () => { + process.env.AUTH_DISABLED = 'true'; + + await expect( + service.createUser({ email: 'a@example.com', role: UserType.STEWARD }), + ).rejects.toBeInstanceOf(InternalServerErrorException); + expect(cognitoMock.calls()).toHaveLength(0); + }); + }); + + describe('addUserToGroup / removeUserFromGroup', () => { + it('adds a user to the group for their role', async () => { + cognitoMock.on(AdminAddUserToGroupCommand).resolves({}); + + await service.addUserToGroup('A@Example.com', UserType.ADMIN); + + expect( + cognitoMock.commandCalls(AdminAddUserToGroupCommand)[0].args[0].input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'a@example.com', + GroupName: 'admins', + }); + }); + + it('removes a user from the group for their role', async () => { + cognitoMock.on(AdminRemoveUserFromGroupCommand).resolves({}); + + await service.removeUserFromGroup('a@example.com', UserType.STEWARD); + + expect( + cognitoMock.commandCalls(AdminRemoveUserFromGroupCommand)[0].args[0] + .input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'a@example.com', + GroupName: 'stewards', + }); + }); + + it('throws NotFoundException when the user does not exist (add)', async () => { + cognitoMock + .on(AdminAddUserToGroupCommand) + .rejects(awsError('UserNotFoundException')); + + await expect( + service.addUserToGroup('a@example.com', UserType.ADMIN), + ).rejects.toBeInstanceOf(NotFoundException); + }); + + it('throws InternalServerErrorException on an unexpected AWS error (remove)', async () => { + cognitoMock + .on(AdminRemoveUserFromGroupCommand) + .rejects(awsError('ServiceFailure')); + + await expect( + service.removeUserFromGroup('a@example.com', UserType.ADMIN), + ).rejects.toBeInstanceOf(InternalServerErrorException); + }); + }); + + describe('disableUser / enableUser', () => { + it('disables a user', async () => { + cognitoMock.on(AdminDisableUserCommand).resolves({}); + + await service.disableUser('A@Example.com'); + + expect( + cognitoMock.commandCalls(AdminDisableUserCommand)[0].args[0].input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'a@example.com', + }); + }); + + it('enables a user', async () => { + cognitoMock.on(AdminEnableUserCommand).resolves({}); + + await service.enableUser('a@example.com'); + + expect( + cognitoMock.commandCalls(AdminEnableUserCommand)[0].args[0].input, + ).toEqual({ + UserPoolId: POOL_ID, + Username: 'a@example.com', + }); + }); + + it('throws NotFoundException when disabling an unknown user', async () => { + cognitoMock + .on(AdminDisableUserCommand) + .rejects(awsError('UserNotFoundException')); + + await expect(service.disableUser('a@example.com')).rejects.toBeInstanceOf( + NotFoundException, + ); + }); + + it('throws InternalServerErrorException on an unexpected AWS error (enable)', async () => { + cognitoMock + .on(AdminEnableUserCommand) + .rejects(awsError('ServiceFailure')); + + await expect(service.enableUser('a@example.com')).rejects.toBeInstanceOf( + InternalServerErrorException, + ); + }); + }); +}); diff --git a/apps/backend/src/aws/cognito/cognito.service.ts b/apps/backend/src/aws/cognito/cognito.service.ts index 0f0db0206..81b1ad999 100644 --- a/apps/backend/src/aws/cognito/cognito.service.ts +++ b/apps/backend/src/aws/cognito/cognito.service.ts @@ -1,7 +1,29 @@ -import { Injectable, Logger } from '@nestjs/common'; +import { + ConflictException, + HttpException, + Injectable, + InternalServerErrorException, + Logger, + NotFoundException, +} from '@nestjs/common'; +import { + AdminAddUserToGroupCommand, + AdminCreateUserCommand, + AdminDeleteUserCommand, + AdminDisableUserCommand, + AdminEnableUserCommand, + AdminRemoveUserFromGroupCommand, + CognitoIdentityProviderClient, +} from '@aws-sdk/client-cognito-identity-provider'; import { Request } from 'express'; -import { AccessTokenPayload } from './cognito.types'; -import { isAuthDisabled } from './cognito.config'; +import { + AccessTokenPayload, + COGNITO_GROUPS, + CognitoRole, + CognitoUserResult, +} from './cognito.types'; +import { getCognitoConfig, isAuthDisabled } from './cognito.config'; +import { CreateCognitoUserDto } from './dto/create-cognito-user.dto'; @Injectable() export class CognitoService { @@ -44,4 +66,175 @@ export class CognitoService { } return authenticatedRequest.user; } + + // Built on first use so startup and getUser do not depend on AWS settings. + private client?: CognitoIdentityProviderClient; + private userPoolId?: string; + + private getClient(): { + client: CognitoIdentityProviderClient; + userPoolId: string; + } { + if (!this.client || !this.userPoolId) { + const config = getCognitoConfig(); + if (!config) { + throw new InternalServerErrorException( + 'Cognito is not configured: AUTH_DISABLED=true, so user management is unavailable.', + ); + } + this.client = new CognitoIdentityProviderClient({ + region: config.region, + }); + this.userPoolId = config.userPoolId; + } + return { client: this.client, userPoolId: this.userPoolId }; + } + + // Cognito usernames are the email, lowercased so one address maps to one account. + private normalizeEmail(email: string): string { + return email.trim().toLowerCase(); + } + + /** + * Maps an AWS error to the HTTP exception we want callers to see. + * Nest exceptions pass through unchanged. + */ + private handleError(error: unknown, action: string): never { + if (error instanceof HttpException) { + throw error; + } + const name = (error as { name?: string })?.name; + if (name === 'UsernameExistsException') { + throw new ConflictException('A user with this email already exists'); + } + if (name === 'UserNotFoundException') { + throw new NotFoundException('No user with this email exists'); + } + this.logger.error( + `Failed to ${action}: ${(error as Error)?.message ?? String(error)}`, + (error as Error)?.stack, + ); + throw new InternalServerErrorException( + `Failed to ${action} Cognito user: ${ + (error as Error)?.message ?? 'unknown error' + }`, + ); + } + + /** + * Creates a Cognito account with a verified email and adds it to the role's group. + * Cognito's invite email (with a temporary password) is suppressed. + * + * @throws {ConflictException} If an account with this email already exists. + * @throws {InternalServerErrorException} On any other AWS failure. + */ + async createUser(dto: CreateCognitoUserDto): Promise { + const { client, userPoolId } = this.getClient(); + const username = this.normalizeEmail(dto.email); + + let sub: string | undefined; + let enabled = true; + try { + const result = await client.send( + new AdminCreateUserCommand({ + UserPoolId: userPoolId, + Username: username, + UserAttributes: [ + { Name: 'email', Value: username }, + { Name: 'email_verified', Value: 'true' }, + ], + MessageAction: 'SUPPRESS', + }), + ); + sub = result.User?.Attributes?.find((a) => a.Name === 'sub')?.Value; + enabled = result.User?.Enabled ?? true; + } catch (error) { + this.handleError(error, 'create'); + } + + try { + await this.addUserToGroup(username, dto.role); + } catch (error) { + // Do not leave an account behind with no role. + try { + await client.send( + new AdminDeleteUserCommand({ + UserPoolId: userPoolId, + Username: username, + }), + ); + } catch (cleanupError) { + this.logger.error( + `Could not remove ${username} after a failed group assignment: ${ + (cleanupError as Error)?.message + }`, + ); + } + throw error; + } + + return { username, sub, email: username, role: dto.role, enabled }; + } + + /** Adds the user to the group for `role`. */ + async addUserToGroup(email: string, role: CognitoRole): Promise { + const { client, userPoolId } = this.getClient(); + try { + await client.send( + new AdminAddUserToGroupCommand({ + UserPoolId: userPoolId, + Username: this.normalizeEmail(email), + GroupName: COGNITO_GROUPS[role], + }), + ); + } catch (error) { + this.handleError(error, 'add group to'); + } + } + + /** Removes the user from the group for `role`. */ + async removeUserFromGroup(email: string, role: CognitoRole): Promise { + const { client, userPoolId } = this.getClient(); + try { + await client.send( + new AdminRemoveUserFromGroupCommand({ + UserPoolId: userPoolId, + Username: this.normalizeEmail(email), + GroupName: COGNITO_GROUPS[role], + }), + ); + } catch (error) { + this.handleError(error, 'remove group from'); + } + } + + /** Blocks the user from signing in without deleting the account. */ + async disableUser(email: string): Promise { + const { client, userPoolId } = this.getClient(); + try { + await client.send( + new AdminDisableUserCommand({ + UserPoolId: userPoolId, + Username: this.normalizeEmail(email), + }), + ); + } catch (error) { + this.handleError(error, 'disable'); + } + } + + /** Restores a disabled user's access. */ + async enableUser(email: string): Promise { + const { client, userPoolId } = this.getClient(); + try { + await client.send( + new AdminEnableUserCommand({ + UserPoolId: userPoolId, + Username: this.normalizeEmail(email), + }), + ); + } catch (error) { + this.handleError(error, 'enable'); + } + } } diff --git a/apps/backend/src/aws/cognito/cognito.types.ts b/apps/backend/src/aws/cognito/cognito.types.ts index 391edb624..b1264f733 100644 --- a/apps/backend/src/aws/cognito/cognito.types.ts +++ b/apps/backend/src/aws/cognito/cognito.types.ts @@ -1,3 +1,5 @@ +import { UserType } from '../../entities/user.entity'; + // Resolved Cognito configuration derived from environment variables. export interface CognitoConfig { region: string; // AWS region (ex: us-east-1) @@ -17,3 +19,21 @@ export interface AccessTokenPayload { exp: number; // Expiration time (Unix timestamp) iat: number; // Issued at time (Unix timestamp) } + +// Role assigned to a Cognito account. Same values as the `users.type` column. +export type CognitoRole = UserType; + +// Cognito group name for each role. The groups live in the user pool already. +export const COGNITO_GROUPS: Record = { + [UserType.ADMIN]: 'admins', + [UserType.STEWARD]: 'stewards', +}; + +// What createUser returns for the account it created. +export interface CognitoUserResult { + username: string; // Cognito username (the lowercased email) + sub?: string; // Cognito subject (unique id), when Cognito returns one + email: string; + role: CognitoRole; + enabled: boolean; +} diff --git a/apps/backend/src/aws/cognito/dto/create-cognito-user.dto.ts b/apps/backend/src/aws/cognito/dto/create-cognito-user.dto.ts new file mode 100644 index 000000000..c4c2163fb --- /dev/null +++ b/apps/backend/src/aws/cognito/dto/create-cognito-user.dto.ts @@ -0,0 +1,21 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsEmail, IsEnum } from 'class-validator'; +import { UserType } from '../../../entities/user.entity'; + +export class CreateCognitoUserDto { + @ApiProperty({ + description: 'Email address for the new account. Used as the sign-in name.', + format: 'email', + example: 'steward@example.com', + }) + @IsEmail() + email: string; + + @ApiProperty({ + description: 'Role for the new account', + enum: UserType, + example: UserType.STEWARD, + }) + @IsEnum(UserType) + role: UserType; +} diff --git a/apps/backend/src/data-source.ts b/apps/backend/src/data-source.ts index e9c754811..23c6e83e7 100644 --- a/apps/backend/src/data-source.ts +++ b/apps/backend/src/data-source.ts @@ -2,6 +2,19 @@ import { DataSource } from 'typeorm'; import { PluralNamingStrategy } from './strategies/plural-naming.strategy'; import * as dotenv from 'dotenv'; +import { User } from './entities/user.entity'; +import { Site } from './entities/site.entity'; +import { AdminEvent } from './entities/admin-event.entity'; +import { StewardEvent } from './entities/steward-event.entity'; +import { RecurringEvent } from './entities/recurring-event.entity'; +import { PlantInventory } from './entities/plant-inventory.entity'; +import { Image } from './entities/image.entity'; +import { Video } from './entities/video.entity'; +import { Testimonial } from './entities/testimonial.entity'; +import { Announcement } from './entities/announcement.entity'; +import { PartnerOrg } from './entities/partner-org.entity'; +import { Address } from './entities/address.entity'; + dotenv.config(); const AppDataSource = new DataSource({ @@ -11,8 +24,21 @@ const AppDataSource = new DataSource({ username: process.env.NX_DB_USERNAME, password: process.env.NX_DB_PASSWORD, database: process.env.NX_DB_DATABASE, - entities: [], - migrations: ['apps/backend/src/migrations/*.js'], + entities: [ + User, + Site, + AdminEvent, + StewardEvent, + RecurringEvent, + PlantInventory, + Image, + Video, + Testimonial, + Announcement, + PartnerOrg, + Address, + ], + migrations: ['apps/backend/src/migrations/*.ts'], // Setting synchronize: true shouldn't be used in production - otherwise you can lose production data synchronize: false, namingStrategy: new PluralNamingStrategy(), diff --git a/apps/backend/src/entities/address.entity.ts b/apps/backend/src/entities/address.entity.ts new file mode 100644 index 000000000..9c4fb26a0 --- /dev/null +++ b/apps/backend/src/entities/address.entity.ts @@ -0,0 +1,41 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + OneToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; +import { Point } from 'geojson'; + +@Entity('addresses') +export class Address { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @OneToOne(() => Site, (site) => site.address) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + street!: string; + + @Column() + city!: string; + + @Column() + state!: string; + + @Column() + zip!: string; + + @Column({ + type: 'geometry', + spatialFeatureType: 'Point', + srid: 4326, + }) + location!: Point; + + @Column({ type: 'jsonb', nullable: true }) + geojson!: Record; +} diff --git a/apps/backend/src/entities/admin-event.entity.ts b/apps/backend/src/entities/admin-event.entity.ts new file mode 100644 index 000000000..5edccb311 --- /dev/null +++ b/apps/backend/src/entities/admin-event.entity.ts @@ -0,0 +1,42 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; + +@Entity('admin_events') +export class AdminEvent { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.adminEvents) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + name!: string; + + @Column() + description!: string; + + @Column({ type: 'date' }) + date!: string; + + @Column({ type: 'time' }) + startTime!: string; + + @Column({ type: 'time', nullable: true }) + endTime?: string; + + @Column() + place!: string; + + @Column({ nullable: true }) + flyerS3Key?: string; + + @Column() + registrationLink!: string; +} diff --git a/apps/backend/src/entities/announcement.entity.ts b/apps/backend/src/entities/announcement.entity.ts new file mode 100644 index 000000000..b348eb1f5 --- /dev/null +++ b/apps/backend/src/entities/announcement.entity.ts @@ -0,0 +1,29 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; +import { User } from './user.entity'; + +@Entity('announcements') +export class Announcement { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Column({ type: 'date' }) + date!: string; + + @ManyToOne(() => User, (user) => user.announcements) + @JoinColumn({ name: 'steward_id' }) + steward!: User; + + @ManyToOne(() => Site, (site) => site.announcements) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column({ type: 'text' }) + info!: string; +} diff --git a/apps/backend/src/entities/image.entity.ts b/apps/backend/src/entities/image.entity.ts new file mode 100644 index 000000000..2549ec875 --- /dev/null +++ b/apps/backend/src/entities/image.entity.ts @@ -0,0 +1,35 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; +import { User } from './user.entity'; + +@Entity('images') +export class Image { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.images) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + s3Key!: string; + + @Column({ type: 'varchar', nullable: true }) + title!: string | null; + + @Column({ type: 'text', nullable: true }) + description!: string | null; + + @Column({ type: 'timestamptz', default: () => 'now()' }) + uploadedAt!: Date; + + @ManyToOne(() => User, { onDelete: 'SET NULL', nullable: true }) + @JoinColumn({ name: 'uploaded_by' }) + uploadedBy!: User | null; +} diff --git a/apps/backend/src/entities/partner-org.entity.ts b/apps/backend/src/entities/partner-org.entity.ts new file mode 100644 index 000000000..164595829 --- /dev/null +++ b/apps/backend/src/entities/partner-org.entity.ts @@ -0,0 +1,23 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; + +// NOTE: modeled as one-to-many (site -> many orgs). If an org can also +// belong to multiple sites, this needs to become a ManyToMany with a join table. +@Entity('partner_orgs') +export class PartnerOrg { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.partnerOrgs) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + name!: string; +} diff --git a/apps/backend/src/entities/plant-inventory.entity.ts b/apps/backend/src/entities/plant-inventory.entity.ts new file mode 100644 index 000000000..65df82204 --- /dev/null +++ b/apps/backend/src/entities/plant-inventory.entity.ts @@ -0,0 +1,24 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; + +@Entity('plant_inventory') +export class PlantInventory { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.plantInventory) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + plantName!: string; + + @Column({ nullable: true }) + imageS3Key?: string; +} diff --git a/apps/backend/src/entities/recurring-event.entity.ts b/apps/backend/src/entities/recurring-event.entity.ts new file mode 100644 index 000000000..a7403ed0f --- /dev/null +++ b/apps/backend/src/entities/recurring-event.entity.ts @@ -0,0 +1,52 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; + +export enum RecurrenceFrequency { + DAILY = 'daily', + WEEKLY = 'weekly', + BIWEEKLY = 'biweekly', + MONTHLY = 'monthly', +} + +@Entity('recurring_events') +export class RecurringEvent { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.recurringEvents) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + name!: string; + + @Column() + description!: string; + + @Column({ type: 'date' }) + startDate!: string; + + @Column({ type: 'time' }) + startTime!: string; + + @Column({ type: 'time', nullable: true }) + endTime?: string; + + @Column() + place!: string; + + @Column({ nullable: true }) + flyerS3Key?: string; + + @Column({ type: 'enum', enum: RecurrenceFrequency }) + frequency!: RecurrenceFrequency; + + @Column({ type: 'date', nullable: true }) + endDate?: string; +} diff --git a/apps/backend/src/entities/site.entity.ts b/apps/backend/src/entities/site.entity.ts new file mode 100644 index 000000000..8aa04c8ef --- /dev/null +++ b/apps/backend/src/entities/site.entity.ts @@ -0,0 +1,85 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, + OneToMany, + OneToOne, +} from 'typeorm'; +import { User } from './user.entity'; +import { AdminEvent } from './admin-event.entity'; +import { StewardEvent } from './steward-event.entity'; +import { RecurringEvent } from './recurring-event.entity'; +import { PlantInventory } from './plant-inventory.entity'; +import { Image } from './image.entity'; +import { Video } from './video.entity'; +import { Testimonial } from './testimonial.entity'; +import { Announcement } from './announcement.entity'; +import { PartnerOrg } from './partner-org.entity'; +import { Address } from './address.entity'; + +export enum SiteType { + EXISTING_LAND_TRUST = 'existing_land_trust', + EXISTING_COALITION = 'existing_coalition', + EMERGING_LAND_TRUST = 'emerging_land_trust', + EMERGING_COALITION = 'emerging_coalition', +} + +@Entity('sites') +export class Site { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Column() + name!: string; + + @ManyToOne(() => User, (user) => user.sites) + @JoinColumn({ name: 'user_id' }) + steward!: User; + + @Column() + history!: string; + + @OneToOne(() => Address, (address) => address.site) + address!: Address; + + @Column() + accessibility!: string; + + @Column({ nullable: true }) + foundingDate?: string; + + @Column({ nullable: true }) + hoursOpen?: string; + + @Column({ type: 'enum', enum: SiteType }) + type!: SiteType; + + @OneToMany(() => AdminEvent, (event) => event.site) + adminEvents!: AdminEvent[]; + + @OneToMany(() => StewardEvent, (event) => event.site) + stewardEvents!: StewardEvent[]; + + @OneToMany(() => RecurringEvent, (event) => event.site) + recurringEvents!: RecurringEvent[]; + + @OneToMany(() => PlantInventory, (plant) => plant.site) + plantInventory!: PlantInventory[]; + + @OneToMany(() => Image, (image) => image.site) + images!: Image[]; + + @OneToMany(() => Video, (video) => video.site) + videos!: Video[]; + + @OneToMany(() => Testimonial, (testimonial) => testimonial.site) + testimonials!: Testimonial[]; + + @OneToMany(() => Announcement, (announcement) => announcement.site) + announcements!: Announcement[]; + + @OneToMany(() => PartnerOrg, (org) => org.site) + partnerOrgs!: PartnerOrg[]; +} diff --git a/apps/backend/src/entities/steward-event.entity.ts b/apps/backend/src/entities/steward-event.entity.ts new file mode 100644 index 000000000..4b1cc7ca6 --- /dev/null +++ b/apps/backend/src/entities/steward-event.entity.ts @@ -0,0 +1,41 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; +import { User } from './user.entity'; + +@Entity('steward_events') +export class StewardEvent { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.stewardEvents) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @ManyToOne(() => User, (user) => user.stewardEvents) + @JoinColumn({ name: 'steward_id' }) + steward!: User; + + @Column() + description!: string; + + @Column({ type: 'date' }) + date!: string; + + @Column({ type: 'time' }) + startTime!: string; + + @Column({ type: 'time', nullable: true }) + endTime?: string; + + @Column() + place!: string; + + @Column({ nullable: true }) + flyerS3Key?: string; +} diff --git a/apps/backend/src/entities/testimonial.entity.ts b/apps/backend/src/entities/testimonial.entity.ts new file mode 100644 index 000000000..1b84c7627 --- /dev/null +++ b/apps/backend/src/entities/testimonial.entity.ts @@ -0,0 +1,27 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; + +@Entity('testimonials') +export class Testimonial { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.testimonials) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column({ type: 'text' }) + question!: string; + + @Column({ type: 'text' }) + answer!: string; + + @Column({ nullable: true }) + stewardImageS3Key?: string; +} diff --git a/apps/backend/src/entities/user.entity.ts b/apps/backend/src/entities/user.entity.ts new file mode 100644 index 000000000..68fb2cde4 --- /dev/null +++ b/apps/backend/src/entities/user.entity.ts @@ -0,0 +1,33 @@ +import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm'; +import { Site } from './site.entity'; +import { StewardEvent } from './steward-event.entity'; +import { Announcement } from './announcement.entity'; + +export enum UserType { + ADMIN = 'admin', + STEWARD = 'steward', +} + +@Entity('users') +export class User { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @Column() + name!: string; + + @Column({ unique: true }) + email!: string; + + @Column({ type: 'enum', enum: UserType }) + type!: UserType; + + @OneToMany(() => Site, (site) => site.steward) + sites!: Site[]; + + @OneToMany(() => StewardEvent, (event) => event.steward) + stewardEvents!: StewardEvent[]; + + @OneToMany(() => Announcement, (announcement) => announcement.steward) + announcements!: Announcement[]; +} diff --git a/apps/backend/src/entities/video.entity.ts b/apps/backend/src/entities/video.entity.ts new file mode 100644 index 000000000..5b7532ae2 --- /dev/null +++ b/apps/backend/src/entities/video.entity.ts @@ -0,0 +1,35 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, +} from 'typeorm'; +import { Site } from './site.entity'; +import { User } from './user.entity'; + +@Entity('videos') +export class Video { + @PrimaryGeneratedColumn('uuid') + id!: string; + + @ManyToOne(() => Site, (site) => site.videos) + @JoinColumn({ name: 'site_id' }) + site!: Site; + + @Column() + s3Key!: string; + + @Column({ type: 'varchar', nullable: true }) + title!: string | null; + + @Column({ type: 'text', nullable: true }) + description!: string | null; + + @Column({ type: 'timestamptz', default: () => 'now()' }) + uploadedAt!: Date; + + @ManyToOne(() => User, { onDelete: 'SET NULL', nullable: true }) + @JoinColumn({ name: 'uploaded_by' }) + uploadedBy!: User | null; +} diff --git a/apps/backend/src/events/README.md b/apps/backend/src/events/README.md new file mode 100644 index 000000000..bb67b8bf1 --- /dev/null +++ b/apps/backend/src/events/README.md @@ -0,0 +1,35 @@ +# Events + +`GET /api/adminEvent` lists Luma-linked staff events so the frontend can show the public event calendar. Steward-run events are not included here — they belong to a separate endpoint. + +## `GET /api/adminEvent` + +**Auth:** `@Public()` — anyone can call this without a Bearer token. + +**Query params** (optional): + +| Param | Meaning | +| --------- | --------------------------- | +| `site_id` | UUID of the associated site | + +Invalid `site_id` (not a UUID) → `400`. + +**Response:** JSON array. Empty `[]` when nothing matches — not `404`. + +Each element: + +| Field | Notes | +| ------------------ | ---------------------------------- | +| `site` | `{ id, name }` | +| `name` | Event title | +| `date` / `time` | `YYYY-MM-DD` and `HH:MM:SS` | +| `description` | Longer copy | +| `registrationLink` | Present when the event has a URL | + +Results are sorted by date, then time, then id (earliest first). + +Swagger: tag **Events**. Enable with `SWAGGER_ENABLED=true` and open `/api`. + +## Schema notes + +`admin_events` stores `name` in addition to `description`. Steward events are unchanged in this PR. diff --git a/apps/backend/src/events/dto/admin-event-query.dto.spec.ts b/apps/backend/src/events/dto/admin-event-query.dto.spec.ts new file mode 100644 index 000000000..4376a59f0 --- /dev/null +++ b/apps/backend/src/events/dto/admin-event-query.dto.spec.ts @@ -0,0 +1,28 @@ +import { plainToInstance } from 'class-transformer'; +import { validate } from 'class-validator'; + +import { AdminEventQueryDto } from './admin-event-query.dto'; + +async function validateQuery(plain: Record) { + const dto = plainToInstance(AdminEventQueryDto, plain); + return validate(dto); +} + +describe('AdminEventQueryDto', () => { + it('accepts a valid site_id', async () => { + const errors = await validateQuery({ + site_id: '11111111-1111-4111-8111-111111111111', + }); + expect(errors).toHaveLength(0); + }); + + it('accepts an empty query (all filters optional)', async () => { + const errors = await validateQuery({}); + expect(errors).toHaveLength(0); + }); + + it('rejects a non-UUID site_id', async () => { + const errors = await validateQuery({ site_id: 'not-a-uuid' }); + expect(errors.some((error) => error.property === 'site_id')).toBe(true); + }); +}); diff --git a/apps/backend/src/events/dto/admin-event-query.dto.ts b/apps/backend/src/events/dto/admin-event-query.dto.ts new file mode 100644 index 000000000..4d0a45224 --- /dev/null +++ b/apps/backend/src/events/dto/admin-event-query.dto.ts @@ -0,0 +1,16 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { IsOptional, IsUUID } from 'class-validator'; + +/** + * Query filters for `GET /adminEvent`. Omitted params are unconstrained. + * Invalid `site_id` (not a UUID) fails validation with 400. + */ +export class AdminEventQueryDto { + @ApiPropertyOptional({ + description: 'Restrict results to events at this site', + format: 'uuid', + }) + @IsOptional() + @IsUUID() + site_id?: string; +} diff --git a/apps/backend/src/events/dto/admin-event-response.dto.ts b/apps/backend/src/events/dto/admin-event-response.dto.ts new file mode 100644 index 000000000..a30134439 --- /dev/null +++ b/apps/backend/src/events/dto/admin-event-response.dto.ts @@ -0,0 +1,44 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +export class AdminEventSiteDto { + @ApiProperty({ format: 'uuid' }) + id!: string; + + @ApiProperty() + name!: string; +} + +/** + * Luma-linked admin event returned by `GET /adminEvent`. + */ +export class AdminEventResponseDto { + @ApiProperty({ format: 'uuid' }) + id!: string; + + @ApiProperty({ type: AdminEventSiteDto }) + site!: AdminEventSiteDto; + + @ApiProperty({ description: 'Event title' }) + name!: string; + + @ApiProperty({ + description: 'Calendar date (YYYY-MM-DD)', + example: '2026-10-25', + }) + date!: string; + + @ApiProperty({ + description: 'Local start time (HH:MM:SS)', + example: '14:00:00', + }) + time!: string; + + @ApiProperty() + description!: string; + + @ApiPropertyOptional({ + description: 'Registration URL, when the event has one', + example: 'https://lu.ma/example-harvest', + }) + registrationLink?: string; +} diff --git a/apps/backend/src/events/events.controller.spec.ts b/apps/backend/src/events/events.controller.spec.ts new file mode 100644 index 000000000..cd8342bbe --- /dev/null +++ b/apps/backend/src/events/events.controller.spec.ts @@ -0,0 +1,51 @@ +import { Test } from '@nestjs/testing'; + +import { IS_PUBLIC_KEY } from '../aws/cognito/cognito.decorator'; +import { EventsController } from './events.controller'; +import { EventsService } from './events.service'; +import { AdminEventResponseDto } from './dto/admin-event-response.dto'; + +describe('EventsController', () => { + let controller: EventsController; + let service: { findAllForAdmin: jest.Mock }; + + const sample: AdminEventResponseDto[] = [ + { + id: 'evt-1', + site: { id: 'site-1', name: 'Egleston' }, + name: 'Harvest', + date: '2026-10-25', + time: '14:00:00', + description: 'Cider', + registrationLink: 'https://lu.ma/harvest', + }, + ]; + + beforeEach(async () => { + service = { findAllForAdmin: jest.fn().mockResolvedValue(sample) }; + + const moduleRef = await Test.createTestingModule({ + controllers: [EventsController], + providers: [{ provide: EventsService, useValue: service }], + }).compile(); + + controller = moduleRef.get(EventsController); + }); + + it('forwards query filters and returns the service result', async () => { + const query = { + site_id: '11111111-1111-4111-8111-111111111111', + }; + + await expect(controller.getAdminEvents(query)).resolves.toEqual(sample); + expect(service.findAllForAdmin).toHaveBeenCalledWith(query); + }); + + it('marks GET /adminEvent as @Public()', () => { + const isPublic = Reflect.getMetadata( + IS_PUBLIC_KEY, + EventsController.prototype.getAdminEvents, + ); + expect(isPublic).toBe(true); + }); +}); diff --git a/apps/backend/src/events/events.controller.ts b/apps/backend/src/events/events.controller.ts new file mode 100644 index 000000000..3b49b9628 --- /dev/null +++ b/apps/backend/src/events/events.controller.ts @@ -0,0 +1,32 @@ +import { Controller, Get, Query } from '@nestjs/common'; +import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger'; + +import { Public } from '../aws/cognito/cognito.decorator'; +import { AdminEventQueryDto } from './dto/admin-event-query.dto'; +import { AdminEventResponseDto } from './dto/admin-event-response.dto'; +import { EventsService } from './events.service'; + +@ApiTags('Events') +@Controller('adminEvent') +export class EventsController { + constructor(private readonly eventsService: EventsService) {} + + /** + * Public chronological list of Luma-linked admin events. + */ + @Get() + @Public() + @ApiOperation({ + summary: 'List Luma-linked admin events', + description: + 'Returns staff / Luma-linked events in chronological order. ' + + 'Filter with `site_id`. An empty array means nothing matched. ' + + 'Steward-run events are not included (separate endpoint).', + }) + @ApiOkResponse({ type: [AdminEventResponseDto] }) + getAdminEvents( + @Query() query: AdminEventQueryDto, + ): Promise { + return this.eventsService.findAllForAdmin(query); + } +} diff --git a/apps/backend/src/events/events.module.ts b/apps/backend/src/events/events.module.ts new file mode 100644 index 000000000..217789ebb --- /dev/null +++ b/apps/backend/src/events/events.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; + +import { AdminEvent } from '../entities/admin-event.entity'; +import { EventsController } from './events.controller'; +import { EventsService } from './events.service'; + +@Module({ + imports: [TypeOrmModule.forFeature([AdminEvent])], + controllers: [EventsController], + providers: [EventsService], +}) +export class EventsModule {} diff --git a/apps/backend/src/events/events.service.spec.ts b/apps/backend/src/events/events.service.spec.ts new file mode 100644 index 000000000..f7fe212ea --- /dev/null +++ b/apps/backend/src/events/events.service.spec.ts @@ -0,0 +1,168 @@ +import { Test } from '@nestjs/testing'; +import { getRepositoryToken } from '@nestjs/typeorm'; + +import { AdminEvent } from '../entities/admin-event.entity'; +import { Site } from '../entities/site.entity'; +import { EventsService } from './events.service'; + +const SITE_A = { + id: '11111111-1111-4111-8111-111111111111', + name: 'Egleston', +} as Site; +const SITE_B = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Fowler Clark', +} as Site; + +function adminEvent( + overrides: Partial & { + id: string; + date: string; + startTime: string; + }, +): AdminEvent { + return { + name: 'Harvest', + description: 'Harvest description', + place: 'Orchard', + registrationLink: 'https://lu.ma/harvest', + site: SITE_A, + ...overrides, + } as AdminEvent; +} + +describe('EventsService', () => { + let service: EventsService; + let adminRepo: { find: jest.Mock }; + + const lumaEvents = [ + adminEvent({ + id: 'a-late', + date: '2026-11-08', + startTime: '11:00:00', + name: 'Winter Planning Workshop', + description: 'Staff-led workshop', + registrationLink: 'https://lu.ma/workshop', + site: SITE_B, + }), + adminEvent({ + id: 'a-early', + date: '2026-10-25', + startTime: '14:00:00', + name: 'Fall Harvest Celebration', + description: 'Cider and potluck', + registrationLink: 'https://lu.ma/harvest', + site: SITE_A, + }), + ]; + + beforeEach(async () => { + adminRepo = { find: jest.fn().mockResolvedValue(lumaEvents) }; + + const moduleRef = await Test.createTestingModule({ + providers: [ + EventsService, + { provide: getRepositoryToken(AdminEvent), useValue: adminRepo }, + ], + }).compile(); + + service = moduleRef.get(EventsService); + }); + + describe('findAllForAdmin', () => { + it('returns the full mapped shape for admin events', async () => { + const results = await service.findAllForAdmin({}); + const harvest = results.find((event) => event.id === 'a-early'); + + expect(harvest).toEqual({ + id: 'a-early', + site: { id: SITE_A.id, name: SITE_A.name }, + name: 'Fall Harvest Celebration', + date: '2026-10-25', + time: '14:00:00', + description: 'Cider and potluck', + registrationLink: 'https://lu.ma/harvest', + }); + expect(harvest).not.toHaveProperty('eventType'); + expect(harvest).not.toHaveProperty('sourceType'); + }); + + it('returns events in chronological order (date, then time)', async () => { + const results = await service.findAllForAdmin({}); + + expect(results.map((event) => event.id)).toEqual(['a-early', 'a-late']); + }); + + it('sorts same-day events by time, then id', async () => { + adminRepo.find.mockResolvedValue([ + adminEvent({ + id: 'same-day-late', + date: '2026-10-25', + startTime: '16:00:00', + }), + adminEvent({ + id: 'same-day-early', + date: '2026-10-25', + startTime: '08:00:00', + }), + adminEvent({ + id: 'same-day-mid', + date: '2026-10-25', + startTime: '08:00:00', + }), + ]); + + const results = await service.findAllForAdmin({}); + expect(results.map((event) => event.id)).toEqual([ + 'same-day-early', + 'same-day-mid', + 'same-day-late', + ]); + }); + + it('normalizes TypeORM Date objects into date and time strings', async () => { + adminRepo.find.mockResolvedValue([ + adminEvent({ + id: 'date-obj', + date: new Date(2026, 9, 25) as unknown as string, + startTime: new Date(2026, 9, 25, 14, 30, 5) as unknown as string, + }), + ]); + + const [event] = await service.findAllForAdmin({}); + expect(event.date).toBe('2026-10-25'); + expect(event.time).toBe('14:30:05'); + }); + + it('filters by site_id', async () => { + await service.findAllForAdmin({ site_id: SITE_A.id }); + + expect(adminRepo.find).toHaveBeenCalledWith({ + where: { site: { id: SITE_A.id } }, + relations: { site: true }, + }); + }); + + it('returns an empty list when nothing matches', async () => { + adminRepo.find.mockResolvedValue([]); + + await expect( + service.findAllForAdmin({ site_id: SITE_B.id }), + ).resolves.toEqual([]); + }); + + it('omits registrationLink when the event has an empty link', async () => { + adminRepo.find.mockResolvedValue([ + adminEvent({ + id: 'a-no-link', + date: '2026-10-01', + startTime: '12:00:00', + registrationLink: '', + }), + ]); + + const [event] = await service.findAllForAdmin({}); + expect(event).not.toHaveProperty('registrationLink'); + }); + }); +}); diff --git a/apps/backend/src/events/events.service.ts b/apps/backend/src/events/events.service.ts new file mode 100644 index 000000000..4c65b3961 --- /dev/null +++ b/apps/backend/src/events/events.service.ts @@ -0,0 +1,92 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { FindOptionsWhere, Repository } from 'typeorm'; + +import { AdminEvent } from '../entities/admin-event.entity'; +import { AdminEventQueryDto } from './dto/admin-event-query.dto'; +import { AdminEventResponseDto } from './dto/admin-event-response.dto'; + +@Injectable() +export class EventsService { + constructor( + @InjectRepository(AdminEvent) + private readonly adminEventRepo: Repository, + ) {} + + /** + * Returns Luma-linked admin events that match `filters`, sorted by date + * then time (earliest first). An empty array means no rows matched. + */ + async findAllForAdmin( + filters: AdminEventQueryDto, + ): Promise { + const events = await this.adminEventRepo.find({ + where: this.buildWhere(filters), + relations: { site: true }, + }); + + const mapped = events.map((event) => this.mapAdminEvent(event)); + mapped.sort((a, b) => compareChronological(a, b)); + return mapped; + } + + private buildWhere( + filters: AdminEventQueryDto, + ): FindOptionsWhere { + const where: FindOptionsWhere = {}; + if (filters.site_id) { + where.site = { id: filters.site_id }; + } + return where; + } + + private mapAdminEvent(event: AdminEvent): AdminEventResponseDto { + const dto: AdminEventResponseDto = { + id: event.id, + site: { id: event.site.id, name: event.site.name }, + name: event.name, + date: normalizeDate(event.date), + time: normalizeTime(event.startTime), + description: event.description, + }; + if (event.registrationLink) { + dto.registrationLink = event.registrationLink; + } + return dto; + } +} + +function pad2(n: number): string { + return String(n).padStart(2, '0'); +} + +function normalizeDate(value: string | Date): string { + if (value instanceof Date) { + return `${value.getFullYear()}-${pad2(value.getMonth() + 1)}-${pad2( + value.getDate(), + )}`; + } + return String(value).slice(0, 10); +} + +function normalizeTime(value: string | Date): string { + if (value instanceof Date) { + return `${pad2(value.getHours())}:${pad2(value.getMinutes())}:${pad2( + value.getSeconds(), + )}`; + } + const asString = String(value); + const match = asString.match(/(\d{2}:\d{2}:\d{2})/); + return match ? match[1] : asString.slice(0, 8); +} + +function compareChronological( + a: Pick, + b: Pick, +): number { + const byDateTime = `${a.date}T${a.time}`.localeCompare(`${b.date}T${b.time}`); + if (byDateTime !== 0) { + return byDateTime; + } + return a.id.localeCompare(b.id); +} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index f5c3ac608..bd55a3bff 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -25,14 +25,27 @@ async function bootstrap() { if (swaggerEnabled) { const config = new DocumentBuilder() - .setTitle('[YOUR_APP_NAME] API Docs') - .setDescription('Documentation for [YOUR_APP_NAME] API routes') + .setTitle('BFFC API Docs') + .setDescription('Documentation for BFFC API routes') .addBearerAuth({ type: 'http', description: '[TL] Replace: how clients obtain a Bearer token for this API.', }) - .addTag('Users', 'Operations on users') + .addTag( + 'Sites', + 'Site details, addresses, plant inventory, and site media', + ) + .addTag('Events', 'Luma-linked admin events') + .addTag('Media', 'Images and videos for a site') + .addTag('Events', 'Admin (Luma-linked) and steward-published events') + .addTag('Users', 'Admin and steward user accounts') + .addTag('Announcements', 'Steward announcements posted to a site') + .addTag( + 'Volunteer Opportunities', + 'Volunteer opportunities tied to a site', + ) + .addTag('Partner Orgs', 'Partner organizations associated with a site') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // Create the Swagger document diff --git a/apps/backend/src/media/dto/media-item.dto.ts b/apps/backend/src/media/dto/media-item.dto.ts new file mode 100644 index 000000000..b62dfe118 --- /dev/null +++ b/apps/backend/src/media/dto/media-item.dto.ts @@ -0,0 +1,34 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; + +export class MediaItemDto { + @ApiProperty({ format: 'uuid' }) + id: string; + + @ApiProperty({ description: 'Full public URL to the media file (unsigned)' }) + url: string; + + @ApiPropertyOptional({ + description: 'Display title for the media item', + nullable: true, + }) + title: string | null; + + @ApiPropertyOptional({ + description: 'Longer description for the media item', + nullable: true, + }) + description: string | null; + + @ApiProperty({ + description: 'When the item was uploaded (ISO 8601)', + type: String, + format: 'date-time', + }) + uploadedAt: Date; + + @ApiPropertyOptional({ + description: "Name of the site's steward or staff member, if available", + nullable: true, + }) + uploadedBy: string | null; +} diff --git a/apps/backend/src/media/dto/media-query.dto.ts b/apps/backend/src/media/dto/media-query.dto.ts new file mode 100644 index 000000000..6a2e28913 --- /dev/null +++ b/apps/backend/src/media/dto/media-query.dto.ts @@ -0,0 +1,43 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { IsIn, IsInt, IsOptional, Max, Min } from 'class-validator'; + +export enum MediaType { + IMAGE = 'image', + VIDEO = 'video', +} + +export class MediaQueryDto { + @ApiPropertyOptional({ + enum: MediaType, + description: + 'Restrict the response to a single media type. Any other value returns 400.', + }) + @IsOptional() + @IsIn(Object.values(MediaType)) + type?: MediaType; + + @ApiPropertyOptional({ + description: 'Page number (1-based)', + minimum: 1, + default: 1, + }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page = 1; + + @ApiPropertyOptional({ + description: 'Number of items per page, per media type', + minimum: 1, + maximum: 100, + default: 20, + }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100) + limit = 20; +} diff --git a/apps/backend/src/media/dto/media-response.dto.ts b/apps/backend/src/media/dto/media-response.dto.ts new file mode 100644 index 000000000..1e51f2f23 --- /dev/null +++ b/apps/backend/src/media/dto/media-response.dto.ts @@ -0,0 +1,27 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { MediaItemDto } from './media-item.dto'; + +export class MediaPaginationDto { + @ApiProperty({ description: 'Current page (1-based)' }) + page: number; + + @ApiProperty({ description: 'Items per page, per media type' }) + limit: number; + + @ApiProperty({ description: 'Total number of images for the site' }) + imagesTotal: number; + + @ApiProperty({ description: 'Total number of videos for the site' }) + videosTotal: number; +} + +export class MediaResponseDto { + @ApiProperty({ type: [MediaItemDto], description: 'Images, newest first' }) + images: MediaItemDto[]; + + @ApiProperty({ type: [MediaItemDto], description: 'Videos, newest first' }) + videos: MediaItemDto[]; + + @ApiProperty({ type: MediaPaginationDto }) + pagination: MediaPaginationDto; +} diff --git a/apps/backend/src/media/media.controller.spec.ts b/apps/backend/src/media/media.controller.spec.ts new file mode 100644 index 000000000..899c6e24a --- /dev/null +++ b/apps/backend/src/media/media.controller.spec.ts @@ -0,0 +1,71 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { NotFoundException } from '@nestjs/common'; +import { MediaController } from './media.controller'; +import { MediaService } from './media.service'; +import { MediaResponseDto } from './dto/media-response.dto'; +import { MediaType } from './dto/media-query.dto'; + +describe('MediaController', () => { + let controller: MediaController; + let mockService: { getMediaBySiteId: jest.Mock }; + + const siteId = '123e4567-e89b-12d3-a456-426614174000'; + + const mockResponse: MediaResponseDto = { + images: [ + { + id: 'img-1', + url: 'https://bucket.s3.us-east-2.amazonaws.com/img.jpg', + title: 'Spring', + description: 'blossoms', + uploadedAt: new Date('2026-04-12T09:00:00Z'), + uploadedBy: 'Jamie Chen', + }, + ], + videos: [], + pagination: { page: 1, limit: 20, imagesTotal: 1, videosTotal: 0 }, + }; + + beforeEach(async () => { + mockService = { getMediaBySiteId: jest.fn() }; + + const module: TestingModule = await Test.createTestingModule({ + controllers: [MediaController], + providers: [{ provide: MediaService, useValue: mockService }], + }).compile(); + + controller = module.get(MediaController); + }); + + it('delegates to the service and returns its result', async () => { + mockService.getMediaBySiteId.mockResolvedValue(mockResponse); + const query = { page: 1, limit: 20 }; + + const result = await controller.getMediaBySiteId(siteId, query); + + expect(mockService.getMediaBySiteId).toHaveBeenCalledWith(siteId, query); + expect(result).toEqual(mockResponse); + }); + + it('passes the type filter through to the service', async () => { + mockService.getMediaBySiteId.mockResolvedValue(mockResponse); + const query = { page: 1, limit: 20, type: MediaType.IMAGE }; + + await controller.getMediaBySiteId(siteId, query); + + expect(mockService.getMediaBySiteId).toHaveBeenCalledWith(siteId, query); + }); + + it('propagates NotFoundException from the service', async () => { + mockService.getMediaBySiteId.mockRejectedValue( + new NotFoundException('Site not found'), + ); + + await expect( + controller.getMediaBySiteId('00000000-0000-0000-0000-000000000000', { + page: 1, + limit: 20, + }), + ).rejects.toThrow(NotFoundException); + }); +}); diff --git a/apps/backend/src/media/media.controller.ts b/apps/backend/src/media/media.controller.ts new file mode 100644 index 000000000..6c86c3a10 --- /dev/null +++ b/apps/backend/src/media/media.controller.ts @@ -0,0 +1,67 @@ +import { Controller, Get, Param, ParseUUIDPipe, Query } from '@nestjs/common'; +import { + ApiTags, + ApiOperation, + ApiParam, + ApiQuery, + ApiResponse, + ApiNotFoundResponse, + ApiBadRequestResponse, +} from '@nestjs/swagger'; +import { MediaService } from './media.service'; +import { MediaResponseDto } from './dto/media-response.dto'; +import { MediaQueryDto, MediaType } from './dto/media-query.dto'; + +@ApiTags('Media') +@Controller('media') +export class MediaController { + constructor(private mediaService: MediaService) {} + + @Get(':siteId') + @ApiOperation({ + summary: 'Get all media for a site', + description: + 'Returns all published images and videos for a single site, newest first, in a paginated response. Optionally filter to a single media type.', + }) + @ApiParam({ + name: 'siteId', + description: 'Site UUID', + type: 'string', + format: 'uuid', + }) + @ApiQuery({ + name: 'type', + required: false, + enum: MediaType, + description: 'Restrict the response to only images or only videos', + }) + @ApiQuery({ + name: 'page', + required: false, + type: Number, + description: 'Page number (1-based, default 1)', + }) + @ApiQuery({ + name: 'limit', + required: false, + type: Number, + description: 'Items per page, per media type (default 20, max 100)', + }) + @ApiResponse({ + status: 200, + description: 'Media retrieved successfully', + type: MediaResponseDto, + }) + @ApiBadRequestResponse({ + description: 'Malformed site ID or invalid query parameter', + }) + @ApiNotFoundResponse({ + description: 'Site not found', + }) + async getMediaBySiteId( + @Param('siteId', ParseUUIDPipe) siteId: string, + @Query() query: MediaQueryDto, + ): Promise { + return this.mediaService.getMediaBySiteId(siteId, query); + } +} diff --git a/apps/backend/src/media/media.module.ts b/apps/backend/src/media/media.module.ts new file mode 100644 index 000000000..ddc0ebb3b --- /dev/null +++ b/apps/backend/src/media/media.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { MediaController } from './media.controller'; +import { MediaService } from './media.service'; +import { Site } from '../entities/site.entity'; +import { Image } from '../entities/image.entity'; +import { Video } from '../entities/video.entity'; + +@Module({ + imports: [TypeOrmModule.forFeature([Site, Image, Video])], + controllers: [MediaController], + providers: [MediaService], + exports: [MediaService], +}) +export class MediaModule {} diff --git a/apps/backend/src/media/media.service.spec.ts b/apps/backend/src/media/media.service.spec.ts new file mode 100644 index 000000000..11de8e817 --- /dev/null +++ b/apps/backend/src/media/media.service.spec.ts @@ -0,0 +1,213 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { NotFoundException } from '@nestjs/common'; +import { MediaService } from './media.service'; +import { Site } from '../entities/site.entity'; +import { Image } from '../entities/image.entity'; +import { Video } from '../entities/video.entity'; +import { MediaType } from './dto/media-query.dto'; + +describe('MediaService', () => { + let service: MediaService; + let siteRepo: { exists: jest.Mock }; + let imageRepo: { findAndCount: jest.Mock; count: jest.Mock }; + let videoRepo: { findAndCount: jest.Mock; count: jest.Mock }; + + const siteId = '123e4567-e89b-12d3-a456-426614174000'; + + const alex = { id: 'u-admin', name: 'Alex Rivera' } as Image['uploadedBy']; + const jamie = { id: 'u-steward', name: 'Jamie Chen' } as Image['uploadedBy']; + + // Three images with out-of-order uploadedAt values so sorting is observable, + // plus a single video. uploadedBy is tracked per item. + const makeSite = (overrides: Partial = {}): Partial => ({ + id: siteId, + name: 'Egleston Community Orchard', + images: [ + { + id: 'img-old', + s3Key: 'sites/test/old.jpg', + title: 'Old', + description: 'oldest image', + uploadedAt: new Date('2026-01-01T00:00:00Z'), + uploadedBy: alex, + site: {} as Site, + }, + { + id: 'img-new', + s3Key: 'sites/test/new.jpg', + title: 'New', + description: 'newest image', + uploadedAt: new Date('2026-06-01T00:00:00Z'), + uploadedBy: jamie, + site: {} as Site, + }, + { + id: 'img-mid', + s3Key: 'sites/test/mid.jpg', + title: 'Mid', + description: 'middle image', + uploadedAt: new Date('2026-03-01T00:00:00Z'), + uploadedBy: alex, + site: {} as Site, + }, + ], + videos: [ + { + id: 'vid-1', + s3Key: 'sites/test/tour.mp4', + title: 'Tour', + description: 'walking tour', + uploadedAt: new Date('2026-05-01T00:00:00Z'), + uploadedBy: jamie, + site: {} as Site, + }, + ], + ...overrides, + }); + + const defaultQuery = { page: 1, limit: 20 }; + + const images = () => + makeSite() + .images!.slice() + .sort((a, b) => b.uploadedAt.getTime() - a.uploadedAt.getTime()); + const videos = () => makeSite().videos!; + + beforeEach(async () => { + process.env.AWS_REGION = 'us-east-2'; + process.env.AWS_MEDIA_BUCKET_NAME = 'test-bucket'; + + siteRepo = { exists: jest.fn().mockResolvedValue(true) }; + imageRepo = { + findAndCount: jest.fn().mockResolvedValue([images(), 3]), + count: jest.fn().mockResolvedValue(3), + }; + videoRepo = { + findAndCount: jest.fn().mockResolvedValue([videos(), 1]), + count: jest.fn().mockResolvedValue(1), + }; + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + MediaService, + { provide: getRepositoryToken(Site), useValue: siteRepo }, + { provide: getRepositoryToken(Image), useValue: imageRepo }, + { provide: getRepositoryToken(Video), useValue: videoRepo }, + ], + }).compile(); + + service = module.get(MediaService); + }); + + it('paginates in the database, newest first, with uploaders loaded', async () => { + await service.getMediaBySiteId(siteId, { page: 3, limit: 5 }); + + const expected = { + where: { site: { id: siteId } }, + relations: ['uploadedBy'], + order: { uploadedAt: 'DESC', id: 'ASC' }, + skip: 10, + take: 5, + }; + expect(imageRepo.findAndCount).toHaveBeenCalledWith(expected); + expect(videoRepo.findAndCount).toHaveBeenCalledWith(expected); + }); + + it('returns both images and videos with URLs, metadata, and uploadedBy', async () => { + const result = await service.getMediaBySiteId(siteId, defaultQuery); + + expect(result.images.map((i) => i.id)).toEqual([ + 'img-new', + 'img-mid', + 'img-old', + ]); + expect(result.videos[0]).toEqual({ + id: 'vid-1', + url: 'https://test-bucket.s3.us-east-2.amazonaws.com/sites/test/tour.mp4', + title: 'Tour', + description: 'walking tour', + uploadedAt: new Date('2026-05-01T00:00:00Z'), + uploadedBy: 'Jamie Chen', + }); + expect(result.pagination).toEqual({ + page: 1, + limit: 20, + imagesTotal: 3, + videosTotal: 1, + }); + }); + + it('returns only images when type=image, without fetching video rows', async () => { + const result = await service.getMediaBySiteId(siteId, { + ...defaultQuery, + type: MediaType.IMAGE, + }); + + expect(result.images).toHaveLength(3); + expect(result.videos).toEqual([]); + expect(videoRepo.findAndCount).not.toHaveBeenCalled(); + // Totals still reflect everything available. + expect(result.pagination.videosTotal).toBe(1); + }); + + it('returns only videos when type=video, without fetching image rows', async () => { + const result = await service.getMediaBySiteId(siteId, { + ...defaultQuery, + type: MediaType.VIDEO, + }); + + expect(result.videos).toHaveLength(1); + expect(result.images).toEqual([]); + expect(imageRepo.findAndCount).not.toHaveBeenCalled(); + expect(result.pagination.imagesTotal).toBe(3); + }); + + it('returns empty arrays for a site with no media', async () => { + imageRepo.findAndCount.mockResolvedValue([[], 0]); + videoRepo.findAndCount.mockResolvedValue([[], 0]); + + const result = await service.getMediaBySiteId(siteId, defaultQuery); + + expect(result).toEqual({ + images: [], + videos: [], + pagination: { page: 1, limit: 20, imagesTotal: 0, videosTotal: 0 }, + }); + }); + + it('keeps full totals when the page holds only part of the results', async () => { + imageRepo.findAndCount.mockResolvedValue([[images()[2]], 3]); + + const result = await service.getMediaBySiteId(siteId, { + page: 2, + limit: 2, + }); + + expect(result.images.map((i) => i.id)).toEqual(['img-old']); + expect(result.pagination.imagesTotal).toBe(3); + }); + + it('returns null uploadedBy when a media item has no uploader', async () => { + imageRepo.findAndCount.mockResolvedValue([ + [{ ...images()[0], uploadedBy: null }], + 1, + ]); + + const result = await service.getMediaBySiteId(siteId, defaultQuery); + + expect(result.images[0].uploadedBy).toBeNull(); + }); + + it('throws NotFoundException when the site does not exist', async () => { + siteRepo.exists.mockResolvedValue(false); + + await expect( + service.getMediaBySiteId( + '00000000-0000-0000-0000-000000000000', + defaultQuery, + ), + ).rejects.toThrow(NotFoundException); + expect(imageRepo.findAndCount).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/backend/src/media/media.service.ts b/apps/backend/src/media/media.service.ts new file mode 100644 index 000000000..a829a035b --- /dev/null +++ b/apps/backend/src/media/media.service.ts @@ -0,0 +1,105 @@ +import { Injectable, NotFoundException } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { Site } from '../entities/site.entity'; +import { Image } from '../entities/image.entity'; +import { Video } from '../entities/video.entity'; +import { MediaItemDto } from './dto/media-item.dto'; +import { MediaResponseDto } from './dto/media-response.dto'; +import { MediaQueryDto, MediaType } from './dto/media-query.dto'; + +@Injectable() +export class MediaService { + private readonly s3Region: string; + private readonly s3Bucket: string; + + constructor( + @InjectRepository(Site) private siteRepo: Repository, + @InjectRepository(Image) private imageRepo: Repository, + @InjectRepository(Video) private videoRepo: Repository