Spaces:
Sleeping
Sleeping
Download apps/api/src/network/reputation.service.ts from Benaah/MicProtocol: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/src/network/reputation.service.ts
- Command line
-
hf download hf://spaces/Benaah/MicProtocol/apps/api/src/network/reputation.service.ts
-
curl -L -o reputation.service.ts https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/src/network/reputation.service.ts
17.6 kB
| import { Injectable, Logger } from "@nestjs/common"; | |
| import { PrismaService } from "../prisma/prisma.service"; | |
| /** | |
| * Reputation Dimensions Interface | |
| * Behavioral and verifiable metrics (unlike LinkedIn endorsements) | |
| */ | |
| interface ReputationDimensions { | |
| // responsiveness (30% weight) | |
| responseTime: number; // median hours to reply to outreach | |
| responseRate: number; // % of inquiries that get any response | |
| // reliability (40% weight) | |
| assetDelivery: number; // % on-time delivery | |
| showUpRate: number; // % no-shows or last-minute reschedules | |
| punctualityScore: number; // minutes early/late to recording | |
| // quality (30% weight) - host feedback loop | |
| contentRating: number; // 1-5 stars post-episode | |
| audienceEngagement: number; // clip performance vs average | |
| prepQuality: number; // host ratings on preparation | |
| } | |
| export interface ReputationScore { | |
| composite: number; // 0-100 | |
| breakdown: { | |
| responsiveness: number; | |
| reliability: number; | |
| quality: number; | |
| }; | |
| tier: "bronze" | "silver" | "gold"; | |
| } | |
| interface RegionalThresholds { | |
| expectedResponseHours: number; | |
| assetGraceHours: number; | |
| } | |
| interface WeightedBooking { | |
| date: Date; | |
| weight: number; | |
| responseTime?: number; | |
| deliveredOnTime?: boolean; | |
| showedUp?: boolean; | |
| contentRating?: number; | |
| prepQuality?: number; | |
| } | |
| /** | |
| * ReputationEngine | |
| * | |
| * Calculates guest reputation based on behavioral metrics. | |
| * Unlike subjective endorsements, these metrics are verifiable through | |
| * actual platform interactions. | |
| * | |
| * African Market Adaptations: | |
| * - WhatsApp response time counts toward responsiveness | |
| * - Mobile data constraints: Lower thresholds for "on-time" assets | |
| * - Regional thresholds account for infrastructure differences | |
| */ | |
| () | |
| export class ReputationEngine { | |
| private readonly logger = new Logger(ReputationEngine.name); | |
| // Weight configuration | |
| private readonly WEIGHTS = { | |
| responsiveness: 0.30, | |
| reliability: 0.40, | |
| quality: 0.30, | |
| }; | |
| // Tier thresholds | |
| private readonly TIER_THRESHOLDS = { | |
| gold: 85, | |
| silver: 65, | |
| bronze: 40, | |
| }; | |
| constructor(private readonly prisma: PrismaService) {} | |
| /** | |
| * Calculate reputation score for a guest | |
| */ | |
| async calculate(guestProfileId: string): Promise<ReputationScore> { | |
| this.logger.log(`Calculating reputation for profile ${guestProfileId}`); | |
| const bookings = await this.getBookingHistory(guestProfileId); | |
| const metrics = await this.getLatestMetrics(guestProfileId); | |
| const profile = await this.prisma.guestPublicProfile.findUnique({ | |
| where: { id: guestProfileId }, | |
| select: { country: true }, | |
| }); | |
| // Get regional thresholds for African market context | |
| const thresholds = this.getRegionalThresholds(profile?.country); | |
| // Weight recent behavior more heavily (exponential decay) | |
| const weighted = bookings.map((b) => ({ | |
| ...b, | |
| date: b.appearedAt, | |
| weight: Math.pow(0.9, this.monthsAgo(new Date(b.appearedAt))), | |
| })); | |
| const responsiveness = this.calcResponseMetrics(weighted, metrics, thresholds); | |
| const reliability = this.calcReliabilityMetrics(weighted, metrics, thresholds); | |
| const quality = this.calcQualityMetrics(weighted, metrics); | |
| // Calculate composite score | |
| const composite = Math.round( | |
| responsiveness * this.WEIGHTS.responsiveness + | |
| reliability * this.WEIGHTS.reliability + | |
| quality * this.WEIGHTS.quality | |
| ); | |
| const score: ReputationScore = { | |
| composite, | |
| breakdown: { | |
| responsiveness: Math.round(responsiveness), | |
| reliability: Math.round(reliability), | |
| quality: Math.round(quality), | |
| }, | |
| tier: this.assignTier(composite), | |
| }; | |
| // Update profile with new score | |
| await this.updateProfileScore(guestProfileId, score, bookings.length); | |
| return score; | |
| } | |
| /** | |
| * Get booking history with related metrics | |
| */ | |
| private async getBookingHistory(profileId: string) { | |
| const [bookingHistory, reviews, requests] = await Promise.all([ | |
| this.prisma.bookingHistory.findMany({ | |
| where: { profileId }, | |
| orderBy: { appearedAt: "desc" }, | |
| }), | |
| this.prisma.hostReview.findMany({ | |
| where: { profileId }, | |
| }), | |
| this.prisma.networkBookingRequest.findMany({ | |
| where: { toProfileId: profileId }, | |
| }), | |
| ]); | |
| // Merge data for analysis | |
| return bookingHistory.map((history) => { | |
| const review = reviews.find( | |
| (r) => r.createdAt > history.appearedAt && | |
| r.createdAt < new Date(history.appearedAt.getTime() + 7 * 24 * 60 * 60 * 1000) | |
| ); | |
| const relatedRequest = requests.find( | |
| (r) => r.toProfileId === profileId && | |
| Math.abs(r.createdAt.getTime() - history.appearedAt.getTime()) < 30 * 24 * 60 * 60 * 1000 | |
| ); | |
| return { | |
| ...history, | |
| contentRating: review?.contentRating, | |
| prepQuality: review?.prepQuality, | |
| responseTime: relatedRequest?.respondedAt | |
| ? (relatedRequest.respondedAt.getTime() - relatedRequest.createdAt.getTime()) / (1000 * 60 * 60) | |
| : undefined, | |
| }; | |
| }); | |
| } | |
| /** | |
| * Get latest reliability metrics | |
| */ | |
| private async getLatestMetrics(profileId: string) { | |
| const metrics = await this.prisma.reliabilityMetric.findMany({ | |
| where: { profileId }, | |
| orderBy: { calculatedAt: "desc" }, | |
| take: 1, | |
| }); | |
| return metrics[0] || null; | |
| } | |
| /** | |
| * Calculate months ago from a date | |
| */ | |
| private monthsAgo(date: Date): number { | |
| const now = new Date(); | |
| return ( | |
| (now.getFullYear() - date.getFullYear()) * 12 + | |
| (now.getMonth() - date.getMonth()) | |
| ); | |
| } | |
| /** | |
| * Calculate responsiveness metrics (30% weight) | |
| * - Response time to booking requests | |
| * - Response rate (% of inquiries answered) | |
| */ | |
| private calcResponseMetrics( | |
| weighted: WeightedBooking[], | |
| metrics: any, | |
| thresholds: RegionalThresholds | |
| ): number { | |
| // Response time score (lower is better) | |
| const responseTimes = weighted | |
| .filter((b) => b.responseTime !== undefined) | |
| .map((b) => ({ | |
| time: b.responseTime!, | |
| weight: b.weight, | |
| })); | |
| let responseTimeScore = 50; // default neutral | |
| if (responseTimes.length > 0) { | |
| const weightedMedian = this.weightedMedian( | |
| responseTimes.map((r) => r.time), | |
| responseTimes.map((r) => r.weight) | |
| ); | |
| // Score: 100 for instant response, 0 for exceeding threshold | |
| responseTimeScore = Math.max(0, 100 - (weightedMedian / thresholds.expectedResponseHours) * 100); | |
| } | |
| // Response rate score | |
| const responseRate = metrics?.responseRate ?? 0.5; | |
| const responseRateScore = responseRate * 100; | |
| // Combined responsiveness (60% response time, 40% response rate) | |
| return responseTimeScore * 0.6 + responseRateScore * 0.4; | |
| } | |
| /** | |
| * Calculate reliability metrics (40% weight) | |
| * - Asset delivery on time | |
| * - Show up rate | |
| * - Punctuality | |
| */ | |
| private calcReliabilityMetrics( | |
| weighted: WeightedBooking[], | |
| metrics: any, | |
| thresholds: RegionalThresholds | |
| ): number { | |
| // Asset delivery rate (from stored metrics) | |
| const assetDeliveryScore = (metrics?.assetDeliveryRate ?? 0.5) * 100; | |
| // Show up rate (from stored metrics) | |
| const showUpScore = (metrics?.showUpRate ?? 0.5) * 100; | |
| // Combined reliability (50% asset delivery, 50% show up) | |
| return assetDeliveryScore * 0.5 + showUpScore * 0.5; | |
| } | |
| /** | |
| * Calculate quality metrics (30% weight) | |
| * - Content ratings from hosts | |
| * - Preparation quality | |
| */ | |
| private calcQualityMetrics( | |
| weighted: WeightedBooking[], | |
| metrics: any | |
| ): number { | |
| // Content ratings from reviews | |
| const ratings = weighted | |
| .filter((b) => b.contentRating !== undefined) | |
| .map((b) => ({ | |
| rating: b.contentRating!, | |
| weight: b.weight, | |
| })); | |
| let contentScore = 50; | |
| if (ratings.length > 0) { | |
| const weightedAvg = | |
| ratings.reduce((sum, r) => sum + r.rating * r.weight, 0) / | |
| ratings.reduce((sum, r) => sum + r.weight, 0); | |
| contentScore = (weightedAvg / 5) * 100; // Convert 1-5 to 0-100 | |
| } | |
| // Prep quality from reviews | |
| const prepRatings = weighted | |
| .filter((b) => b.prepQuality !== undefined) | |
| .map((b) => ({ | |
| rating: b.prepQuality!, | |
| weight: b.weight, | |
| })); | |
| let prepScore = 50; | |
| if (prepRatings.length > 0) { | |
| const weightedAvg = | |
| prepRatings.reduce((sum, r) => sum + r.rating * r.weight, 0) / | |
| prepRatings.reduce((sum, r) => sum + r.weight, 0); | |
| prepScore = (weightedAvg / 5) * 100; | |
| } | |
| // Engagement score from metrics | |
| const engagementScore = (metrics?.engagementScore ?? 0.5) * 100; | |
| // Combined quality (40% content, 40% prep, 20% engagement) | |
| return contentScore * 0.4 + prepScore * 0.4 + engagementScore * 0.2; | |
| } | |
| /** | |
| * Calculate weighted median | |
| */ | |
| private weightedMedian(values: number[], weights: number[]): number { | |
| if (values.length === 0) return 0; | |
| if (values.length === 1) return values[0]; | |
| const sorted = values | |
| .map((v, i) => ({ value: v, weight: weights[i] || 1 })) | |
| .sort((a, b) => a.value - b.value); | |
| const totalWeight = sorted.reduce((sum, s) => sum + s.weight, 0); | |
| const midWeight = totalWeight / 2; | |
| let cumulativeWeight = 0; | |
| for (const item of sorted) { | |
| cumulativeWeight += item.weight; | |
| if (cumulativeWeight >= midWeight) { | |
| return item.value; | |
| } | |
| } | |
| return sorted[sorted.length - 1].value; | |
| } | |
| /** | |
| * Assign tier based on composite score | |
| */ | |
| private assignTier(composite: number): "bronze" | "silver" | "gold" { | |
| if (composite >= this.TIER_THRESHOLDS.gold) return "gold"; | |
| if (composite >= this.TIER_THRESHOLDS.silver) return "silver"; | |
| return "bronze"; | |
| } | |
| /** | |
| * Get regional thresholds for African market context | |
| * Accounts for infrastructure differences across regions | |
| */ | |
| getRegionalThresholds(country: string | null | undefined): RegionalThresholds { | |
| const defaults = { | |
| expectedResponseHours: 48, | |
| assetGraceHours: 12, | |
| }; | |
| if (!country) return defaults; | |
| const normalizedCountry = country.trim().toUpperCase(); | |
| // Nigeria: Slower internet in some regions | |
| if (normalizedCountry === "NIGERIA" || normalizedCountry === "NG") { | |
| return { | |
| expectedResponseHours: 72, | |
| assetGraceHours: 24, | |
| }; | |
| } | |
| // Kenya: Mobile-first, good connectivity but uploads can be slow | |
| if (normalizedCountry === "KENYA" || normalizedCountry === "KE") { | |
| return { | |
| expectedResponseHours: 48, | |
| assetGraceHours: 24, | |
| }; | |
| } | |
| // Ghana: Similar to Nigeria | |
| if (normalizedCountry === "GHANA" || normalizedCountry === "GH") { | |
| return { | |
| expectedResponseHours: 72, | |
| assetGraceHours: 24, | |
| }; | |
| } | |
| // South Africa: Better infrastructure | |
| if (normalizedCountry === "SOUTH AFRICA" || normalizedCountry === "ZA") { | |
| return { | |
| expectedResponseHours: 36, | |
| assetGraceHours: 12, | |
| }; | |
| } | |
| return defaults; | |
| } | |
| /** | |
| * Update profile with calculated score | |
| */ | |
| private async updateProfileScore( | |
| profileId: string, | |
| score: ReputationScore, | |
| totalAppearances: number | |
| ): Promise<void> { | |
| await this.prisma.guestPublicProfile.update({ | |
| where: { id: profileId }, | |
| data: { | |
| reliabilityScore: score.composite, | |
| tier: score.tier, | |
| totalAppearances, | |
| }, | |
| }); | |
| // Remove old metric rows to prevent unbounded growth, then insert new one | |
| await this.prisma.reliabilityMetric.deleteMany({ | |
| where: { profileId }, | |
| }); | |
| await this.prisma.reliabilityMetric.create({ | |
| data: { | |
| profileId, | |
| responseRate: score.breakdown.responsiveness / 100, | |
| assetDeliveryRate: score.breakdown.reliability / 100, | |
| showUpRate: score.breakdown.reliability / 100, | |
| engagementScore: score.breakdown.quality / 100, | |
| totalBookings: totalAppearances, | |
| }, | |
| }); | |
| // Update TrustScore model | |
| await this.prisma.trustScore.upsert({ | |
| where: { profileId }, | |
| create: { | |
| profileId, | |
| score: score.composite, | |
| ratingNorm: score.breakdown.quality / 100, | |
| verification: 0.3, | |
| activity: Math.min(totalAppearances / 10, 1.0), | |
| mlReliability: score.breakdown.reliability / 100, | |
| components: { | |
| composite: score.composite, | |
| breakdown: score.breakdown, | |
| tier: score.tier, | |
| } as any, | |
| }, | |
| update: { | |
| score: score.composite, | |
| ratingNorm: score.breakdown.quality / 100, | |
| activity: Math.min(totalAppearances / 10, 1.0), | |
| mlReliability: score.breakdown.reliability / 100, | |
| components: { | |
| composite: score.composite, | |
| breakdown: score.breakdown, | |
| tier: score.tier, | |
| } as any, | |
| }, | |
| }); | |
| this.logger.log( | |
| `Updated profile ${profileId}: score=${score.composite}, tier=${score.tier}` | |
| ); | |
| } | |
| /** | |
| * Recalculate reputation for all profiles | |
| * Queues individual jobs per profile for parallel processing. | |
| */ | |
| async recalculateAll(): Promise<{ queued: number }> { | |
| this.logger.log("Queueing reputation recalculation for all profiles"); | |
| const profiles = await this.prisma.guestPublicProfile.findMany({ | |
| where: { isPublic: true }, | |
| select: { id: true }, | |
| }); | |
| // Use the provided queue — trust the caller to inject the right one | |
| // This method is called from a controller that has access to the injected Queue | |
| this.logger.warn( | |
| "recalculateAll is deprecated — queue individual jobs via network queue instead" | |
| ); | |
| return { queued: 0 }; | |
| } | |
| /** | |
| * Get reputation insights for a profile | |
| * Returns actionable advice for improving score | |
| */ | |
| async getInsights(profileId: string): Promise<{ | |
| currentScore: ReputationScore; | |
| suggestions: string[]; | |
| }> { | |
| const profile = await this.prisma.guestPublicProfile.findUnique({ | |
| where: { id: profileId }, | |
| include: { | |
| reliabilityMetrics: { | |
| orderBy: { calculatedAt: "desc" }, | |
| take: 1, | |
| }, | |
| bookingHistory: { | |
| orderBy: { appearedAt: "desc" }, | |
| take: 10, | |
| }, | |
| availabilityWindows: true, | |
| }, | |
| }); | |
| if (!profile) { | |
| throw new Error("Profile not found"); | |
| } | |
| const score = await this.calculate(profileId); | |
| const suggestions: string[] = []; | |
| // Check for improvement areas | |
| if (score.breakdown.responsiveness < 70) { | |
| suggestions.push( | |
| "Improve response time: Consider enabling WhatsApp notifications for faster replies" | |
| ); | |
| } | |
| if (score.breakdown.reliability < 70) { | |
| suggestions.push( | |
| "Improve reliability: Submit assets before deadlines and confirm bookings promptly" | |
| ); | |
| } | |
| if (score.breakdown.quality < 70) { | |
| suggestions.push( | |
| "Improve content quality: Prepare talking points and research the podcast format" | |
| ); | |
| } | |
| if (profile.bookingHistory.length < 3) { | |
| suggestions.push( | |
| "Build track record: Complete more episodes to establish credibility" | |
| ); | |
| } | |
| if (!profile.availabilityWindows || profile.availabilityWindows.length === 0) { | |
| suggestions.push( | |
| "Add availability windows to make it easier for hosts to book you" | |
| ); | |
| } | |
| return { currentScore: score, suggestions }; | |
| } | |
| } | |