-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.ts
499 lines (483 loc) · 13.8 KB
/
post.ts
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
import { TRPCError } from "@trpc/server";
import { z, ZodArray } from "zod";
import {
createPost,
deletePost,
finalizePost,
getPost,
getAllPosts,
updatePostStatus,
getFilteredPosts,
getAttachments,
finalizePostEdit,
pushUserAppliedTo,
getUserContextualizedPost,
createDraftPost,
} from "../../db/actions/Post";
import Post from "../../db/models/Post";
import {
FosterType,
Size,
Breed,
Gender,
Age,
Temperament,
GoodWith,
Medical,
Behavioral,
Trained,
IPost,
IDraftPost,
} from "../../utils/types/post";
import { findUserByEmail, updateUserByUid } from "../../db/actions/User";
import { router, procedure } from "../trpc";
import nodemailer from "nodemailer";
import { FilterQuery, Types } from "mongoose";
import { populateEmailTemplate } from "../../email/email-template";
import inlineCss from "inline-css";
import { postFilterSchema } from "../../components/FeedPage/FeedPage";
const zodOidType = z.custom<Types.ObjectId>(
(item) => String(item).length == 24
);
const questionnaireSchema = z.array(
z.object({
key: z.string(),
answer: z.string(),
})
);
const postSchema = z.object({
name: z.string(),
description: z.string(),
type: z.nativeEnum(FosterType),
size: z.nativeEnum(Size),
breed: z.array(z.nativeEnum(Breed)),
otherBreedDescription: z.string().optional(),
gender: z.nativeEnum(Gender),
age: z.nativeEnum(Age),
draft: z.boolean(),
temperament: z.array(z.nativeEnum(Temperament)),
medical: z.array(z.nativeEnum(Medical)),
behavioral: z.array(z.nativeEnum(Behavioral)),
houseTrained: z.nativeEnum(Trained),
crateTrained: z.nativeEnum(Trained),
spayNeuterStatus: z.nativeEnum(Trained),
getsAlongWithMen: z.nativeEnum(Trained),
getsAlongWithWomen: z.nativeEnum(Trained),
getsAlongWithOlderKids: z.nativeEnum(Trained),
getsAlongWithYoungKids: z.nativeEnum(Trained),
getsAlongWithLargeDogs: z.nativeEnum(Trained),
getsAlongWithSmallDogs: z.nativeEnum(Trained),
getsAlongWithCats: z.nativeEnum(Trained),
attachments: z.array(
z.discriminatedUnion("type", [
z.object({
type: z.literal("image"),
key: z.string(),
length: z.number(),
width: z.number(),
}),
z.object({
type: z.literal("video"),
key: z.string(),
}),
])
),
});
const draftPostSchema = postSchema.extend({
type: z.nativeEnum(FosterType).nullable(),
size: z.nativeEnum(Size).nullable(),
breed: z.array(z.nativeEnum(Breed)).nullable(),
gender: z.nativeEnum(Gender).nullable(),
age: z.nativeEnum(Age).nullable(),
});
const fosterTypeEmails: Record<FosterType, string> = {
[FosterType.FosterMove]: "foster@angelsrescue.org",
[FosterType.Return]: "returns@angelsrescue.org, foster@angelsrescue.org",
[FosterType.Temporary]: "tempfoster@angelsrescue.org",
[FosterType.Boarding]: "boardingadmin@angelsrescue.org",
[FosterType.Shelter]: "fosteroffer@angelsrescue.org",
[FosterType.OwnerSurrender]: "fosteroffer@angelsrescue.org",
} as const;
const transporter = nodemailer.createTransport({
host: process.env.SMTP_SERVER_EMAIL,
port: parseInt(process.env.PORT_EMAIL as string),
auth: {
user: process.env.LOGIN_EMAIL,
pass: process.env.PASSWORD_EMAIL,
},
});
const goodWithMap: Record<GoodWith, string> = {
[GoodWith.Cats]: "getsAlongWithCats",
[GoodWith.LargeDogs]: "getsAlongWithLargeDogs",
[GoodWith.Men]: "getsAlongWithMen",
[GoodWith.OlderChildren]: "getsAlongWithOlderKids",
[GoodWith.SmallDogs]: "getsAlongWithSmallDogs",
[GoodWith.Women]: "getsAlongWithWomen",
[GoodWith.YoungChildren]: "getsAlongWithYoungKids",
} as const;
export const postRouter = router({
get: procedure
.input(
z.object({
_id: zodOidType,
})
)
.query(async ({ input, ctx }) => {
try {
return getUserContextualizedPost(input._id, ctx.session.uid, true);
} catch (e) {
console.error(e);
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
create: procedure.input(postSchema).mutation(async ({ input }) => {
const session = await Post.startSession();
session.startTransaction();
try {
const post = await createPost(
{
...input,
date: new Date(),
covered: false,
usersAppliedTo: [],
},
session
);
await session.commitTransaction();
return post;
} catch (e) {
await session.abortTransaction();
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
draft: procedure.input(draftPostSchema).mutation(async ({ input }) => {
const session = await Post.startSession();
session.startTransaction();
try {
const post = await createDraftPost(
{
...input,
date: new Date(),
covered: false,
usersAppliedTo: [],
},
session
);
await session.commitTransaction();
return post;
} catch (e) {
await session.abortTransaction();
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
offer: procedure
.input(
z.object({
email: z.string(),
postOid: zodOidType,
responses: questionnaireSchema,
})
)
.mutation(async ({ input }) => {
try {
const user = await findUserByEmail(input.email);
if (!user) {
throw new Error("No user with given email exists");
}
const post = await getPost(input.postOid, true);
if (!post) {
throw new Error("No post with given id exists.");
}
const email =
process.env.NEXT_PUBLIC_CONTEXT === "production"
? fosterTypeEmails[post.type]
: input.email;
const emailBody = populateEmailTemplate(post, user, input.responses);
let count = 0;
const maxTries = 3;
const options = { url: "www.angelsrescue.org" };
while (true) {
try {
const emailFormatted = await inlineCss(emailBody, options);
await transporter.sendMail({
from: '"Angels Among Us Pet Rescue Placements Platform" <bitsofgood.aau@gmail.com>',
to: email,
subject: `[OFFER] ${user.name ?? "Volunteer"} <> ${post.name}`,
html: emailFormatted,
});
break;
} catch (e) {
if (++count == maxTries) {
throw new TRPCError({
message: "Unable to send Email.",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}
}
await pushUserAppliedTo(input.postOid, user.uid);
} catch (e) {
if (e instanceof TRPCError) throw e;
else
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "An unexpected error occurred.",
cause: e,
});
}
return { success: true };
}),
delete: procedure
.input(
z.object({
postOid: zodOidType,
})
)
.mutation(async ({ input }) => {
try {
return await deletePost(input.postOid);
} catch (e) {
if (e instanceof TRPCError) {
throw e;
} else {
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}
}),
finalize: procedure
.input(
z.object({
_id: zodOidType,
})
)
.mutation(async ({ input }) => {
try {
return await finalizePost(input._id);
} catch (e) {
throw new TRPCError({
message: "All attachments not uploaded",
code: "PRECONDITION_FAILED",
cause: e,
});
}
}),
finalizeEdit: procedure
.input(
z.object({
oldId: zodOidType,
newId: zodOidType,
})
)
.mutation(async ({ input }) => {
try {
return await finalizePostEdit(input.oldId, input.newId);
} catch (e) {
throw new TRPCError({
message: "All attachments not uploaded",
code: "PRECONDITION_FAILED",
cause: e,
});
}
}),
/**
* `editPost` does not actually edit the target post id:
* - A new post document is created (new _id) with the updated fields (post-edit)
* - The updated attachments are uploaded with the new post id as the prefix for the object key
* - The old document and its attachments are deleted
*/
editPost: procedure
.input(
z.object({
_id: zodOidType,
updateFields: postSchema,
})
)
.mutation(async ({ input }) => {
try {
const existingPost = await getPost(input._id, false);
if (!existingPost) {
throw new Error("Unable to find existing post id.");
}
const newPost = await createPost({
...input.updateFields,
date: existingPost.date,
covered: existingPost.covered,
usersAppliedTo: existingPost.usersAppliedTo,
});
return newPost;
} catch (e) {
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
updateStatus: procedure
.input(
z.object({
_id: zodOidType,
})
)
.mutation(async ({ input }) => {
try {
await updatePostStatus(input._id);
return { success: true };
} catch (e) {
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
editDraftPost: procedure
.input(
z.object({
_id: zodOidType,
updateFields: draftPostSchema,
})
)
.mutation(async ({ input }) => {
try {
const existingPost = await getPost(input._id, false);
if (!existingPost) {
throw new Error("Unable to find existing post id.");
}
const newPost = await createDraftPost({
...input.updateFields,
date: existingPost.date,
covered: existingPost.covered,
usersAppliedTo: existingPost.usersAppliedTo,
});
return newPost;
} catch (e) {
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
getAllPosts: procedure.query(async () => {
try {
return await getAllPosts();
} catch (e) {
throw new TRPCError({
message: "Internal Server Error",
code: "INTERNAL_SERVER_ERROR",
cause: e,
});
}
}),
getAttachments: procedure
.input(
z.object({
_id: zodOidType,
})
)
.query(async ({ input }) => {
try {
return getAttachments(input._id);
} catch (e) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "An unexpected error occurred",
cause: e,
});
}
}),
getFilteredPosts: procedure
.input(
z.object({
postFilters: postFilterSchema,
covered: z.optional(z.boolean()),
draft: z.optional(z.boolean()),
})
)
.query(async ({ input, ctx }) => {
const postFilters = input.postFilters;
const notAllowedBehavioral = Object.values(Behavioral).filter(
(obj) => !postFilters.behavioral.includes(obj)
);
/**
* Go through each value in GoodWith enum.
* If the value should be filtered as yes, get the specific key from the goodWithMap and set the filter array to only yes.
* Otherwise we don't need to filter by that enum value and can set the filter array to yes, no and unknown.
*/
const getsAlongWith: Record<string, Trained> = Object.values(
GoodWith
).reduce((acc, curr) => {
if (postFilters.goodWith.includes(curr)) {
return { ...acc, ...{ [goodWithMap[curr]]: [Trained.Yes] } };
} else {
return {
...acc,
...{
[goodWithMap[curr]]: [Trained.Yes, Trained.No, Trained.Unknown],
},
};
}
}, {});
const baseFilter: FilterQuery<IPost | IDraftPost> = {
$or: [{ breed: { $in: postFilters.breed } }, { breed: { $size: 0 } }],
type: { $in: [...postFilters.type, null] },
age: { $in: [...postFilters.age, null] },
size: { $in: [...postFilters.size, null] },
gender: { $in: [...postFilters.gender, null] },
behavioral: { $nin: notAllowedBehavioral },
getsAlongWithCats: { $in: getsAlongWith["getsAlongWithCats"] },
getsAlongWithLargeDogs: {
$in: getsAlongWith["getsAlongWithLargeDogs"],
},
getsAlongWithMen: { $in: getsAlongWith["getsAlongWithMen"] },
getsAlongWithOlderKids: {
$in: getsAlongWith["getsAlongWithOlderKids"],
},
getsAlongWithSmallDogs: {
$in: getsAlongWith["getsAlongWithSmallDogs"],
},
getsAlongWithWomen: { $in: getsAlongWith["getsAlongWithWomen"] },
getsAlongWithYoungKids: {
$in: getsAlongWith["getsAlongWithYoungKids"],
},
pending: false,
};
if (input.covered !== undefined) {
baseFilter.covered = input.covered;
}
if (input.draft !== undefined) {
baseFilter.draft = input.draft;
}
try {
const filteredPosts = await getFilteredPosts(
baseFilter,
ctx.session.uid
);
return filteredPosts;
} catch (e) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "An unexpected error occurred.",
cause: e,
});
}
}),
});