-
Notifications
You must be signed in to change notification settings - Fork 0
/
coupons.js
331 lines (331 loc) · 15.5 KB
/
coupons.js
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
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CouponRoutes = exports.couponIsExpired = void 0;
const shared_1 = require("./shared");
const zod_1 = require("zod");
const couponIsExpired = (date) => {
if (!date) {
// throw Error("invalid date");
return false;
}
//prisma likes to return the date as a string :(
return new Date().getTime() > new Date(date).getTime();
};
exports.couponIsExpired = couponIsExpired;
const getDefaultCouponGroupName = (listingForCoupon) => {
if (!listingForCoupon) {
return "";
}
// alright so if a coupon doesn't have a group name explicitly given then assign it
// the display title and id
// listing can only have one default coupon
return `${listingForCoupon === null || listingForCoupon === void 0 ? void 0 : listingForCoupon.name}`;
};
const CouponRoutes = (prisma, publicProcedure) => {
if (!publicProcedure) {
throw Error("public Procedure not found");
}
const create = publicProcedure
.input((payload) => __awaiter(void 0, void 0, void 0, function* () {
const parsedPayload = shared_1.createCouponSchema.parse(payload); //validate the incoming object
const listingAlreadyHasCoupon = !!(yield prisma.coupon.findFirst({
where: { listingId: parsedPayload.listingId },
}));
const admin = yield prisma.user
.findUnique({
where: { email: parsedPayload.email },
})
.then((user) => (user === null || user === void 0 ? void 0 : user.role) === "ADMIN");
if (listingAlreadyHasCoupon && !admin) {
throw Error("Listing already has coupon and User do not have admin permissions ");
}
return parsedPayload;
}))
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const expirationDate = new Date(input.expirationDate).toISOString();
const listingForCoupon = yield prisma.listing.findUnique({
where: { id: input.listingId },
});
if (listingForCoupon === null) {
throw Error("can't find listing");
}
if (!input.groupName) {
input.groupName = getDefaultCouponGroupName(listingForCoupon);
}
const coupon = yield prisma.coupon.create({
data: Object.assign(Object.assign({}, input), { expirationDate }),
});
// return coupon;
}));
const getByUnique = publicProcedure
.input((payload) => {
const parsedName = shared_1.getCouponSchema.parse(payload); //validate the incoming object
return parsedName;
})
.query(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const coupon = yield prisma.coupon.findUnique({ where: { name: input } });
if (coupon === null) {
throw Error("No coupon found");
}
return coupon;
}));
const getAll = publicProcedure
.input((email) => {
const parsedPayload = shared_1.getAllCouponsSchema.parse(email);
return parsedPayload;
})
.query(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
if (input) {
const coupons = yield prisma.coupon.findMany({
where: { email: input },
});
return coupons;
}
else {
const coupons = yield prisma.coupon.findMany({});
return coupons;
}
}));
const update = publicProcedure
.input((payload) => {
const parsedPayload = shared_1.updateCouponSchema.parse(payload); //validate the incoming object
return parsedPayload;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const { groupName } = input, i = __rest(input, ["groupName"]);
const coupon = yield prisma.coupon.update({
where: { id: input.id },
data: Object.assign({}, input),
});
return coupon;
}));
const remove = publicProcedure
.input((payload) => {
const parsedName = shared_1.couponIdSchema.parse(payload);
return parsedName;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const removedCoupon = yield prisma.coupon.delete({
where: { id: input.id },
});
yield prisma.couponsForUser.deleteMany({ where: { couponId: removedCoupon.id } });
return removedCoupon.id;
}));
const couponUse = publicProcedure
.input((payload) => {
const parsedName = shared_1.useCouponSchema.parse(payload);
return parsedName;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const user = yield prisma.user.findUnique({
where: { email: input.email },
});
if ((user === null || user === void 0 ? void 0 : user.id) && input.email) {
const couponExistsForUser = yield prisma.couponsForUser.findFirst({
where: {
AND: {
couponId: input.couponId,
userEmail: input.email,
},
},
});
if (!couponExistsForUser) {
// if the coupon does not exist for a user it may be the listing coupon
const isCouponForListing = yield prisma.coupon
.findUnique({
where: { id: input.couponId },
})
.then((coupon) => __awaiter(void 0, void 0, void 0, function* () {
var _a;
const listing = yield prisma.listing.findUnique({
where: { id: (_a = coupon === null || coupon === void 0 ? void 0 : coupon.listingId) !== null && _a !== void 0 ? _a : -1 },
});
return { coupon, listing };
}))
.then(({ listing, coupon }) => getDefaultCouponGroupName(listing) === (coupon === null || coupon === void 0 ? void 0 : coupon.groupName));
if (isCouponForListing) {
// if it is the coupon for listing adding it as a coupon for the user. this way we can track that they used it
const response = yield prisma.couponsForUser.create({
data: { couponId: input.couponId, used: true, userEmail: input.email },
});
return response;
}
else {
throw Error("Coupon does not exist for user and coupon is not for listing");
}
}
const response = yield prisma.couponsForUser.update({
where: { id: couponExistsForUser === null || couponExistsForUser === void 0 ? void 0 : couponExistsForUser.id },
data: { used: true },
});
return response;
}
}));
const addCouponForUserByGroup = publicProcedure
.input((payload) => __awaiter(void 0, void 0, void 0, function* () {
const parsedPayload = shared_1.addCouponForUserByGroupSchema.parse(payload); //passed in the correct info
const group = yield prisma.groups.findUnique({
where: { groupName: parsedPayload.groupName },
});
if ((group === null || group === void 0 ? void 0 : group.activationCode) === "NotRequired" ||
(group === null || group === void 0 ? void 0 : group.activationCode) === "Not Required" || // no code required
(group === null || group === void 0 ? void 0 : group.activationCode) === parsedPayload.code // code required
) {
return parsedPayload;
}
else {
throw Error("invalid code");
}
//time to verify the code
}))
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
// first find all of the coupons
const coupons = yield prisma.coupon.findMany({
where: { groupName: input.groupName },
});
// now grab all the existing coupons that a user has access to
const usersExistingCouponIds = yield prisma.couponsForUser
.findMany({
where: { userEmail: input.userEmail },
})
.then((userCoupons) => userCoupons.map((c) => c.couponId));
// we only want to add coupons the user hasn't used
const couponsPromises = coupons
.filter((c) => {
return !usersExistingCouponIds.includes(c.id);
})
// create an array promise
.map((c) => {
return prisma.couponsForUser.create({
data: {
couponId: c.id,
used: false,
userEmail: input.userEmail,
},
});
});
// add all coupons that the user is elidible for
return yield Promise.all(couponsPromises);
}));
const hasCouponBeenUsed = publicProcedure
.input((payload) => {
const parsedPayload = zod_1.z.object({ couponId: zod_1.z.number() }).parse(payload); //validate the incoming object
return parsedPayload;
})
.query(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
var _b;
const coupon = yield prisma.couponsForUser.findFirst({
where: { couponId: input.couponId },
});
return (_b = coupon === null || coupon === void 0 ? void 0 : coupon.used) !== null && _b !== void 0 ? _b : false;
}));
const getCouponsValidity = (selectedCoupon, couponsForUser, listings) => __awaiter(void 0, void 0, void 0, function* () {
var _c;
let couponUsedState = "INVALID";
const listing = listings.find((l) => { var _a; return (_a = l.id === (selectedCoupon === null || selectedCoupon === void 0 ? void 0 : selectedCoupon.listingId)) !== null && _a !== void 0 ? _a : ""; });
const groupExists = yield prisma.groups
.findUnique({ where: { groupName: (_c = selectedCoupon === null || selectedCoupon === void 0 ? void 0 : selectedCoupon.groupName) !== null && _c !== void 0 ? _c : "" } })
.then((g) => !!g);
const couponAvailableToUser = couponsForUser.find((c) => c.couponId === selectedCoupon.id);
if (couponAvailableToUser === undefined && selectedCoupon.groupName !== (listing === null || listing === void 0 ? void 0 : listing.name)) {
// needs to enroll in group
couponUsedState = "NEEDS_GROUP";
}
else if (couponAvailableToUser === null || couponAvailableToUser === void 0 ? void 0 : couponAvailableToUser.used)
couponUsedState = "USED";
else if ((0, exports.couponIsExpired)(selectedCoupon === null || selectedCoupon === void 0 ? void 0 : selectedCoupon.expirationDate))
couponUsedState = "EXPIRED";
else if (getDefaultCouponGroupName(listing) === (selectedCoupon === null || selectedCoupon === void 0 ? void 0 : selectedCoupon.groupName) || groupExists) {
couponUsedState = "VALID";
}
return { couponId: selectedCoupon.id, couponUsedState };
});
const getUserCouponRelation = publicProcedure
.input((payload) => {
const parsedPayload = shared_1.GetCouponForUserBySchema.parse(payload); //validate the incoming object
return parsedPayload;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const couponResponse = yield prisma.couponsForUser
.findMany({
where: { userEmail: input.userEmail },
})
.then((couponsAvailableToUser) => __awaiter(void 0, void 0, void 0, function* () {
const usersCoupons = yield prisma.coupon.findMany({
where: { id: { in: couponsAvailableToUser.map((cIds) => cIds.couponId) } },
});
const listings = yield prisma.listing.findMany({
where: { id: { in: usersCoupons.map((c) => { var _a; return (_a = c.listingId) !== null && _a !== void 0 ? _a : -1; }) } },
});
const couponsValidity = yield Promise.all(usersCoupons.map((c) => getCouponsValidity(c, couponsAvailableToUser, listings)));
return { usersCoupons, couponsAvailableToUser, listings, couponsValidity };
}));
return couponResponse;
}));
const getCouponsForListing = publicProcedure
.input((payload) => {
const parsedPayload = zod_1.z.object({ listingId: zod_1.z.number(), userEmail: zod_1.z.string().email() }).parse(payload); //validate the incoming object
return parsedPayload;
})
.query(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const couponsForListing = yield prisma.coupon.findMany({ where: { listingId: input.listingId } });
const listings = yield prisma.listing.findMany({ where: { id: input.listingId } });
const couponsForUser = yield prisma.couponsForUser.findMany({ where: { userEmail: input.userEmail } });
const couponAvailability = yield Promise.all(couponsForListing.map((c) => getCouponsValidity(c, couponsForUser, listings)));
return { couponsForListing, couponAvailability };
}));
const getCouponsForGroup = publicProcedure
.input((payload) => {
const parsedPayload = zod_1.z.object({ groupName: zod_1.z.string().min(1) }).parse(payload);
return parsedPayload;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const couponsByGroup = yield prisma.coupon.findMany({ where: { groupName: input.groupName } });
return couponsByGroup;
}));
const getListingForCoupon = publicProcedure
.input((payload) => {
const parsedPayload = zod_1.z.object({ listingId: zod_1.z.number() }).parse(payload);
return parsedPayload;
})
.mutation(({ input }) => __awaiter(void 0, void 0, void 0, function* () {
const listingForCoupon = yield prisma.listing.findUnique({ where: { id: input.listingId } });
return listingForCoupon;
}));
const couponRoutes = {
couponCreate: create,
couponGetByUnique: getByUnique,
couponUpdate: update,
couponRemove: remove,
couponGetAll: getAll,
couponUse,
addCouponForUserByGroup,
hasCouponBeenUsed,
getUserCouponRelation,
getCouponsForListing,
getCouponsForGroup,
getListingForCoupon,
};
return couponRoutes;
};
exports.CouponRoutes = CouponRoutes;