All files / src/modules/social/services wishlist.service.ts

0% Statements 0/160
0% Branches 0/44
0% Functions 0/22
0% Lines 0/146

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 440 441 442 443 444 445 446 447 448 449 450 451                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { SharedWishlist, SharedWishlistDocument } from '../../../database/schemas/shared-wishlist.schema';
import { Product, ProductDocument } from '../../../database/schemas/product.schema';
import { User, UserDocument } from '../../../database/schemas/user.schema';
 
@Injectable()
export class WishlistService {
  private readonly logger = new Logger(WishlistService.name);
 
  constructor(
    @InjectModel(SharedWishlist.name) private wishlistModel: Model<SharedWishlistDocument>,
    @InjectModel(Product.name) private productModel: Model<ProductDocument>,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
  ) {}
 
  async createWishlist(data: {
    title: string;
    description?: string;
    ownerId: string;
    occasion?: any;
    privacy?: string;
  }): Promise<SharedWishlistDocument> {
    try {
      const wishlist = new this.wishlistModel({
        title: data.title,
        description: data.description,
        ownerId: data.ownerId,
        occasion: data.occasion,
        privacy: data.privacy || 'private',
        participants: [{
          userId: data.ownerId,
          role: 'owner',
          joinedAt: new Date(),
          permissions: {
            canAdd: true,
            canRemove: true,
            canEdit: true,
            canInvite: true,
            canPurchase: true,
          },
          status: 'active',
        }],
        settings: {
          allowComments: true,
          allowVoting: true,
          allowSuggestions: true,
          requireApproval: false,
          autoRemovePurchased: false,
        },
        analytics: {
          totalItems: 0,
          purchasedItems: 0,
          totalValue: 0,
          purchasedValue: 0,
          averagePriority: 0,
          lastActivity: new Date(),
        },
        activityLog: [{
          userId: data.ownerId as any,
          action: 'wishlist_created',
          details: { title: data.title },
          timestamp: new Date(),
        }],
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date(),
      });
 
      await wishlist.save();
      
      this.logger.log(`Wishlist created: ${wishlist._id} by user ${data.ownerId}`);
      return wishlist;
    } catch (error) {
      this.logger.error(`Error creating wishlist for user ${data.ownerId}`, error);
      throw error;
    }
  }
 
  async addProductToWishlist(
    wishlistId: string,
    productId: string,
    userId: string,
    options: {
      priority?: number;
      notes?: string;
      variants?: {
        size?: string;
        color?: string;
        sku?: string;
      };
    } = {}
  ): Promise<boolean> {
    try {
      const wishlist = await this.wishlistModel.findById(wishlistId);
      Iif (!wishlist) {
        throw new Error('Wishlist not found');
      }
 
      // Check if user has permission to add items
      const participant = wishlist.participants.find(p => p.userId.toString() === userId);
      Iif (!participant || !participant.permissions.canAdd) {
        throw new Error('No permission to add items to this wishlist');
      }
 
      // Check if product already exists in wishlist
      const existingProduct = wishlist.products.find(p => p.productId.toString() === productId);
      Iif (existingProduct) {
        throw new Error('Product already in wishlist');
      }
 
      // Get product details for analytics
      const product = await this.productModel.findById(productId);
      Iif (!product) {
        throw new Error('Product not found');
      }
 
      // Add product to wishlist
      wishlist.products.push({
        productId: productId as any,
        addedBy: userId as any,
        addedAt: new Date(),
        priority: options.priority || 3,
        notes: options.notes,
        purchased: false,
        variants: options.variants,
        votes: [],
      });
 
      // Update analytics
      wishlist.analytics.totalItems = wishlist.products.length;
      wishlist.analytics.totalValue += product.variants[0]?.price?.current || 0;
      wishlist.analytics.averagePriority = wishlist.products.reduce((sum, p) => sum + p.priority, 0) / wishlist.products.length;
      wishlist.analytics.lastActivity = new Date();
 
      // Add to activity log
      wishlist.activityLog.push({
        userId: userId as any,
        action: 'added_item',
        details: {
          productId,
          productTitle: product.title,
          priority: options.priority || 3,
        },
        timestamp: new Date(),
      });
 
      wishlist.updatedAt = new Date();
      await wishlist.save();
 
      this.logger.log(`Product ${productId} added to wishlist ${wishlistId} by user ${userId}`);
      return true;
    } catch (error) {
      this.logger.error(`Error adding product ${productId} to wishlist ${wishlistId}`, error);
      throw error;
    }
  }
 
  async removeProductFromWishlist(wishlistId: string, productId: string, userId: string): Promise<boolean> {
    try {
      const wishlist = await this.wishlistModel.findById(wishlistId);
      Iif (!wishlist) {
        throw new Error('Wishlist not found');
      }
 
      // Check if user has permission to remove items
      const participant = wishlist.participants.find(p => p.userId.toString() === userId);
      Iif (!participant || !participant.permissions.canRemove) {
        throw new Error('No permission to remove items from this wishlist');
      }
 
      // Find and remove the product
      const productIndex = wishlist.products.findIndex(p => p.productId.toString() === productId);
      Iif (productIndex === -1) {
        throw new Error('Product not found in wishlist');
      }
 
      const removedProduct = wishlist.products[productIndex];
      wishlist.products.splice(productIndex, 1);
 
      // Update analytics
      wishlist.analytics.totalItems = wishlist.products.length;
      if (wishlist.products.length > 0) {
        wishlist.analytics.averagePriority = wishlist.products.reduce((sum, p) => sum + p.priority, 0) / wishlist.products.length;
      } else {
        wishlist.analytics.averagePriority = 0;
      }
      wishlist.analytics.lastActivity = new Date();
 
      // Add to activity log
      wishlist.activityLog.push({
        userId: userId as any,
        action: 'removed_item',
        details: {
          productId,
        },
        timestamp: new Date(),
      });
 
      wishlist.updatedAt = new Date();
      await wishlist.save();
 
      this.logger.log(`Product ${productId} removed from wishlist ${wishlistId} by user ${userId}`);
      return true;
    } catch (error) {
      this.logger.error(`Error removing product ${productId} from wishlist ${wishlistId}`, error);
      throw error;
    }
  }
 
  async inviteToWishlist(wishlistId: string, inviterId: string, inviteeId: string, role: string = 'viewer'): Promise<boolean> {
    try {
      const wishlist = await this.wishlistModel.findById(wishlistId);
      Iif (!wishlist) {
        throw new Error('Wishlist not found');
      }
 
      // Check if inviter has permission to invite
      const inviter = wishlist.participants.find(p => p.userId.toString() === inviterId);
      Iif (!inviter || !inviter.permissions.canInvite) {
        throw new Error('No permission to invite users to this wishlist');
      }
 
      // Check if user is already a participant
      const existingParticipant = wishlist.participants.find(p => p.userId.toString() === inviteeId);
      Iif (existingParticipant) {
        throw new Error('User is already a participant');
      }
 
      // Add participant
      const permissions = this.getPermissionsByRole(role);
      wishlist.participants.push({
        userId: inviteeId as any,
        role,
        joinedAt: new Date(),
        permissions,
        invitedBy: inviterId as any,
        status: 'invited',
      });
 
      // Add to activity log
      wishlist.activityLog.push({
        userId: inviterId as any,
        action: 'invited_user',
        details: {
          inviteeId,
          role,
        },
        timestamp: new Date(),
      });
 
      wishlist.updatedAt = new Date();
      await wishlist.save();
 
      this.logger.log(`User ${inviteeId} invited to wishlist ${wishlistId} by ${inviterId}`);
      return true;
    } catch (error) {
      this.logger.error(`Error inviting user ${inviteeId} to wishlist ${wishlistId}`, error);
      throw error;
    }
  }
 
  async acceptWishlistInvitation(wishlistId: string, userId: string): Promise<boolean> {
    try {
      const wishlist = await this.wishlistModel.findById(wishlistId);
      Iif (!wishlist) {
        throw new Error('Wishlist not found');
      }
 
      const participant = wishlist.participants.find(p => p.userId.toString() === userId && p.status === 'invited');
      Iif (!participant) {
        throw new Error('Invitation not found');
      }
 
      participant.status = 'active';
      participant.joinedAt = new Date();
 
      // Add to activity log
      wishlist.activityLog.push({
        userId: userId as any,
        action: 'joined_wishlist',
        details: {},
        timestamp: new Date(),
      });
 
      wishlist.updatedAt = new Date();
      await wishlist.save();
 
      this.logger.log(`User ${userId} accepted invitation to wishlist ${wishlistId}`);
      return true;
    } catch (error) {
      this.logger.error(`Error accepting wishlist invitation for user ${userId}`, error);
      throw error;
    }
  }
 
  async markProductAsPurchased(
    wishlistId: string,
    productId: string,
    userId: string,
    purchaseDetails: {
      price?: number;
      url?: string;
    } = {}
  ): Promise<boolean> {
    try {
      const wishlist = await this.wishlistModel.findById(wishlistId);
      Iif (!wishlist) {
        throw new Error('Wishlist not found');
      }
 
      const product = wishlist.products.find(p => p.productId.toString() === productId);
      Iif (!product) {
        throw new Error('Product not found in wishlist');
      }
 
      Iif (product.purchased) {
        throw new Error('Product already marked as purchased');
      }
 
      product.purchased = true;
      product.purchasedBy = userId as any;
      product.purchasedAt = new Date();
      product.purchasePrice = purchaseDetails.price;
      product.purchaseUrl = purchaseDetails.url;
 
      // Update analytics
      wishlist.analytics.purchasedItems += 1;
      Iif (purchaseDetails.price) {
        wishlist.analytics.purchasedValue += purchaseDetails.price;
      }
      wishlist.analytics.lastActivity = new Date();
 
      // Add to activity log
      wishlist.activityLog.push({
        userId: userId as any,
        action: 'purchased_item',
        details: {
          productId,
          price: purchaseDetails.price,
        },
        timestamp: new Date(),
      });
 
      // Auto-remove if setting is enabled
      Iif (wishlist.settings.autoRemovePurchased) {
        const productIndex = wishlist.products.findIndex(p => p.productId.toString() === productId);
        Iif (productIndex !== -1) {
          wishlist.products.splice(productIndex, 1);
          wishlist.analytics.totalItems = wishlist.products.length;
        }
      }
 
      wishlist.updatedAt = new Date();
      await wishlist.save();
 
      this.logger.log(`Product ${productId} marked as purchased in wishlist ${wishlistId} by user ${userId}`);
      return true;
    } catch (error) {
      this.logger.error(`Error marking product ${productId} as purchased in wishlist ${wishlistId}`, error);
      throw error;
    }
  }
 
  async getUserWishlists(userId: string): Promise<SharedWishlistDocument[]> {
    try {
      const wishlists = await this.wishlistModel
        .find({
          'participants.userId': userId,
          'participants.status': { $in: ['active', 'invited'] },
          isActive: true,
        })
        .populate('ownerId', 'profile.firstName profile.lastName profile.avatar')
        .sort({ updatedAt: -1 });
 
      return wishlists;
    } catch (error) {
      this.logger.error(`Error getting wishlists for user ${userId}`, error);
      throw error;
    }
  }
 
  async getPopularWishlists(limit: number = 10): Promise<Array<{
    wishlistId: string;
    title: string;
    owner: string;
    items: number;
    privacy: string;
  }>> {
    try {
      const wishlists = await this.wishlistModel
        .find({
          privacy: 'public',
          isActive: true,
          'analytics.totalItems': { $gt: 0 },
        })
        .populate('ownerId', 'profile.firstName profile.lastName')
        .sort({ 'analytics.lastActivity': -1, 'participants.length': -1 })
        .limit(limit);
 
      return wishlists.map(wishlist => ({
        wishlistId: wishlist._id.toString(),
        title: wishlist.title,
        owner: `${(wishlist.ownerId as any).profile.firstName} ${(wishlist.ownerId as any).profile.lastName}`,
        items: wishlist.analytics.totalItems,
        privacy: wishlist.privacy,
      }));
    } catch (error) {
      this.logger.error('Error getting popular wishlists', error);
      return [];
    }
  }
 
  private getPermissionsByRole(role: string): {
    canAdd: boolean;
    canRemove: boolean;
    canEdit: boolean;
    canInvite: boolean;
    canPurchase: boolean;
  } {
    switch (role) {
      case 'owner':
        return {
          canAdd: true,
          canRemove: true,
          canEdit: true,
          canInvite: true,
          canPurchase: true,
        };
      case 'editor':
        return {
          canAdd: true,
          canRemove: true,
          canEdit: true,
          canInvite: false,
          canPurchase: true,
        };
      case 'viewer':
      default:
        return {
          canAdd: false,
          canRemove: false,
          canEdit: false,
          canInvite: false,
          canPurchase: true,
        };
    }
  }
}