Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 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x 7x 7x 7x 7x 8x 1x 1x 6x 6x 6x 10x 10x 10x 10x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 2x 2x 4x 4x 4x 2x 2x 2x | /**
* Notification System Utilities
* Handles in-app notifications, email, SMS
*/
import { prisma } from './prisma';
export type NotificationType = "order" | "review" | "stock" | "promo" | "shipping";
export interface Notification {
id: string;
userId: number;
type: NotificationType;
title: string;
message: string;
link?: string;
read: boolean;
createdAt: Date;
}
export interface NotificationPreferences {
email: boolean;
push: boolean;
sms: boolean;
orders: boolean;
reviews: boolean;
stock: boolean;
promotions: boolean;
}
/**
* Create a new notification
*/
export async function createNotification(
userId: number,
type: NotificationType,
title: string,
message: string,
link?: string
): Promise<Notification> {
const notification = await prisma.notification.create({
data: {
userId,
type,
title,
message,
link}});
return {
id: notification.id,
userId: notification.userId,
type: notification.type as NotificationType,
title: notification.title,
message: notification.message,
link: notification.link || undefined,
read: notification.read,
createdAt: notification.createdAt};
}
/**
* Get user notifications with pagination
*/
export async function getUserNotifications(
userId: number,
options: { page?: number; limit?: number; unreadOnly?: boolean } = {}
): Promise<{
notifications: Notification[];
pagination: { page: number; limit: number; total: number; pages: number };
unreadCount: number;
}> {
const page = options.page || 1;
const limit = options.limit || 20;
const skip = (page - 1) * limit;
const where = {
userId,
...(options.unreadOnly ? { read: false } : {})};
const [notifications, total, unreadCount] = await Promise.all([
prisma.notification.findMany({
where,
orderBy: { createdAt: 'desc' },
skip,
take: limit}),
prisma.notification.count({ where }),
prisma.notification.count({ where: { userId, read: false } }),
]);
return {
notifications: notifications.map((n) => ({
id: n.id,
userId: n.userId,
type: n.type as NotificationType,
title: n.title,
message: n.message,
link: n.link || undefined,
read: n.read,
createdAt: n.createdAt})),
pagination: {
page,
limit,
total,
pages: Math.ceil(total / limit)},
unreadCount};
}
/**
* Mark a notification as read
*/
export async function markNotificationAsRead(notificationId: string): Promise<Notification> {
const notification = await prisma.notification.update({
where: { id: notificationId },
data: { read: true }});
return {
id: notification.id,
userId: notification.userId,
type: notification.type as NotificationType,
title: notification.title,
message: notification.message,
link: notification.link || undefined,
read: notification.read,
createdAt: notification.createdAt};
}
/**
* Mark all user notifications as read
*/
export async function markAllNotificationsAsRead(userId: number): Promise<{ count: number }> {
const result = await prisma.notification.updateMany({
where: { userId, read: false },
data: { read: true }});
return { count: result.count };
}
/**
* Delete a notification
*/
export async function deleteNotification(notificationId: string): Promise<void> {
await prisma.notification.delete({
where: { id: notificationId }});
}
/**
* Get user notification preferences
*/
export async function getNotificationPreferences(
userId: number
): Promise<NotificationPreferences> {
let preferences = await prisma.notificationPreference.findUnique({
where: { userId }});
// Create default preferences if they don't exist
if (!preferences) {
preferences = await prisma.notificationPreference.create({
data: { userId }});
}
return {
email: preferences.email,
push: preferences.push,
sms: preferences.sms,
orders: preferences.orders,
reviews: preferences.reviews,
stock: preferences.stock,
promotions: preferences.promotions};
}
/**
* Update user notification preferences
*/
export async function updateNotificationPreferences(
userId: number,
preferences: Partial<NotificationPreferences>
): Promise<NotificationPreferences> {
const updated = await prisma.notificationPreference.upsert({
where: { userId },
update: preferences,
create: {
userId,
...preferences}});
return {
email: updated.email,
push: updated.push,
sms: updated.sms,
orders: updated.orders,
reviews: updated.reviews,
stock: updated.stock,
promotions: updated.promotions};
}
/**
* Send order status notification
*/
export async function sendOrderNotification(
userId: number,
orderId: number,
status: string
): Promise<Notification> {
// Check user preferences
const prefs = await getNotificationPreferences(userId);
if (!prefs.orders) {
// User has disabled order notifications, but we still create the in-app notification
// We just won't send email/SMS
}
const statusMessages: Record<string, { title: string; message: string }> = {
PROCESSING: {
title: 'Order Confirmed',
message: `Your order #${orderId} has been confirmed and is being processed.`},
SHIPPED: {
title: 'Order Shipped',
message: `Your order #${orderId} has been shipped and is on the way!`},
DELIVERED: {
title: 'Order Delivered',
message: `Your order #${orderId} has been delivered. Enjoy!`},
CANCELLED: {
title: 'Order Cancelled',
message: `Your order #${orderId} has been cancelled.`}};
const { title, message } = statusMessages[status] || {
title: 'Order Update',
message: `Your order #${orderId} status has been updated to ${status}.`};
return createNotification(
userId,
'order',
title,
message,
`/order-confirmation/${orderId}`
);
}
/**
* Send review request notification
*/
export async function sendReviewRequestNotification(
userId: number,
orderId: number
): Promise<Notification> {
const prefs = await getNotificationPreferences(userId);
if (!prefs.reviews) {
throw new Error('User has disabled review notifications');
}
return createNotification(
userId,
'review',
'Review Your Order',
`How was your recent order? Share your experience with us!`,
`/my-account?tab=orders&order=${orderId}`
);
}
/**
* Send back in stock notification
*/
export async function sendBackInStockNotification(
userId: number,
productId: number
): Promise<Notification> {
const prefs = await getNotificationPreferences(userId);
if (!prefs.stock) {
throw new Error('User has disabled stock notifications');
}
// Get product details
const product = await prisma.product.findUnique({
where: { id: productId },
select: { title: true }});
if (!product) {
throw new Error('Product not found');
}
return createNotification(
userId,
'stock',
'Back in Stock!',
`${product.title} is now back in stock. Get it before it's gone!`,
`/product/${productId}`
);
}
/**
* Send promotional notification
*/
export async function sendPromoNotification(
userId: number,
promoTitle: string,
promoMessage: string
): Promise<Notification> {
const prefs = await getNotificationPreferences(userId);
if (!prefs.promotions) {
throw new Error('User has disabled promotional notifications');
}
return createNotification(
userId,
'promo',
promoTitle,
promoMessage,
'/shop'
);
}
/**
* Get unread notification count
*/
export async function getUnreadCount(userId: number): Promise<number> {
return await prisma.notification.count({
where: {
userId,
read: false}});
}
/**
* Delete old read notifications (cleanup utility)
*/
export async function deleteOldNotifications(daysOld: number = 30): Promise<{ count: number }> {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysOld);
const result = await prisma.notification.deleteMany({
where: {
read: true,
createdAt: {
lt: cutoffDate}}});
return { count: result.count };
}
/**
* Bulk create notifications for multiple users
* Filters users based on their notification preferences
*/
export async function bulkCreateNotifications(
userIds: number[],
type: NotificationType,
title: string,
message: string,
link?: string
): Promise<{ count: number; skipped: number }> {
if (userIds.length === 0) {
return { count: 0, skipped: 0 };
}
// Get preferences and filter users based on notification type
const preferences = await prisma.notificationPreference.findMany({
where: {
userId: { in: userIds }},
select: {
userId: true,
email: true,
orders: true,
reviews: true,
stock: true,
promotions: true}});
// Map type to preference field
const typeToField: Record<NotificationType, keyof typeof preferences[0]> = {
order: 'orders',
review: 'reviews',
stock: 'stock',
promo: 'promotions',
shipping: 'orders', // shipping uses orders preference
};
const preferenceField = typeToField[type];
// Filter users who have this notification type enabled
const allowedUserIds = preferences
.filter((pref) => pref[preferenceField] === true)
.map((pref) => pref.userId);
// Include users without preferences (default: enabled)
const usersWithoutPrefs = userIds.filter(
(id) => !preferences.find((p) => p.userId === id)
);
const finalUserIds = [...allowedUserIds, ...usersWithoutPrefs];
if (finalUserIds.length === 0) {
return { count: 0, skipped: userIds.length };
}
const result = await prisma.notification.createMany({
data: finalUserIds.map((userId) => ({
userId,
type,
title,
message,
link}))});
return {
count: result.count,
skipped: userIds.length - result.count};
}
/**
* Notify users who wishlisted a product that it's back in stock
*/
export async function notifyWishlistUsersBackInStock(
productId: number
): Promise<{ notified: number }> {
// Get all users with this product in wishlist
const wishlistUsers = await prisma.wishlist.findMany({
where: { productId },
select: { userId: true }});
const userIds = wishlistUsers.map((w) => w.userId);
if (userIds.length === 0) {
return { notified: 0 };
}
// Filter users who have stock notifications enabled
const preferences = await prisma.notificationPreference.findMany({
where: {
userId: { in: userIds },
stock: true},
select: { userId: true }});
const notifyUserIds = preferences.map((p) => p.userId);
if (notifyUserIds.length === 0) {
return { notified: 0 };
}
// Send notifications to each user
for (const userId of notifyUserIds) {
await sendBackInStockNotification(userId, productId);
}
return { notified: notifyUserIds.length };
}
|