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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions apps/backend/src/orders/order.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import { FilesInterceptor } from '@nestjs/platform-express';
import * as multer from 'multer';
import { ConfirmDeliveryDto } from './dtos/confirm-delivery.dto';
import { CompleteVolunteerActionDto } from './dtos/complete-volunteer-action.dto';
import { FoodRequest } from '../foodRequests/request.entity';
import { CreateOrderDto } from './dtos/create-order.dto';
import { AuthenticatedRequest } from '../auth/authenticated-request';
import { Roles } from '../auth/roles.decorator';
Expand Down Expand Up @@ -82,8 +81,8 @@ export class OrdersController {
resolver: async ({ entityId, services }) => {
return pipeNullable(
() => services.get(OrdersService).findOrderFoodRequest(entityId),
(request: FoodRequest) =>
services.get(PantriesService).findOne(request.pantryId),
(request: FoodRequestSummaryDto) =>
services.get(PantriesService).findOne(request.pantry.pantryId),
(pantry: Pantry) => [pantry.pantryUser.id],
);
},
Expand Down
30 changes: 1 addition & 29 deletions apps/backend/src/orders/order.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,44 +404,16 @@ describe('OrdersService', () => {
const orders = await service.getOrdersByPantry(pantryId);

expect(orders.length).toBe(2);
expect(orders.every((order) => order.request)).toBeDefined();
expect(orders.every((order) => order.request.pantryId === 1)).toBe(true);
expect(orders.every((order) => order.request.pantry)).toBeDefined();
expect(orders.every((order) => order.assignee)).toBeDefined();
});

it('returns empty list for pantry with no orderes', async () => {
it('returns empty list for pantry with no orders', async () => {
const pantryId = 5;
const orders = await service.getOrdersByPantry(pantryId);

expect(orders).toEqual([]);
});

it('honors year filter (no results for future year)', async () => {
const pantryId = 1;
const orders = await service.getOrdersByPantry(pantryId, [2025]);
expect(orders).toEqual([]);
});

it('returns orders when a valid year filter is provided', async () => {
const pantryId = 1;

// Change some order dates so we have 2024, 2025 and 2026 values
await testDataSource.query(
`UPDATE "orders" SET created_at='2025-01-01' WHERE order_id = 1`,
);
await testDataSource.query(
`UPDATE "orders" SET created_at='2026-01-01' WHERE order_id = 2`,
);

const orders = await service.getOrdersByPantry(pantryId, [2024, 2025]);
expect(orders.length).toBeGreaterThan(0);

const years = orders.map((o) => new Date(o.createdAt).getFullYear());
expect(years).toContain(2025);
expect(years.every((y) => y === 2024 || y === 2025)).toBe(true);
});

it('throws NotFoundException for non-existent pantry', async () => {
const pantryId = 9999;

Expand Down
39 changes: 27 additions & 12 deletions apps/backend/src/orders/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { DonationItemsService } from '../donationItems/donationItems.service';
import { AllocationsService } from '../allocations/allocations.service';
import { ApplicationStatus } from '../shared/types';
import { VolunteerOrder } from '../volunteers/types';
import { OrderSummary } from '../pantries/types';

@Injectable()
export class OrdersService {
Expand Down Expand Up @@ -452,10 +453,7 @@ export class OrdersService {
return updatedOrder;
}

async getOrdersByPantry(
pantryId: number,
years?: number[],
): Promise<Order[]> {
async getOrdersByPantry(pantryId: number): Promise<OrderSummary[]> {
validateId(pantryId, 'Pantry');

const pantry = await this.pantryRepo.findOneBy({ pantryId });
Expand All @@ -468,18 +466,35 @@ export class OrdersService {
.leftJoinAndSelect('order.request', 'request')
.leftJoin('request.pantry', 'pantry')
.addSelect('pantry.pantryName')
.leftJoinAndSelect('order.allocations', 'allocations')
.leftJoinAndSelect('allocations.item', 'item')
.leftJoinAndSelect('order.assignee', 'assignee')
.where('request.pantryId = :pantryId', { pantryId });

if (years && years.length > 0) {
qb.andWhere('EXTRACT(YEAR FROM order.createdAt) IN (:...years)', {
years,
});
}
const orders = await qb.getMany();

return qb.getMany();
return orders.map((order) => ({
orderId: order.orderId,
status: order.status,
createdAt: order.createdAt.toISOString(),
shippedAt: order.shippedAt?.toISOString() ?? null,
deliveredAt: order.deliveredAt?.toISOString() ?? null,
request: {
pantryId: order.request.pantryId,
pantry: {
pantryName: order.request.pantry.pantryName,
volunteers:
order.request.pantry.volunteers?.map((v) => ({
id: v.id,
firstName: v.firstName,
lastName: v.lastName,
})) ?? null,
},
},
assignee: {
id: order.assignee.id,
firstName: order.assignee.firstName,
lastName: order.assignee.lastName,
},
}));
}

async updateTrackingCostInfo(orderId: number, dto: TrackingCostDto) {
Expand Down
10 changes: 3 additions & 7 deletions apps/backend/src/pantries/pantries.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Pantry } from './pantries.entity';
import { mock } from 'jest-mock-extended';
import { PantryApplicationDto } from './dtos/pantry-application.dto';
import { OrdersService } from '../orders/order.service';
import { Order } from '../orders/order.entity';
import {
Activity,
AllergensConfidence,
Expand All @@ -16,6 +15,7 @@ import {
ServeAllergicChildren,
ApprovedPantryResponse,
TotalStats,
OrderSummary,
} from './types';
import { EmailsService } from '../emails/email.service';
import { ApplicationStatus } from '../shared/types';
Expand Down Expand Up @@ -359,21 +359,17 @@ describe('PantriesController', () => {
it('should return orders for a pantry', async () => {
const pantryId = 24;

const mockOrders: Partial<Order>[] = [
const mockOrders: Partial<OrderSummary>[] = [
{
orderId: 26,
requestId: 26,
foodManufacturerId: 32,
},
{
orderId: 27,
requestId: 27,
foodManufacturerId: 33,
},
];

mockOrdersService.getOrdersByPantry.mockResolvedValue(
mockOrders as Order[],
mockOrders as OrderSummary[],
);

const result = await controller.getOrders(pantryId);
Expand Down
4 changes: 2 additions & 2 deletions apps/backend/src/pantries/pantries.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ import {
ServeAllergicChildren,
ApprovedPantryResponse,
TotalStats,
OrderSummary,
} from './types';
import { Order } from '../orders/order.entity';
import { OrdersService } from '../orders/order.service';
import { CheckOwnership, pipeNullable } from '../auth/ownership.decorator';
import { Public } from '../auth/public.decorator';
Expand Down Expand Up @@ -122,7 +122,7 @@ export class PantriesController {
@Get('/:pantryId/orders')
async getOrders(
@Param('pantryId', ParseIntPipe) pantryId: number,
): Promise<Order[]> {
): Promise<OrderSummary[]> {
return this.ordersService.getOrdersByPantry(pantryId);
}

Expand Down
28 changes: 28 additions & 0 deletions apps/backend/src/pantries/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,38 @@
import { OrderStatus } from '../orders/types';

export interface ApprovedPantryResponse {
pantryId: number;
pantryName: string;
refrigeratedDonation: RefrigeratedDonation;
volunteers: AssignedVolunteer[];
}

export interface OrderSummary {
orderId: number;
status: OrderStatus;
createdAt: string;
shippedAt: string | null;
deliveredAt: string | null;
request: {
pantryId: number;
pantry: {
pantryName: string;
volunteers:
| {
id: number;
firstName: string;
lastName: string;
}[]
| null;
};
};
assignee: {
id: number;
firstName: string;
lastName: string;
};
}

export interface AssignedVolunteer {
userId: number;
firstName: string;
Expand Down
12 changes: 9 additions & 3 deletions apps/backend/src/volunteers/volunteers.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,11 @@ describe('VolunteersController', () => {
});
});

describe('GET /:id/my-recent-orders', () => {
describe('GET /me/my-recent-orders', () => {
it('returns the 2 most recent orders for a volunteer', async () => {
const req: AuthenticatedRequest = {
user: { id: 6 },
} as AuthenticatedRequest;
const assignee = { id: 6, firstName: 'James', lastName: 'Thomas' };
const recentOrders: Partial<VolunteerOrder>[] = [
{
Expand All @@ -236,17 +239,20 @@ describe('VolunteersController', () => {
recentOrders as VolunteerOrder[],
);

const result = await controller.getRecentOrders(6);
const result = await controller.getRecentOrders(req);

expect(result).toEqual(recentOrders);
expect(result).toHaveLength(2);
expect(mockVolunteersService.getRecentOrders).toHaveBeenCalledWith(6);
});

it('returns empty array when volunteer has no assigned orders', async () => {
const req: AuthenticatedRequest = {
user: { id: 6 },
} as AuthenticatedRequest;
mockVolunteersService.getRecentOrders.mockResolvedValueOnce([]);

const result = await controller.getRecentOrders(6);
const result = await controller.getRecentOrders(req);

expect(result).toEqual([]);
expect(mockVolunteersService.getRecentOrders).toHaveBeenCalledWith(6);
Expand Down
22 changes: 8 additions & 14 deletions apps/backend/src/volunteers/volunteers.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { Assignments, VolunteerOrder } from './types';
import { AuthenticatedRequest } from '../auth/authenticated-request';
import { OrdersService } from '../orders/order.service';
import { FoodRequestSummaryDto } from '../foodRequests/dtos/food-request-summary.dto';
import { CheckOwnership } from '../auth/ownership.decorator';

@Controller('volunteers')
export class VolunteersController {
Expand Down Expand Up @@ -44,19 +43,6 @@ export class VolunteersController {
return this.volunteersService.findOne(userId);
}

@CheckOwnership({
idParam: 'id',
resolver: async ({ entityId }) => [entityId],
bypassRoles: [Role.ADMIN],
})
@Roles(Role.VOLUNTEER, Role.ADMIN)
@Get('/:id/my-recent-orders')
async getRecentOrders(
@Param('id', ParseIntPipe) id: number,
): Promise<VolunteerOrder[]> {
return this.volunteersService.getRecentOrders(id);
}

@Post('/:id/pantries')
async assignPantries(
@Param('id', ParseIntPipe) id: number,
Expand All @@ -75,6 +61,14 @@ export class VolunteersController {
return this.volunteersService.findRequestsByVolunteer(currentUser.id);
}

@Roles(Role.VOLUNTEER)
@Get('/me/my-recent-orders')
async getRecentOrders(
@Req() req: AuthenticatedRequest,
): Promise<VolunteerOrder[]> {
return this.volunteersService.getRecentOrders(req.user.id);
}

// returns all orders globally
// only includes actionCompletion for orders assigned to the requesting volunteer
@Roles(Role.VOLUNTEER)
Expand Down
16 changes: 10 additions & 6 deletions apps/frontend/src/api/apiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import axios, {
type InternalAxiosRequestConfig,
} from 'axios';
import { NavigateFunction } from 'react-router-dom';
import { ROUTES } from '../routes';
import {
User,
Order,
Expand All @@ -24,7 +25,6 @@ import {
ConfirmDeliveryDto,
OrderWithoutRelations,
FoodRequestSummaryDto,
OrderWithoutFoodManufacturer,
PantryWithUser,
Assignments,
PantryStats,
Expand Down Expand Up @@ -76,9 +76,9 @@ export class ApiClient {
(error: AxiosError) => {
if (error.response?.status === 403) {
if (this.navigate) {
this.navigate('/unauthorized');
this.navigate(ROUTES.UNAUTHORIZED);
} else {
window.location.replace('/unauthorized');
window.location.replace(ROUTES.UNAUTHORIZED);
}
}
return Promise.reject(error);
Expand Down Expand Up @@ -169,9 +169,7 @@ export class ApiClient {
.then((response) => response.data);
}

public async getPantryOrders(
pantryId: number,
): Promise<OrderWithoutFoodManufacturer[]> {
public async getPantryOrders(pantryId: number): Promise<OrderSummary[]> {
Comment thread
dburkhart07 marked this conversation as resolved.
return this.axiosInstance
.get(`/api/pantries/${pantryId}/orders`)
.then((response) => response.data);
Expand Down Expand Up @@ -255,6 +253,12 @@ export class ApiClient {
.then((response) => response.data);
}

public async getVolunteerRecentOrders(): Promise<VolunteerOrder[]> {
return this.axiosInstance
.get(`/api/volunteers/me/my-recent-orders`)
.then((response) => response.data);
}

public async completeOrderAction(
orderId: number,
action: VolunteerAction,
Expand Down
18 changes: 18 additions & 0 deletions apps/frontend/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import ProfilePage from '@containers/profilePage';
import VolunteerOrderManagement from '@containers/volunteerOrderManagement';
import TestAdminDashboard from '@containers/testAdminDashboard';
import AdminRequestManagement from '@containers/adminRequestManagement';
import PantryDashboard from '@containers/pantryDashboard';
import VolunteerDashboard from '@containers/volunteerDashboard';

Amplify.configure(CognitoAuthConfig);

Expand Down Expand Up @@ -85,6 +87,22 @@ const router = createBrowserRouter([
</ProtectedRoute>
),
},
{
path: ROUTES.PANTRY_DASHBOARD,
element: (
<ProtectedRoute>
<PantryDashboard />
</ProtectedRoute>
),
},
{
path: ROUTES.VOLUNTEER_DASHBOARD,
element: (
<ProtectedRoute>
<VolunteerDashboard />
</ProtectedRoute>
),
},
{
path: ROUTES.FM_DONATION_MANAGEMENT,
element: (
Expand Down
Loading
Loading