-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathride.ts
More file actions
572 lines (520 loc) · 17.8 KB
/
Copy pathride.ts
File metadata and controls
572 lines (520 loc) · 17.8 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
import express from 'express';
import { v4 as uuid, validate } from 'uuid';
import { Condition } from 'dynamoose';
import * as csv from '@fast-csv/format';
import moment from 'moment-timezone';
import { ObjectType } from 'dynamoose/dist/General';
import * as db from './common';
import { Ride, Status, Type, RideType, SchedulingState } from '../models/ride';
import { Tag, LocationType } from '../models/location';
import { validateUser, daysUntilWeekday } from '../util';
import { DriverType } from '../models/driver';
import { RiderType } from '../models/rider';
import { notify } from '../util/notification';
import { Change, JWTPayload } from '../util/types';
import { UserType } from '../models/subscription';
const router = express.Router();
const tableName = 'Rides';
// Debug endpoint to get current user's JWT token
router.get('/debug/token', validateUser('User'), (req, res) => {
const token = req.headers.authorization?.replace('Bearer ', '');
res.json({
token: token,
user: res.locals.user,
});
});
// Diagnostic endpoint to find corrupted rides that fail populate
router.get('/diagnose', async (_req, res) => {
try {
Ride.scan(new Condition()).exec(async (err, data) => {
if (err) {
res.status(500).send({ err: err.message });
return;
}
const items = data || [];
const bad: any[] = [];
const goodIds: string[] = [];
for (const item of items) {
if (!item) continue;
let id: string | undefined = undefined;
try {
id =
(item as any).id || ((item as any).get && (item as any).get('id'));
} catch (e) {
// Ignore error when getting item ID
}
try {
const populated = await (item as any).populate();
if (id) goodIds.push(id);
} catch (e: any) {
bad.push({ id, error: e?.message || String(e) });
}
}
res
.status(200)
.send({ total: items.length, goodCount: goodIds.length, bad });
});
} catch (e: any) {
res.status(500).send({ err: e?.message || 'diagnostic failed' });
}
});
router.get('/download', (req, res) => {
const dateStart = moment(req.query.date as string).toISOString();
const dateEnd = moment(req.query.date as string)
.endOf('day')
.toISOString();
const condition = new Condition()
.where('startTime')
.between(dateStart, dateEnd)
.where('status')
.not()
.eq(Status.CANCELLED);
const callback = (value: any) => {
const dataToExport = value
.sort((a: any, b: any) => moment(a.startTime).diff(moment(b.startTime)))
.flatMap((doc: any) => {
const start = moment(doc.startTime);
const end = moment(doc.endTime);
const fullName = (user: RiderType | DriverType) =>
`${user.firstName} ${user.lastName.substring(0, 1)}.`;
// Handle multiple riders - create a row for each rider
const ridersToProcess = doc.riders || [];
if (ridersToProcess.length === 0) {
// No riders assigned
return [
{
Name: 'No rider assigned',
'Pick Up': start.format('h:mm A'),
From: doc.startLocation.name,
To: doc.endLocation.name,
'Drop Off': end.format('h:mm A'),
Needs: 'None',
Driver: doc.driver ? fullName(doc.driver) : '',
},
];
}
return ridersToProcess.map((rider: RiderType) => ({
Name: fullName(rider),
'Pick Up': start.format('h:mm A'),
From: doc.startLocation.name,
To: doc.endLocation.name,
'Drop Off': end.format('h:mm A'),
Needs:
rider.accessibility && rider.accessibility.length > 0
? rider.accessibility.join(', ')
: 'None',
Driver: doc.driver ? fullName(doc.driver) : '',
}));
});
csv
.writeToBuffer(dataToExport, { headers: true })
.then((data) => res.send(data))
.catch((err) => res.send(err));
};
db.scan(res, Ride, condition, callback);
});
// Get and query all master repeating rides in table
router.get('/repeating', validateUser('User'), (req, res) => {
const {
query: { rider },
} = req;
const now = moment().format('YYYY-MM-DD');
const condition = new Condition('recurring')
.eq(true)
.where('endDate')
.ge(now)
.where('status')
.not()
.eq(Status.CANCELLED);
if (rider) {
// If rider filter is specified, use callback to filter after scan
db.scan(res, Ride, condition, (data: RideType[]) => {
// Filter for rides that include this rider
const riderRides = data.filter((ride) => {
// Check both old (rider) and new (riders) format for compatibility
if (ride.riders && Array.isArray(ride.riders)) {
return ride.riders.some((riderObj) => riderObj.id === rider);
}
// Legacy support for old rider field (if it exists)
if ((ride as any).rider && (ride as any).rider.id === rider) {
return true;
}
return false;
});
res.status(200).send({ data: riderRides });
});
} else {
// No rider filter, can use direct scan
db.scan(res, Ride, condition);
}
});
// Get a ride by id in Rides table
router.get('/:id', validateUser('User'), (req, res) => {
const {
params: { id },
} = req;
db.getById(res, Ride, id, tableName);
});
// Get all rides for a rider by Rider ID
router.get('/rider/:id', validateUser('User'), (req, res) => {
const {
params: { id },
} = req;
// Scan all rides and filter in JavaScript to avoid Dynamoose array condition issues
db.scan(res, Ride, new Condition(), (data: RideType[]) => {
// Filter for rides that include this rider
const riderRides = data.filter((ride) => {
// Check both old (rider) and new (riders) format for compatibility
if (ride.riders && Array.isArray(ride.riders)) {
return ride.riders.some((rider) => rider.id === id);
}
// Legacy support for old rider field (if it exists)
if ((ride as any).rider && (ride as any).rider.id === id) {
return true;
}
return false;
});
res.status(200).send({ data: riderRides });
});
});
// Get and query all rides in table
router.get('/', validateUser('User'), (req, res) => {
const {
type,
status,
rider,
driver,
date,
scheduled,
schedulingState,
allDates,
} = req.query;
// Extract caller identity from validated JWT (set by validateUser middleware)
const { id: callerId, userType } = res.locals.user as JWTPayload;
// Scope query params to the caller's own identity.
// Admins: pass through whatever the query provides (existing behaviour).
// Riders: always scope to their own rider ID; discard any ?rider= or ?driver= param.
// Drivers: always scope to their own driver ID; discard any ?rider= or ?driver= param.
let effectiveRider = rider as string | undefined;
let effectiveDriver = driver as string | undefined;
if (userType === UserType.RIDER) {
effectiveRider = callerId;
effectiveDriver = undefined;
} else if (userType === UserType.DRIVER) {
effectiveDriver = callerId;
effectiveRider = undefined;
} else if (userType !== UserType.ADMIN) {
// Unrecognised non-admin role — deny as a defence-in-depth fallback
res.status(403).send({ err: 'Insufficient permissions for this request.' });
return;
}
let condition = new Condition();
if (type) {
condition = condition.where('type').eq(type);
} else if (scheduled) {
// Legacy support: scheduled=true means not unscheduled
condition = condition
.where('schedulingState')
.eq(SchedulingState.SCHEDULED);
}
// New schedulingState filter
if (schedulingState) {
condition = condition.where('schedulingState').eq(schedulingState);
}
if (status) {
condition = condition.where('status').eq(status);
}
// Skip rider condition in Dynamoose query - will filter in JavaScript
if (effectiveDriver) {
condition = condition.where('driver').eq(effectiveDriver);
}
// Only apply date filter if date is provided and allDates is not true
if (date && allDates !== 'true') {
const dateStart = moment(date as string).toISOString();
const dateEnd = moment(date as string)
.endOf('day')
.toISOString();
condition = condition.where('startTime').between(dateStart, dateEnd);
}
if (effectiveRider) {
// If rider filter is specified, use callback to filter after scan
db.scan(res, Ride, condition, (data: RideType[]) => {
// Filter for rides that include this rider
const riderRides = data.filter((ride) => {
// Check both old (rider) and new (riders) format for compatibility
if (ride.riders && Array.isArray(ride.riders)) {
return ride.riders.some((riderObj) => riderObj.id === effectiveRider);
}
// Legacy support for old rider field (if it exists)
if ((ride as any).rider && (ride as any).rider.id === effectiveRider) {
return true;
}
return false;
});
res.status(200).send({ data: riderRides });
});
} else {
// No rider filter, can use direct scan
db.scan(res, Ride, condition);
}
});
// Diagnostic endpoint to find corrupted rides that fail populate
router.get('/diagnose', async (_req, res) => {
try {
Ride.scan(new Condition()).exec(async (err, data) => {
if (err) {
res.status(500).send({ err: err.message });
return;
}
const items = data || [];
const bad: any[] = [];
const goodIds: string[] = [];
for (const item of items) {
if (!item) continue;
let id: string | undefined = undefined;
try {
id =
(item as any).id || ((item as any).get && (item as any).get('id'));
} catch (e) {
// Ignore error when getting item ID
}
try {
const populated = await (item as any).populate();
if (id) goodIds.push(id);
} catch (e: any) {
bad.push({ id, error: e?.message || String(e) });
}
}
res
.status(200)
.send({ total: items.length, goodCount: goodIds.length, bad });
});
} catch (e: any) {
res.status(500).send({ err: e?.message || 'diagnostic failed' });
}
});
// Create a new ride
router.post('/', validateUser('User'), (req, res) => {
const { body } = req;
const {
startLocation,
endLocation,
isRecurring = false,
// Legacy support
recurring,
} = body;
// Process locations - convert to reference IDs for storage
const startLocationObj = startLocation as LocationType;
const endLocationObj = endLocation as LocationType;
// For now, only support single rides (isRecurring = false)
if (isRecurring || recurring) {
res.status(400).send({
err: 'Recurring rides are not yet supported. Please create a single ride.',
});
return;
}
// Validate single ride requirements - support both legacy rider and new riders array
const hasRiders = body.riders && body.riders.length > 0;
const hasLegacyRider = body.rider;
if (!body.startTime || !body.endTime || (!hasRiders && !hasLegacyRider)) {
res.status(400).send({
err: 'Missing required fields: startTime, endTime, and at least one rider are required for single rides.',
});
return;
}
// Validate that startTime is in the future
const startTime = new Date(body.startTime);
const now = new Date();
if (startTime <= now) {
res.status(400).send({
err: 'Start time must be in the future.',
});
return;
}
// Validate that endTime is after startTime
const endTime = new Date(body.endTime);
if (endTime <= startTime) {
res.status(400).send({
err: 'End time must be after start time.',
});
return;
}
// Determine scheduling state based on driver assignment
const hasDriver = body.driver ? true : false;
const schedulingState =
body.schedulingState ||
(hasDriver ? SchedulingState.SCHEDULED : SchedulingState.UNSCHEDULED);
// Determine riders array - support both new format and legacy format
let ridersArray;
if (body.riders && body.riders.length > 0) {
ridersArray = body.riders;
} else if (body.rider) {
// Convert legacy single rider to array
ridersArray = [body.rider];
} else {
ridersArray = [];
}
// Process riders - convert to IDs only for database storage (same logic as PUT route)
if (ridersArray && Array.isArray(ridersArray)) {
ridersArray = ridersArray.map((rider: any) =>
typeof rider === 'string' ? rider : rider.id
);
}
// Create single ride
const ride = new Ride({
id: uuid(),
startLocation: startLocationObj,
endLocation: endLocationObj,
startTime: body.startTime,
endTime: body.endTime,
riders: ridersArray,
driver: body.driver || undefined,
type: body.type || Type.UPCOMING,
status: body.status || Status.NOT_STARTED,
schedulingState: schedulingState,
isRecurring: false,
timezone: body.timezone || 'America/New_York',
});
db.create(res, ride, async (doc) => {
const createdRide = doc as RideType;
const { userType } = res.locals.user;
// Send notification
notify(createdRide, body, userType, Change.CREATED)
.then(() => res.send(createdRide))
.catch(() => res.send(createdRide));
});
});
// Update an existing ride
router.put('/:id', validateUser('User'), (req, res) => {
const {
params: { id },
body,
} = req;
const { type, startLocation, endLocation } = body;
if (
type &&
type === Type.UPCOMING &&
body.schedulingState === SchedulingState.UNSCHEDULED
) {
body.$REMOVE = ['driver'];
}
// Auto-update schedulingState based on driver assignment
if (body.driver) {
// If driver is being assigned, mark as scheduled
body.schedulingState = SchedulingState.SCHEDULED;
} else if (body.$REMOVE && body.$REMOVE.includes('driver')) {
// If driver is being removed, mark as unscheduled
body.schedulingState = SchedulingState.UNSCHEDULED;
} else if (
Object.prototype.hasOwnProperty.call(body, 'driver') &&
!body.driver
) {
// If driver is explicitly set to null/undefined, mark as unscheduled
body.schedulingState = SchedulingState.UNSCHEDULED;
}
// Process riders - convert to IDs only for database storage
if (body.riders && Array.isArray(body.riders)) {
body.riders = body.riders.map((rider: any) =>
typeof rider === 'string' ? rider : rider.id
);
}
//Check if id matches or user is admin
db.getById(res, Ride, id, tableName, (ride: RideType) => {
const { riders, driver } = ride;
const userIsRider =
riders && riders.some((rider) => rider.id === res.locals.user.id);
if (
res.locals.user.userType === UserType.ADMIN ||
userIsRider ||
(driver && res.locals.user.id === driver.id)
) {
db.update(res, Ride, { id }, body, tableName, async (doc) => {
const ride = doc;
const { userType } = res.locals.user;
// send ride even if notification failed since it was actually updated
notify(ride, body, userType)
.then(() => res.send(ride))
.catch(() => res.send(ride));
});
} else {
res.status(400).send({
err: 'User ID does not match request ID and user is not an admin.',
});
}
});
});
// Recurring ride edits - disabled until recurring rides are implemented
router.put('/:id/edits', validateUser('User'), (req, res) => {
res.status(400).send({
err: 'Recurring ride edits are not supported yet. Only single rides are currently supported.',
});
});
// Delete an existing ride
router.delete('/:id', validateUser('User'), (req, res) => {
const {
params: { id },
} = req;
db.getById(res, Ride, id, tableName, (ride) => {
const { isRecurring, riders, driver } = ride;
// For now, block deletion of recurring rides
if (isRecurring) {
res.status(400).send({
err: 'Recurring ride deletion not supported yet. Only single rides can be deleted.',
});
return;
}
// Check if user has permission to cancel/delete this ride
const userIsRider =
riders && riders.some((rider: any) => rider.id === res.locals.user.id);
const userIsDriver = driver && res.locals.user.id === driver.id;
const userIsAdmin = res.locals.user.userType === 'Admin';
if (!userIsAdmin && !userIsRider && !userIsDriver) {
res.status(403).send({
err: 'You do not have permission to cancel this ride.',
});
return;
}
// Check constraints based on user type and ride status
if (!userIsAdmin) {
// Riders can only cancel rides that haven't started
if (userIsRider && ride.status !== Status.NOT_STARTED) {
res.status(400).send({
err: 'You can only cancel rides that have not started yet.',
});
return;
}
// Drivers cannot cancel rides (only admins can)
if (userIsDriver && !userIsRider) {
res.status(400).send({
err: 'Drivers cannot cancel rides. Please contact an admin.',
});
return;
}
}
// Admin can cancel any ride, but check if it's already completed/past
if (ride.status === Status.COMPLETED) {
res.status(400).send({
err: 'Cannot cancel a ride that has already been completed.',
});
return;
}
// Delete the ride from database and send notification
Ride.delete(id)
.then(async () => {
// Send cancellation notification
const { userType } = res.locals.user;
try {
await notify(ride, {}, userType, Change.CANCELLED);
} catch (notificationError) {
console.error(
'Failed to send cancellation notification:',
notificationError
);
// Continue with the response even if notification fails
}
res.send({ id });
})
.catch((err) => res.status(500).send({ err: err.message }));
});
});
export default router;