This commit is contained in:
2025-12-14 18:11:59 +01:00
parent acc15e8d8d
commit 217337862c
91 changed files with 5919 additions and 1999 deletions

View File

@@ -6,6 +6,7 @@
*/
import type { AsyncUseCase } from '@gridpilot/shared/application';
import type { ILogger } from '@gridpilot/shared/application';
import type { IPageViewRepository } from '../../domain/repositories/IPageViewRepository';
import type { IEngagementRepository } from '../../domain/repositories/IEngagementRepository';
import type { IAnalyticsSnapshotRepository } from '../../domain/repositories/IAnalyticsSnapshotRepository';
@@ -47,56 +48,108 @@ export class GetEntityAnalyticsQuery
constructor(
private readonly pageViewRepository: IPageViewRepository,
private readonly engagementRepository: IEngagementRepository,
private readonly snapshotRepository: IAnalyticsSnapshotRepository
private readonly snapshotRepository: IAnalyticsSnapshotRepository,
private readonly logger: ILogger
) {}
async execute(input: GetEntityAnalyticsInput): Promise<EntityAnalyticsOutput> {
this.logger.debug(`Executing GetEntityAnalyticsQuery with input: ${JSON.stringify(input)}`);
const period = input.period ?? 'weekly';
const now = new Date();
const since = input.since ?? this.getPeriodStartDate(now, period);
this.logger.debug(`Calculated period: ${period}, now: ${now.toISOString()}, since: ${since.toISOString()}`);
// Get current metrics
const totalPageViews = await this.pageViewRepository.countByEntityId(
input.entityType,
input.entityId,
since
);
let totalPageViews = 0;
try {
totalPageViews = await this.pageViewRepository.countByEntityId(
input.entityType,
input.entityId,
since
);
this.logger.debug(`Total page views for entity ${input.entityId}: ${totalPageViews}`);
} catch (error) {
this.logger.error(`Error counting total page views for entity ${input.entityId}: ${error.message}`);
throw error;
}
const uniqueVisitors = await this.pageViewRepository.countUniqueVisitors(
input.entityType,
input.entityId,
since
);
let uniqueVisitors = 0;
try {
uniqueVisitors = await this.pageViewRepository.countUniqueVisitors(
input.entityType,
input.entityId,
since
);
this.logger.debug(`Unique visitors for entity ${input.entityId}: ${uniqueVisitors}`);
} catch (error) {
this.logger.error(`Error counting unique visitors for entity ${input.entityId}: ${error.message}`);
throw error;
}
const sponsorClicks = await this.engagementRepository.getSponsorClicksForEntity(
input.entityId,
since
);
let sponsorClicks = 0;
try {
sponsorClicks = await this.engagementRepository.getSponsorClicksForEntity(
input.entityId,
since
);
this.logger.debug(`Sponsor clicks for entity ${input.entityId}: ${sponsorClicks}`);
} catch (error) {
this.logger.error(`Error getting sponsor clicks for entity ${input.entityId}: ${error.message}`);
throw error;
}
// Calculate engagement score (weighted sum of actions)
const engagementScore = await this.calculateEngagementScore(input.entityId, since);
let engagementScore = 0;
try {
engagementScore = await this.calculateEngagementScore(input.entityId, since);
this.logger.debug(`Engagement score for entity ${input.entityId}: ${engagementScore}`);
} catch (error) {
this.logger.error(`Error calculating engagement score for entity ${input.entityId}: ${error.message}`);
throw error;
}
// Determine trust indicator
const trustIndicator = this.determineTrustIndicator(totalPageViews, uniqueVisitors, engagementScore);
this.logger.debug(`Trust indicator for entity ${input.entityId}: ${trustIndicator}`);
// Calculate exposure value (for sponsor ROI)
const exposureValue = this.calculateExposureValue(totalPageViews, uniqueVisitors, sponsorClicks);
this.logger.debug(`Exposure value for entity ${input.entityId}: ${exposureValue}`);
// Get previous period for trends
const previousPeriodStart = this.getPreviousPeriodStart(since, period);
const previousPageViews = await this.pageViewRepository.countByEntityId(
input.entityType,
input.entityId,
previousPeriodStart
) - totalPageViews;
this.logger.debug(`Previous period start: ${previousPeriodStart.toISOString()}`);
const previousUniqueVisitors = await this.pageViewRepository.countUniqueVisitors(
input.entityType,
input.entityId,
previousPeriodStart
) - uniqueVisitors;
let previousPageViews = 0;
try {
const fullPreviousPageViews = await this.pageViewRepository.countByEntityId(
input.entityType,
input.entityId,
previousPeriodStart
);
previousPageViews = fullPreviousPageViews - totalPageViews; // This calculates change, not just previous period's total
this.logger.debug(`Previous period full page views: ${fullPreviousPageViews}, change: ${previousPageViews}`);
} catch (error) {
this.logger.error(`Error counting previous period page views for entity ${input.entityId}: ${error.message}`);
throw error;
}
return {
let previousUniqueVisitors = 0;
try {
const fullPreviousUniqueVisitors = await this.pageViewRepository.countUniqueVisitors(
input.entityType,
input.entityId,
previousPeriodStart
);
previousUniqueVisitors = fullPreviousUniqueVisitors - uniqueVisitors; // This calculates change, not just previous period's total
this.logger.debug(`Previous period full unique visitors: ${fullPreviousUniqueVisitors}, change: ${previousUniqueVisitors}`);
} catch (error) {
this.logger.error(`Error counting previous period unique visitors for entity ${input.entityId}: ${error.message}`);
throw error;
}
const result: EntityAnalyticsOutput = {
entityType: input.entityType,
entityId: input.entityId,
summary: {
@@ -118,9 +171,12 @@ export class GetEntityAnalyticsQuery
label: this.formatPeriodLabel(since, now),
},
};
this.logger.info(`Successfully retrieved analytics for entity ${input.entityId}.`);
return result;
}
private getPeriodStartDate(now: Date, period: SnapshotPeriod): Date {
this.logger.debug(`Calculating period start date for "${period}" from ${now.toISOString()}`);
const start = new Date(now);
switch (period) {
case 'daily':
@@ -133,10 +189,12 @@ export class GetEntityAnalyticsQuery
start.setMonth(start.getMonth() - 1);
break;
}
this.logger.debug(`Period start date calculated: ${start.toISOString()}`);
return start;
}
private getPreviousPeriodStart(currentStart: Date, period: SnapshotPeriod): Date {
this.logger.debug(`Calculating previous period start date for "${period}" from ${currentStart.toISOString()}`);
const start = new Date(currentStart);
switch (period) {
case 'daily':
@@ -149,13 +207,23 @@ export class GetEntityAnalyticsQuery
start.setMonth(start.getMonth() - 1);
break;
}
this.logger.debug(`Previous period start date calculated: ${start.toISOString()}`);
return start;
}
private async calculateEngagementScore(entityId: string, since: Date): Promise<number> {
// Base engagement from sponsor interactions
const sponsorClicks = await this.engagementRepository.getSponsorClicksForEntity(entityId, since);
return sponsorClicks * 10; // Weighted score
this.logger.debug(`Calculating engagement score for entity ${entityId} since ${since.toISOString()}`);
let sponsorClicks = 0;
try {
sponsorClicks = await this.engagementRepository.getSponsorClicksForEntity(entityId, since);
this.logger.debug(`Sponsor clicks for engagement score for entity ${entityId}: ${sponsorClicks}`);
} catch (error) {
this.logger.error(`Error getting sponsor clicks for engagement score for entity ${entityId}: ${error.message}`);
throw error;
}
const score = sponsorClicks * 10; // Weighted score
this.logger.debug(`Calculated engagement score for entity ${entityId}: ${score}`);
return score;
}
private determineTrustIndicator(
@@ -163,8 +231,10 @@ export class GetEntityAnalyticsQuery
uniqueVisitors: number,
engagementScore: number
): 'high' | 'medium' | 'low' {
this.logger.debug(`Determining trust indicator with pageViews: ${pageViews}, uniqueVisitors: ${uniqueVisitors}, engagementScore: ${engagementScore}`);
const engagementRate = pageViews > 0 ? engagementScore / pageViews : 0;
const returningVisitorRate = pageViews > 0 ? (pageViews - uniqueVisitors) / pageViews : 0;
this.logger.debug(`Engagement rate: ${engagementRate}, Returning visitor rate: ${returningVisitorRate}`);
if (engagementRate > 0.1 && returningVisitorRate > 0.3) {
return 'high';
@@ -180,20 +250,33 @@ export class GetEntityAnalyticsQuery
uniqueVisitors: number,
sponsorClicks: number
): number {
this.logger.debug(`Calculating exposure value with pageViews: ${pageViews}, uniqueVisitors: ${uniqueVisitors}, sponsorClicks: ${sponsorClicks}`);
// Simple exposure value calculation (could be monetized)
return (pageViews * 0.01) + (uniqueVisitors * 0.05) + (sponsorClicks * 0.50);
const exposure = (pageViews * 0.01) + (uniqueVisitors * 0.05) + (sponsorClicks * 0.50);
this.logger.debug(`Calculated exposure value: ${exposure}`);
return exposure;
}
private calculatePercentageChange(previous: number, current: number): number {
if (previous === 0) return current > 0 ? 100 : 0;
return Math.round(((current - previous) / previous) * 100);
this.logger.debug(`Calculating percentage change from previous: ${previous} to current: ${current}`);
if (previous === 0) {
const change = current > 0 ? 100 : 0;
this.logger.debug(`Percentage change (previous was 0): ${change}%`);
return change;
}
const change = Math.round(((current - previous) / previous) * 100);
this.logger.debug(`Percentage change: ${change}%`);
return change;
}
private formatPeriodLabel(start: Date, end: Date): string {
this.logger.debug(`Formatting period label from ${start.toISOString()} to ${end.toISOString()}`);
const formatter = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
});
return `${formatter.format(start)} - ${formatter.format(end)}`;
const label = `${formatter.format(start)} - ${formatter.format(end)}`;
this.logger.debug(`Formatted period label: "${label}"`);
return label;
}
}