forked from Code-4-Community/scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorder.controller.ts
More file actions
301 lines (279 loc) · 8.92 KB
/
order.controller.ts
File metadata and controls
301 lines (279 loc) · 8.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import {
Controller,
Get,
Patch,
Param,
ParseIntPipe,
Body,
Query,
BadRequestException,
ValidationPipe,
UploadedFiles,
UseInterceptors,
Post,
PayloadTooLargeException,
Req,
} from '@nestjs/common';
import { ApiBody } from '@nestjs/swagger';
import { OrdersService } from './order.service';
import { Order } from './order.entity';
import { Pantry } from '../pantries/pantries.entity';
import { FoodManufacturer } from '../foodManufacturers/manufacturers.entity';
import { AllocationsService } from '../allocations/allocations.service';
import { OrderStatus } from './types';
import { CheckOwnership, pipeNullable } from '../auth/ownership.decorator';
import { PantriesService } from '../pantries/pantries.service';
import { TrackingCostDto } from './dtos/tracking-cost.dto';
import { OrderDetailsDto } from './dtos/order-details.dto';
import { FoodRequestSummaryDto } from '../foodRequests/dtos/food-request-summary.dto';
import { AWSS3Service } from '../aws/aws-s3.service';
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';
import { Role } from '../users/types';
@Controller('orders')
export class OrdersController {
constructor(
private readonly ordersService: OrdersService,
private readonly allocationsService: AllocationsService,
private readonly awsS3Service: AWSS3Service,
) {}
// Called like: /?status=pending&pantryName=Test%20Pantry&pantryName=Test%20Pantry%202
// %20 is the URL encoded space character
// This gets all orders where the status is pending and the pantry name is either Test Pantry or Test Pantry 2
@Get('/')
async getAllOrders(
@Query('status') status?: string,
@Query('pantryName') pantryNames?: string | string[],
): Promise<Order[]> {
if (typeof pantryNames === 'string') {
pantryNames = [pantryNames];
}
return this.ordersService.getAll({ status, pantryNames });
}
@Get('/get-current-orders')
async getCurrentOrders(): Promise<Order[]> {
return this.ordersService.getCurrentOrders();
}
@Get('/get-past-orders')
async getPastOrders(): Promise<Order[]> {
return this.ordersService.getPastOrders();
}
@Get('/:orderId/pantry')
async getPantryFromOrder(
@Param('orderId', ParseIntPipe) orderId: number,
): Promise<Pantry> {
return this.ordersService.findOrderPantry(orderId);
}
// Test endpoint for right now
@CheckOwnership({
idParam: 'orderId',
resolver: async ({ entityId, services }) => {
return pipeNullable(
() => services.get(OrdersService).findOrderFoodRequest(entityId),
(request: FoodRequest) =>
services.get(PantriesService).findOne(request.pantryId),
(pantry: Pantry) => [pantry.pantryUser.id],
);
},
bypassRoles: [Role.VOLUNTEER],
})
@Roles(Role.VOLUNTEER, Role.PANTRY)
@Get('/:orderId/request')
async getRequestFromOrder(
@Param('orderId', ParseIntPipe) orderId: number,
): Promise<FoodRequestSummaryDto> {
return this.ordersService.findOrderFoodRequest(orderId);
}
@Get('/:orderId/manufacturer')
async getManufacturerFromOrder(
@Param('orderId', ParseIntPipe) orderId: number,
): Promise<FoodManufacturer> {
return this.ordersService.findOrderFoodManufacturer(orderId);
}
@Get('/:orderId')
async getOrder(
@Param('orderId', ParseIntPipe) orderId: number,
): Promise<OrderDetailsDto> {
return this.ordersService.findOrderDetails(orderId);
}
@Get('/order/:requestId')
async getOrderByRequestId(
@Param('requestId', ParseIntPipe) requestId: number,
): Promise<Order> {
return this.ordersService.findOrderByRequest(requestId);
}
@Get('/:orderId/allocations')
async getAllAllocationsByOrder(
@Param('orderId', ParseIntPipe) orderId: number,
) {
return this.allocationsService.getAllAllocationsByOrder(orderId);
}
@Post('/')
@ApiBody({
description: 'Details for creating a order',
schema: {
type: 'object',
properties: {
foodRequestId: {
type: 'integer',
description: 'ID of the associated request this order is related to',
example: 1,
},
manufacturerId: {
type: 'integer',
description: 'Food manufacturer ID of the FM fulfilling the order',
example: 1,
},
itemAllocations: {
type: 'object',
description:
'Map of donationItemId -> quantity to allocate, donation items and their quantity to allocate for this order',
additionalProperties: {
type: 'integer',
example: 10,
},
example: {
'5': 10,
'8': 3,
'12': 7,
},
},
},
},
})
async createOrder(
@Req() req: AuthenticatedRequest,
@Body(new ValidationPipe())
orderData: CreateOrderDto,
): Promise<Order> {
const parsedAllocations = new Map<number, number>();
for (const [key, value] of Object.entries(orderData.itemAllocations)) {
const itemId = Number(key);
if (!Number.isInteger(itemId) || itemId < 1) {
throw new BadRequestException(`Invalid item ID: ${key}`);
}
if (typeof value !== 'number') {
throw new BadRequestException(
`Quantity for item ${key} must be of type number`,
);
}
if (!Number.isInteger(value) || value < 1) {
throw new BadRequestException(`Invalid quantity for item ${key}`);
}
if (parsedAllocations.has(itemId)) {
throw new BadRequestException(
`Invalid duplicate item IDs for item: ${itemId}`,
);
}
parsedAllocations.set(itemId, value);
}
return this.ordersService.create(
orderData.foodRequestId,
orderData.manufacturerId,
parsedAllocations,
req.user.id,
);
}
@Patch('/update-status/:orderId')
async updateStatus(
@Param('orderId', ParseIntPipe) orderId: number,
@Body('newStatus') newStatus: string,
): Promise<void> {
if (!Object.values(OrderStatus).includes(newStatus as OrderStatus)) {
throw new BadRequestException('Invalid status');
}
return this.ordersService.updateStatus(orderId, newStatus as OrderStatus);
}
@Patch('/:orderId/update-tracking-cost-info')
async updateTrackingCostInfo(
@Param('orderId', ParseIntPipe) orderId: number,
@Body(new ValidationPipe())
dto: TrackingCostDto,
): Promise<void> {
return this.ordersService.updateTrackingCostInfo(orderId, dto);
}
@Patch('/:orderId/confirm-delivery')
@ApiBody({
description: 'Details for a confirmation of order delivery form',
schema: {
type: 'object',
properties: {
dateReceived: {
type: 'string',
format: 'date-time',
example: new Date().toISOString(),
},
feedback: {
type: 'string',
nullable: true,
example: 'Wonderful shipment!',
},
photos: {
type: 'array',
items: { type: 'string' },
nullable: true,
example: [
'https://s3.amazonaws.com/bucket/photo1.jpg',
'https://s3.amazonaws.com/bucket/photo2.jpg',
],
},
},
},
})
@UseInterceptors(
FilesInterceptor('photos', 10, {
storage: multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // 5 MB in bytes
},
}),
)
async confirmDelivery(
@Param('orderId', ParseIntPipe) orderId: number,
@Body() body: ConfirmDeliveryDto,
@UploadedFiles() photos?: Express.Multer.File[],
): Promise<Order> {
try {
const uploadedPhotoUrls =
photos && photos.length > 0
? await this.awsS3Service.upload(photos)
: [];
return this.ordersService.confirmDelivery(
orderId,
body,
uploadedPhotoUrls,
);
} catch (err: unknown) {
if (typeof err === 'object' && err !== null && 'code' in err) {
if (err.code === 'LIMIT_FILE_SIZE') {
throw new PayloadTooLargeException(
'Each photo must be 5 MB or smaller',
);
}
}
throw err;
}
}
@CheckOwnership({
idParam: 'orderId',
resolver: async ({ entityId, services }) =>
pipeNullable(
() => services.get(OrdersService).findOne(entityId),
(order: Order) => [order.assigneeId],
),
})
@Roles(Role.VOLUNTEER)
@Patch('/:orderId/complete-action')
async completeVolunteerAction(
@Param('orderId', ParseIntPipe) orderId: number,
@Body(new ValidationPipe()) dto: CompleteVolunteerActionDto,
) {
return this.ordersService.completeVolunteerAction(orderId, dto.action);
}
}