All files / src/modules/analytics analytics.service.ts

78.26% Statements 108/138
61.85% Branches 60/97
72% Functions 18/25
78.03% Lines 103/132

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 38414x 14x 14x 14x 14x     14x 18x     18x 18x 18x             21x 21x 21x     21x         21x 1x     20x   1x     19x     19x 19x 19x 19x       19x           19x           19x 19x   2x 2x                     1x 1x 1x     1x         1x       1x         1x     1x 1x 1x 1x       1x           1x           1x 1x                           12x 12x     12x         12x 1x       11x         11x 1x                 10x 10x 10x 10x 10x             10x 10x             10x           10x 10x 10x   10x                             10x 10x   2x 2x                                                             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 2x 2x 2x 2x 2x   2x     1x                         1x 1x                      
import { Injectable, Logger, NotFoundException, ForbiddenException, BadRequestException, Inject, Optional } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import Redis from 'ioredis';
import { withRetry } from '@app/common/utils/retry';
import { ResilienceMetricsService } from '@app/common/services/resilience-metrics.service';
 
@Injectable()
export class AnalyticsService {
  private readonly logger = new Logger(AnalyticsService.name);
 
  constructor(
    private prisma: PrismaService,
    @Inject('REDIS_CLIENT') private redis: Redis,
    @Optional() private readonly metrics?: ResilienceMetricsService,
  ) {}
 
  /**
   * Track a listing view
   */
  async trackView(listingId: number, source?: string, referrer?: string) {
    try {
      const refInfo = referrer ? `, referrer: ${referrer}` : '';
      this.logger.debug(`Tracking view for listing ${listingId} from source: ${source ?? 'unknown'}${refInfo}`);
 
      // Verify listing exists
      const listing = await this.prisma.client.listing.findUnique({
        where: { id: listingId },
        select: { id: true, deletedAt: true },
      });
 
      if (!listing) {
        throw new NotFoundException(`Listing #${listingId} not found`);
      }
 
      if (listing.deletedAt) {
        // Treat soft-deleted listings as not found to match test expectations
        throw new NotFoundException(`Listing #${listingId} not found`);
      }
 
      const date = new Date().toISOString().split('T')[0];
      
      // Increment Redis counters (guard against redis errors during tests)
      try {
        const stop = (this.metrics?.startTimer('redis', 'analytics_track_view') as (() => void)) || (() => {});
        await withRetry(async () => {
          await Promise.all([
            this.redis.incr(`analytics:listing:${listingId}:views:${date}`),
            this.redis.incr(`analytics:listing:${listingId}:views`),
          ]);
          await this.redis.expire(`analytics:listing:${listingId}:views:${date}`, 60 * 60 * 24 * 30);
        }, {
          tries: 3,
          baseDelayMs: 100,
          onAttempt: () => this.metrics?.recordRetry('redis', 'success'),
        });
        stop();
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        this.logger.warn(`Redis not available to track view for listing ${listingId}; continuing. Reason: ${reason}`);
      }
 
      this.logger.log(`Tracked view for listing ${listingId}`);
      return { success: true };
    } catch (error) {
      if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error tracking view for listing ${listingId}:`, error);
      throw new Error('Failed to track view');
    }
  }
 
  /**
   * Track a click (phone reveal, website click, etc.)
   */
  async trackClick(listingId: number, clickType: 'phone' | 'website' | 'email', userId?: number) {
    try {
      const userLabel = userId ? ` by user ${userId}` : '';
      this.logger.debug(`Tracking ${clickType} click for listing ${listingId}${userLabel}`);
 
      // Verify listing exists
      const listing = await this.prisma.client.listing.findUnique({
        where: { id: listingId },
        select: { id: true, deletedAt: true },
      });
 
      Iif (!listing) {
        throw new NotFoundException(`Listing #${listingId} not found`);
      }
 
      Iif (listing.deletedAt) {
        // Treat soft-deleted listings as not found to match test expectations
        throw new NotFoundException(`Listing #${listingId} not found`);
      }
 
      const date = new Date().toISOString().split('T')[0];
      
      // Increment Redis counters
      try {
        const stop = (this.metrics?.startTimer('redis', 'analytics_track_click') as (() => void)) || (() => {});
        await withRetry(async () => {
          await Promise.all([
            this.redis.incr(`listings:clicks:${clickType}:${listingId}:${date}`),
            this.redis.incr(`listings:clicks:${clickType}:${listingId}:total`),
          ]);
          await this.redis.expire(`listings:clicks:${clickType}:${listingId}:${date}`, 60 * 60 * 24 * 30);
        }, {
          tries: 3,
          baseDelayMs: 100,
          onAttempt: () => this.metrics?.recordRetry('redis', 'success'),
        });
        stop();
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        this.logger.warn(`Redis not available to track click for listing ${listingId}; continuing. Reason: ${reason}`);
      }
 
      this.logger.log(`Tracked ${clickType} click for listing ${listingId}`);
      return { success: true };
    } catch (error) {
      Iif (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error tracking click for listing ${listingId}:`, error);
      throw new Error('Failed to track click');
    }
  }
 
  /**
   * Get analytics for a specific listing (owner/agent only)
   */
  async getListingAnalytics(listingId: number, userId: number) {
    try {
      this.logger.debug(`Getting analytics for listing ${listingId} requested by user ${userId}`);
 
      // Verify listing exists and check ownership
      const listing = await this.prisma.client.listing.findUnique({
        where: { id: listingId },
        select: { id: true, userId: true, deletedAt: true },
      });
 
      if (!listing) {
        throw new NotFoundException(`Listing #${listingId} not found`);
      }
 
      // Check ownership (unless admin/moderator)
      const user = await this.prisma.client.user.findUnique({
        where: { id: userId },
        select: { role: true },
      });
 
      if (listing.userId !== userId && user?.role !== 'ADMIN' && user?.role !== 'MODERATOR') {
        throw new ForbiddenException('You do not have permission to view analytics for this listing');
      }
 
      // Get Redis counters
      const [
        totalViews,
        phoneClicks,
        websiteClicks,
        emailClicks,
      ] = await (async () => {
        try {
          const stop = (this.metrics?.startTimer('redis', 'analytics_get_counters') as (() => void)) || (() => {});
          const values = await withRetry(async () => {
            return await Promise.all([
              this.redis.get(`analytics:listing:${listingId}:views`),
              this.redis.get(`analytics:listing:${listingId}:clicks:phone`),
              this.redis.get(`analytics:listing:${listingId}:clicks:website`),
              this.redis.get(`analytics:listing:${listingId}:clicks:email`),
            ]);
          }, { tries: 2, baseDelayMs: 50, onAttempt: () => this.metrics?.recordRetry('redis', 'success') });
          stop();
          return values;
        } catch (_) {
          return ['0', '0', '0', '0'];
        }
      })();
 
      // Get database counts
      const [favoritesCount, sharesCount, inquiriesCount] = await Promise.all([
        this.prisma.client.listingFavorite.count({ where: { listingId } }),
        this.prisma.client.listingShare.count({ where: { listingId } }),
        this.prisma.client.listingInquiry.count({ where: { listingId } }),
      ]);
 
      const views = parseInt(totalViews || '0');
      const clicks = parseInt(phoneClicks || '0') + parseInt(websiteClicks || '0') + parseInt(emailClicks || '0');
      const conversionRate = views > 0 ? (inquiriesCount / views) * 100 : 0;
 
      const analytics = {
        listingId,
        views,
        clicks: {
          total: clicks,
          phone: parseInt(phoneClicks || '0'),
          website: parseInt(websiteClicks || '0'),
          email: parseInt(emailClicks || '0'),
        },
        favorites: favoritesCount,
        shares: sharesCount,
        inquiries: inquiriesCount,
        conversionRate: Math.round(conversionRate * 100) / 100, // Round to 2 decimal places
      };
 
      this.logger.debug(`Fetched analytics for listing ${listingId}`);
      return analytics;
    } catch (error) {
      if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error getting analytics for listing ${listingId}:`, error);
      throw new Error('Failed to get listing analytics');
    }
  }
 
  /**
   * Get popular searches (admin only)
   */
  async getPopularSearches(period: 'day' | 'week' | 'month' = 'week') {
    try {
      this.logger.debug(`Getting popular searches for period: ${period}`);
 
      // TODO: Implement search query tracking
      // For now, return placeholder data
      return {
        period,
        searches: [],
        message: 'Search tracking not yet implemented',
      };
    } catch (error) {
      this.logger.error(`Error getting popular searches:`, error);
      throw new Error('Failed to get popular searches');
    }
  }
 
  /**
   * Cohort analysis: new users per week and their subsequent activity
   */
  async getCohortAnalysis(start?: Date, end?: Date) {
    const from = start || new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
    const to = end || new Date();
    // Aggregate in DB where possible; simplified query for users and their listings/leads
    const users = await this.prisma.client.user.findMany({
      where: { createdAt: { gte: from, lte: to } },
      select: { id: true, createdAt: true },
    });
    const userIds = users.map((u: { id: number }) => u.id);
    const [listingsByUser, leadsByUser] = await Promise.all([
      this.prisma.client.listing.groupBy({ by: ['userId'], where: { userId: { in: userIds } }, _count: { _all: true } }) as any,
      this.prisma.client.lead.groupBy({ by: ['agentId'], where: { agentId: { in: userIds } }, _count: { _all: true } }) as any,
    ]);
    const listingsMap = new Map<number, number>((listingsByUser || []).map((r: any) => [r.userId, r._count._all]));
    const leadsMap = new Map<number, number>((leadsByUser || []).map((r: any) => [r.agentId, r._count._all]));
    return {
      window: { start: from, end: to },
      cohorts: users.map((u: { id: number; createdAt: Date }) => ({ userId: u.id, joined: u.createdAt, listings: listingsMap.get(u.id) || 0, leads: leadsMap.get(u.id) || 0 })),
    };
  }
 
  /**
   * Channel attribution by reading tracked click keys in Redis
   */
  async getChannelAttribution(period: 'day' | 'week' | 'month' = 'week') {
    // Placeholder aggregation via DB clicks (if tracked) and Redis keys; returning zeroes if unavailable
    return {
      period,
      channels: [
        { channel: 'seo',    contributions: 0 },
        { channel: 'paid',   contributions: 0 },
        { channel: 'social', contributions: 0 },
        { channel: 'direct', contributions: 0 },
      ],
    };
  }
 
  /**
   * Geo heatmap: aggregate listings and inquiries by location
   */
  async getGeoHeatmap(period: 'day' | 'week' | 'month' = 'week') {
    const since = new Date();
    const days = period === 'day' ? 1 : period === 'week' ? 7 : 30;
    since.setDate(since.getDate() - days);
    const listings = await this.prisma.client.address.findMany({
      where: { listings: { some: { createdAt: { gte: since } } } } as any,
      select: { id: true, latitude: true, longitude: true, listings: { select: { id: true } } },
    });
    return {
      period,
      points: listings
        .filter((a: any) => typeof a.latitude === 'number' && typeof a.longitude === 'number')
        .map((a: any) => ({ lat: a.latitude, lng: a.longitude, weight: a.listings.length })),
    };
  }
 
  /**
   * Get agent dashboard data
   */
  async getAgentDashboard(userId: number) {
    try {
      this.logger.debug(`Getting dashboard data for agent ${userId}`);
 
      // Verify user exists and is an agent
      const user = await this.prisma.client.user.findUnique({
        where: { id: userId },
        select: { role: true },
      });
 
      Iif (!user) {
        throw new NotFoundException(`User #${userId} not found`);
      }
 
      Iif (!['AGENT', 'AGENCY_OWNER', 'REALTOR_PRO', 'ADMIN'].includes(user.role)) {
        throw new ForbiddenException('Only agents can access dashboard data');
      }
 
      // Get counts
      const [
        publishedListings,
        draftListings,
        archivedListings,
        totalInquiries,
        totalLeads,
      ] = await Promise.all([
        this.prisma.client.listing.count({
          where: { userId, status: 'PUBLISHED', deletedAt: null },
        }),
        this.prisma.client.listing.count({
          where: { userId, status: 'DRAFT', deletedAt: null },
        }),
        this.prisma.client.listing.count({
          where: { userId, status: 'ARCHIVED', deletedAt: null },
        }),
        this.prisma.client.listingInquiry.count({
          where: { listing: { userId } },
        }),
        this.prisma.client.lead.count({
          where: { agentId: userId },
        }),
      ]);
 
      // Get total views across all listings
      const userListings = await this.prisma.client.listing.findMany({
        where: { userId, deletedAt: null },
        select: { id: true, deletedAt: true },
      });
 
      let totalViews = 0;
      for (const listing of userListings) {
        Iif (listing.deletedAt) continue;
        let views: string = '0';
        try {
          const val = await this.redis.get(`analytics:listing:${listing.id}:views`);
          views = val ?? '0';
        } catch (_) {}
        totalViews += parseInt(views);
      }
 
      const dashboard = {
        listings: {
          published: publishedListings,
          draft: draftListings,
          archived: archivedListings,
          total: publishedListings + draftListings + archivedListings,
        },
        totalViews,
        totalInquiries,
        totalLeads,
        conversionRate: totalViews > 0 ? Math.round((totalInquiries / totalViews) * 10000) / 100 : 0,
      };
 
      this.logger.debug(`Fetched dashboard data for agent ${userId}`);
      return dashboard;
    } catch (error) {
      Iif (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error getting agent dashboard for user ${userId}:`, error);
      throw new Error('Failed to get agent dashboard');
    }
  }
}