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 | /** * Notification Service * * Server-side service for creating and managing notifications. * Handles notification preferences and real-time delivery. */ import { prisma } from '@/lib/prisma'; import type { CreateNotificationParams, NotificationType } from './types'; /** * Check if a notification type is enabled for a user */ async function isNotificationEnabled( userId: number, type: NotificationType ): Promise<boolean> { const preferences = await prisma.notificationPreference.findUnique({ where: { userId }, }); // Default to enabled if no preferences set if (!preferences) { return true; } switch (type) { case 'ORDER_UPDATE': return preferences.orders; case 'PROMOTION': case 'PRICE_DROP': return preferences.promotions; case 'BACK_IN_STOCK': return preferences.stock; case 'REVIEW_RESPONSE': return preferences.reviews; case 'SUPPORT_RESPONSE': case 'SYSTEM': return true; // Always enabled default: return true; } } /** * Create a notification for a user * * @example * ```typescript * await createNotification({ * userId: 1, * type: 'ORDER_UPDATE', * title: 'Order Shipped', * message: 'Your order #123 has been shipped', * link: '/account/orders/123', * }); * ``` */ export async function createNotification( params: CreateNotificationParams ): Promise<{ id: string } | null> { const { userId, type, title, message, link } = params; // Check if this notification type is enabled for the user const isEnabled = await isNotificationEnabled(userId, type); if (!isEnabled) { return null; } // Create notification in database const notification = await prisma.notification.create({ data: { userId, type, title, message, link, }, }); return { id: notification.id }; } /** * Mark a notification as read */ export async function markNotificationRead( userId: number, notificationId: string ): Promise<boolean> { const result = await prisma.notification.updateMany({ where: { id: notificationId, userId, }, data: { read: true, }, }); return result.count > 0; } /** * Mark all notifications as read for a user */ export async function markAllNotificationsRead(userId: number): Promise<number> { const result = await prisma.notification.updateMany({ where: { userId, read: false, }, data: { read: true, }, }); return result.count; } /** * Get unread notification count for a user */ export async function getUnreadCount(userId: number): Promise<number> { return prisma.notification.count({ where: { userId, read: false, }, }); } /** * Delete old read notifications (cleanup) */ export async function cleanupOldNotifications( olderThanDays: number = 30 ): Promise<number> { const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - olderThanDays); const result = await prisma.notification.deleteMany({ where: { read: true, createdAt: { lt: cutoffDate, }, }, }); return result.count; } // Convenience functions for common notification types /** * Notify user of order status change */ export async function notifyOrderStatusChange( userId: number, orderId: number | string, status: string, orderNumber?: string ): Promise<{ id: string } | null> { const statusMessages: Record<string, { title: string; message: string }> = { PENDING: { title: 'Order Received', message: `Your order ${orderNumber ? `#${orderNumber}` : ''} has been received and is being processed.`, }, PROCESSING: { title: 'Order Processing', message: `Your order ${orderNumber ? `#${orderNumber}` : ''} is being prepared.`, }, SHIPPED: { title: 'Order Shipped', message: `Great news! Your order ${orderNumber ? `#${orderNumber}` : ''} has been shipped.`, }, DELIVERED: { title: 'Order Delivered', message: `Your order ${orderNumber ? `#${orderNumber}` : ''} has been delivered. Enjoy!`, }, CANCELLED: { title: 'Order Cancelled', message: `Your order ${orderNumber ? `#${orderNumber}` : ''} has been cancelled.`, }, REFUNDED: { title: 'Refund Processed', message: `Your refund for order ${orderNumber ? `#${orderNumber}` : ''} has been processed.`, }, }; const messageData = statusMessages[status] || { title: 'Order Update', message: `Your order status has been updated to ${status}.`, }; return createNotification({ userId, type: 'ORDER_UPDATE', title: messageData.title, message: messageData.message, link: `/account/orders/${orderId}`, metadata: { orderId, status, orderNumber }, }); } /** * Notify user of a price drop on a wishlist item */ export async function notifyPriceDrop( userId: number, productId: number, productName: string, oldPrice: number, newPrice: number ): Promise<{ id: string } | null> { const percentOff = Math.round(((oldPrice - newPrice) / oldPrice) * 100); return createNotification({ userId, type: 'PRICE_DROP', title: 'Price Drop Alert!', message: `${productName} is now ${percentOff}% off! Was $${oldPrice.toFixed(2)}, now $${newPrice.toFixed(2)}.`, link: `/product/${productId}`, metadata: { productId, oldPrice, newPrice, percentOff }, }); } /** * Notify user when a wishlist item is back in stock */ export async function notifyBackInStock( userId: number, productId: number, productName: string ): Promise<{ id: string } | null> { return createNotification({ userId, type: 'BACK_IN_STOCK', title: 'Back in Stock!', message: `${productName} is now available. Get it before it sells out again!`, link: `/product/${productId}`, metadata: { productId }, }); } /** * Notify user of a support ticket response */ export async function notifySupportResponse( userId: number, ticketId: string, ticketSubject: string ): Promise<{ id: string } | null> { return createNotification({ userId, type: 'SUPPORT_RESPONSE', title: 'Support Response', message: `You have a new response to your ticket: "${ticketSubject}"`, link: `/support/tickets/${ticketId}`, metadata: { ticketId, ticketSubject }, }); } /** * Notify user of a review response */ export async function notifyReviewResponse( userId: number, productId: number, productName: string ): Promise<{ id: string } | null> { return createNotification({ userId, type: 'REVIEW_RESPONSE', title: 'Review Response', message: `The seller responded to your review on ${productName}.`, link: `/product/${productId}#reviews`, metadata: { productId }, }); } /** * Send a promotion notification to a user */ export async function notifyPromotion( userId: number, promoTitle: string, promoMessage: string, promoLink?: string ): Promise<{ id: string } | null> { return createNotification({ userId, type: 'PROMOTION', title: promoTitle, message: promoMessage, link: promoLink || '/promotions', }); } |