MicProtocol / apps /api /dist /network /network.service.js
Benaah's picture
Upload folder using huggingface_hub (part 2)
9f29339 verified
Raw History Blame Contribute Delete
59.1 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var NetworkService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.NetworkService = void 0; const common_1 = require("@nestjs/common"); const bullmq_1 = require("@nestjs/bullmq"); const bullmq_2 = require("bullmq"); const crypto_1 = require("crypto"); const prisma_service_1 = require("../prisma/prisma.service"); const authorization_service_1 = require("../common/authorization.service"); const platform_admin_1 = require("../common/platform-admin"); const redis_rate_limiter_service_1 = require("../common/redis-rate-limiter.service"); const shared_types_1 = require("@micprotocol/shared-types"); const meilisearch_service_1 = require("./meilisearch.service"); const reputation_service_1 = require("./reputation.service"); const graph_service_1 = require("./graph.service"); let NetworkService = NetworkService_1 = class NetworkService { prisma; authorizationService; rateLimiter; meilisearch; reputationEngine; graphService; networkQueue; logger = new common_1.Logger(NetworkService_1.name); allowedVerificationStatuses = ["verified", "featured"]; constructor(prisma, authorizationService, rateLimiter, meilisearch, reputationEngine, graphService, networkQueue) { this.prisma = prisma; this.authorizationService = authorizationService; this.rateLimiter = rateLimiter; this.meilisearch = meilisearch; this.reputationEngine = reputationEngine; this.graphService = graphService; this.networkQueue = networkQueue; } slugify(text) { return text .toLowerCase() .trim() .replace(/[^\w\s-]/g, "") .replace(/[\s_]+/g, "-") .replace(/-+/g, "-") .substring(0, 60); } async generateVanityUrl(name) { const base = this.slugify(name); const existing = await this.prisma.guestPublicProfile.findUnique({ where: { vanityUrl: base } }); if (!existing) { return base; } const suffix = (0, crypto_1.createHash)("sha256").update(`${base}-${Date.now()}`).digest("hex").substring(0, 8); return `${base}-${suffix}`; } isVerificationEligible(status) { return status === "verified" || status === "featured"; } isProfileDiscoverable(profile) { return profile.isPublic && this.isVerificationEligible(profile.verificationStatus); } async createProfile(userId, data) { this.logger.log(`Creating guest public profile for user ${userId}`); const existing = await this.prisma.guestPublicProfile.findUnique({ where: { userId }, }); if (existing) { throw new common_1.ConflictException("User already has a public profile"); } const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new common_1.NotFoundException("User not found"); } const displayName = user.profile?.fullName || user.email.split("@")[0]; let profile = null; let attempt = 0; while (!profile && attempt < 5) { attempt++; const baseVanity = await this.generateVanityUrl(displayName); const vanityUrl = baseVanity + (attempt > 1 ? `-${attempt}` : ""); try { profile = await this.prisma.guestPublicProfile.create({ data: { userId, vanityUrl, isPublic: false, headline: data.headline, fullBio: data.fullBio, country: data.country, city: data.city, languages: data.languages || [], timezone: data.timezone, phoneNumber: data.phoneNumber, whatsappNumber: data.whatsappNumber, avatarUrl: data.avatarUrl, visibilitySettings: data.visibilitySettings || {}, expertiseTags: data.expertiseTags ? { createMany: { data: data.expertiseTags.map((t) => ({ name: t.name, category: t.category || null, })), }, } : undefined, availabilityWindows: data.availabilityWindows ? { createMany: { data: data.availabilityWindows.map((w) => ({ dayOfWeek: w.dayOfWeek, startHour: w.startHour, endHour: w.endHour, timezone: w.timezone || "UTC", })), }, } : undefined, }, include: { expertiseTags: true, availabilityWindows: true, }, }); } catch (error) { const maybeKnownError = error; const target = maybeKnownError.meta?.target || []; const isUniqueConstraint = maybeKnownError.code === "P2002"; if (isUniqueConstraint && (target.includes("vanity_url") || target.includes("vanityUrl"))) { this.logger.warn(`Vanity URL collision for user ${userId}; retrying createProfile attempt ${attempt}/5`); continue; } if (isUniqueConstraint && (target.includes("user_id") || target.includes("userId"))) { throw new common_1.ConflictException("User already has a public profile"); } throw error; } } if (!profile) { throw new common_1.ConflictException("Could not create profile due to repeated vanity URL conflicts. Please retry."); } if (this.isProfileDiscoverable(profile)) { await this.networkQueue.add("search.index-profile", { profileId: profile.id, }); } await this.networkQueue.add("graph.ingest-profile", { profileId: profile.id, userId, }); return profile; } async updateProfile(userId, data) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { userId }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (data.isPublic === true && !this.isVerificationEligible(profile.verificationStatus)) { throw new common_1.ForbiddenException("Only verified or featured profiles can be listed publicly. Complete verification first."); } const updated = await this.prisma.$transaction(async (tx) => { if (data.expertiseTags !== undefined) { await tx.expertiseTag.deleteMany({ where: { profileId: profile.id }, }); if (data.expertiseTags.length > 0) { await tx.expertiseTag.createMany({ data: data.expertiseTags.map((t) => ({ profileId: profile.id, name: t.name, category: t.category || null, })), }); } } if (data.availabilityWindows !== undefined) { await tx.availabilityWindow.deleteMany({ where: { profileId: profile.id }, }); if (data.availabilityWindows.length > 0) { await tx.availabilityWindow.createMany({ data: data.availabilityWindows.map((w) => ({ profileId: profile.id, dayOfWeek: w.dayOfWeek, startHour: w.startHour, endHour: w.endHour, timezone: w.timezone || "UTC", })), }); } } return tx.guestPublicProfile.update({ where: { id: profile.id }, data: { headline: data.headline, fullBio: data.fullBio, country: data.country, city: data.city, languages: data.languages, timezone: data.timezone, phoneNumber: data.phoneNumber, whatsappNumber: data.whatsappNumber, avatarUrl: data.avatarUrl, isPublic: data.isPublic, visibilitySettings: data.visibilitySettings ? data.visibilitySettings : undefined, }, include: { expertiseTags: true, availabilityWindows: true, }, }); }); if (this.isProfileDiscoverable(updated)) { await this.networkQueue.add("search.index-profile", { profileId: updated.id, }); } else { await this.networkQueue.add("search.remove-profile", { profileId: updated.id, }); } return updated; } async getMyProfile(userId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { userId }, include: { expertiseTags: true, availabilityWindows: true, bookingHistory: { where: { isPublic: true }, orderBy: { appearedAt: "desc" }, take: 20, }, reliabilityMetrics: { orderBy: { calculatedAt: "desc" }, take: 1, }, hostReviews: { orderBy: { createdAt: "desc" }, take: 10, }, }, }); if (!profile) { return null; } const [viewsThisWeek, pendingRequests] = await Promise.all([ this.prisma.profileView.count({ where: { profileId: profile.id, viewedAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), }, }, }), this.prisma.networkBookingRequest.count({ where: { toProfileId: profile.id, status: "pending", }, }), ]); return { ...profile, analytics: { viewsThisWeek, pendingRequests, }, }; } async getProfileByVanityUrl(vanityUrl) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { vanityUrl }, select: { id: true, vanityUrl: true, headline: true, fullBio: true, country: true, city: true, languages: true, timezone: true, avatarUrl: true, verificationStatus: true, reliabilityScore: true, totalAppearances: true, averageRating: true, tier: true, verificationBadges: true, isPublic: true, createdAt: true, expertiseTags: { select: { name: true, category: true } }, availabilityWindows: true, bookingHistory: { where: { isPublic: true }, orderBy: { appearedAt: "desc" }, select: { id: true, podcastName: true, hostName: true, appearedAt: true, topicsDiscussed: true, isPublic: true, }, }, hostReviews: { orderBy: { createdAt: "desc" }, take: 5, select: { contentRating: true, prepQuality: true, overallRating: true, comment: true, createdAt: true, }, }, }, }); if (!profile || !this.isProfileDiscoverable(profile)) { throw new common_1.NotFoundException("Profile not found"); } return profile; } async getProfileById(profileId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { id: true, vanityUrl: true, headline: true, fullBio: true, country: true, city: true, languages: true, timezone: true, avatarUrl: true, verificationStatus: true, reliabilityScore: true, totalAppearances: true, averageRating: true, tier: true, verificationBadges: true, isPublic: true, createdAt: true, expertiseTags: { select: { name: true, category: true } }, availabilityWindows: true, bookingHistory: { where: { isPublic: true }, orderBy: { appearedAt: "desc" }, select: { id: true, podcastName: true, hostName: true, appearedAt: true, topicsDiscussed: true, isPublic: true, }, }, }, }); if (!profile || !this.isProfileDiscoverable(profile)) { throw new common_1.NotFoundException("Profile not found"); } return profile; } async searchProfiles(params) { const meiliResults = await this.meilisearch.searchProfiles(params); if (meiliResults.total > 0) { this.logger.debug(`Network search (meili) query="${params.query ?? ""}" total=${meiliResults.total}`); return meiliResults; } const fallbackResults = await this.searchProfilesFromDatabase(params); this.logger.debug(`Network search (fallback-db) query="${params.query ?? ""}" total=${fallbackResults.total}`); return fallbackResults; } async searchProfilesFromDatabase(params) { const { query, country, countries, expertise, languages, minReliabilityScore, minAppearances, verificationStatus, tier, maxResponseTimeHours, sortBy, sortOrder, page = 1, limit = 20, } = params; const andFilters = [ { isPublic: true }, { verificationStatus: { in: [...this.allowedVerificationStatuses] } }, ]; if (query && query.trim()) { const q = query.trim(); andFilters.push({ OR: [ { headline: { contains: q, mode: "insensitive" } }, { fullBio: { contains: q, mode: "insensitive" } }, { country: { contains: q, mode: "insensitive" } }, { city: { contains: q, mode: "insensitive" } }, { expertiseTags: { some: { name: { contains: q, mode: "insensitive" }, }, }, }, ], }); } if (country) { andFilters.push({ country }); } if (countries && countries.length > 0) { andFilters.push({ country: { in: countries } }); } if (expertise && expertise.length > 0) { andFilters.push({ expertiseTags: { some: { name: { in: expertise }, }, }, }); } if (languages && languages.length > 0) { andFilters.push({ languages: { hasSome: languages } }); } if (minReliabilityScore !== undefined) { andFilters.push({ reliabilityScore: { gte: minReliabilityScore } }); } if (minAppearances !== undefined) { andFilters.push({ totalAppearances: { gte: minAppearances } }); } if (verificationStatus) { andFilters.push({ verificationStatus }); } if (tier) { andFilters.push({ tier }); } if (maxResponseTimeHours !== undefined) { andFilters.push({ responseTimeHours: { lte: maxResponseTimeHours } }); } const where = { AND: andFilters, }; const orderBy = []; const direction = sortOrder === "asc" ? "asc" : "desc"; if (sortBy && sortBy !== "relevance") { if (sortBy === "reliabilityScore") orderBy.push({ reliabilityScore: direction }); if (sortBy === "responseTimeHours") orderBy.push({ responseTimeHours: direction }); if (sortBy === "totalAppearances") orderBy.push({ totalAppearances: direction }); if (sortBy === "createdAt") orderBy.push({ createdAt: direction }); } if (orderBy.length === 0) { orderBy.push({ reliabilityScore: "desc" }, { totalAppearances: "desc" }); } const [profiles, total] = await Promise.all([ this.prisma.guestPublicProfile.findMany({ where, include: { expertiseTags: true, }, orderBy, skip: (page - 1) * limit, take: limit, }), this.prisma.guestPublicProfile.count({ where }), ]); return { hits: profiles.map((profile) => ({ id: profile.id, vanityUrl: profile.vanityUrl, avatarUrl: profile.avatarUrl, headline: profile.headline, fullBio: profile.fullBio, country: profile.country, city: profile.city, languages: profile.languages, timezone: profile.timezone, expertiseTags: profile.expertiseTags.map((tag) => tag.name), reliabilityScore: Number(profile.reliabilityScore), totalAppearances: profile.totalAppearances, responseTimeHours: profile.responseTimeHours, verificationStatus: profile.verificationStatus, tier: profile.tier, })), total, page, totalPages: Math.ceil(total / limit), }; } async getTrending(region, limit = 10) { const where = { isPublic: true, verificationStatus: { in: [...this.allowedVerificationStatuses] }, }; if (region) { const regionCountries = { "east-africa": ["Kenya", "Tanzania", "Uganda", "Rwanda", "Ethiopia", "Burundi"], "west-africa": ["Nigeria", "Ghana", "Senegal", "Ivory Coast", "Mali", "Burkina Faso"], "southern-africa": ["South Africa", "Botswana", "Zimbabwe", "Mozambique", "Namibia"], "north-africa": ["Egypt", "Morocco", "Tunisia", "Algeria", "Libya"], "central-africa": ["Cameroon", "Gabon", "DRC", "Chad", "CAR"], }; const countries = regionCountries[region]; if (countries) { where.country = { in: countries }; } } return this.prisma.guestPublicProfile.findMany({ where, orderBy: [ { totalAppearances: "desc" }, { reliabilityScore: "desc" }, ], take: limit, include: { expertiseTags: true, }, }); } async trackView(data) { if (!await this.checkViewRateLimit(data.profileId, 10)) { this.logger.warn(`View rate limit exceeded for profile ${data.profileId}`); return { rateLimited: true }; } if (data.viewerPodcastId) { const existingRecentView = await this.prisma.profileView.findFirst({ where: { profileId: data.profileId, viewerPodcastId: data.viewerPodcastId, viewedAt: { gte: new Date(Date.now() - 24 * 60 * 60 * 1000) }, }, }); if (existingRecentView) { await this.prisma.profileView.update({ where: { id: existingRecentView.id }, data: { viewedAt: new Date() }, }); return { deduplicated: true, id: existingRecentView.id }; } } return this.prisma.profileView.create({ data: { profileId: data.profileId, viewerPodcastId: data.viewerPodcastId || null, source: data.source || "direct", }, }); } async getProfileViewStats(userId, profileId, days = 30) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to view stats for this profile"); } const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000); const [total, bySource, byDay] = await Promise.all([ this.prisma.profileView.count({ where: { profileId, viewedAt: { gte: since } }, }), this.prisma.profileView.groupBy({ by: ["source"], where: { profileId, viewedAt: { gte: since } }, _count: true, }), this.prisma.$queryRaw ` SELECT DATE(viewed_at) as date, COUNT(*)::int as views FROM profile_views WHERE profile_id = ${profileId}::uuid AND viewed_at >= ${since} GROUP BY DATE(viewed_at) ORDER BY date `, ]); return { total, bySource, byDay }; } guestStatusRank = { [shared_types_1.GuestStatus.PROSPECT]: 1, [shared_types_1.GuestStatus.CONTACTED]: 2, [shared_types_1.GuestStatus.SCHEDULED]: 3, [shared_types_1.GuestStatus.RECORDED]: 4, [shared_types_1.GuestStatus.PUBLISHED]: 5, }; elevateGuestStatus(current, desired) { const currentRank = this.guestStatusRank[current] ?? 0; const desiredRank = this.guestStatusRank[desired] ?? 0; return desiredRank > currentRank ? desired : current; } journeyEventForStatus(status) { if (status === shared_types_1.GuestStatus.CONTACTED) return shared_types_1.GuestJourneyEventType.CONTACTED; if (status === shared_types_1.GuestStatus.SCHEDULED) return shared_types_1.GuestJourneyEventType.SCHEDULED; if (status === shared_types_1.GuestStatus.RECORDED) return shared_types_1.GuestJourneyEventType.RECORDED; if (status === shared_types_1.GuestStatus.PUBLISHED) return shared_types_1.GuestJourneyEventType.PUBLISHED; return null; } extractFirstProposedDate(proposedDates) { if (!Array.isArray(proposedDates)) { return null; } for (const value of proposedDates) { if (typeof value !== "string") { continue; } const parsedDate = new Date(value); if (!Number.isNaN(parsedDate.getTime())) { return parsedDate; } } return null; } parseProfileIdentity(profile) { const headline = profile.headline?.trim() || ""; const [namePart, companyPart] = headline.split("|").map((part) => part.trim()); const fullName = namePart || profile.user.email.split("@")[0] || "Network Guest"; const company = companyPart || null; return { fullName, company }; } async ensureGuestPipelineEntry(params) { const { podcastId, profile, desiredStatus } = params; const { fullName, company } = this.parseProfileIdentity(profile); const existingGuest = await this.prisma.guest.findUnique({ where: { podcastId_email: { podcastId, email: profile.user.email, }, }, }); if (existingGuest) { const nextStatus = this.elevateGuestStatus(existingGuest.status, desiredStatus); const updatedGuest = await this.prisma.guest.update({ where: { id: existingGuest.id }, data: { fullName: fullName || existingGuest.fullName, company: company ?? existingGuest.company, bio: profile.fullBio ?? existingGuest.bio, socialLinks: (profile.socialProof || {}), status: nextStatus, ...(nextStatus === shared_types_1.GuestStatus.CONTACTED || nextStatus === shared_types_1.GuestStatus.SCHEDULED ? { lastContactAt: new Date() } : {}), }, }); if (nextStatus !== existingGuest.status) { const eventType = this.journeyEventForStatus(nextStatus); if (eventType) { await this.prisma.guestJourneyEvent.create({ data: { guestId: existingGuest.id, eventType, title: `Guest marked as ${nextStatus}`, details: `Guest lifecycle moved to ${nextStatus} via network sync.`, metadata: { source: "network.ensureGuestPipelineEntry", profileId: profile.id, }, }, }); } } return updatedGuest; } const createdGuest = await this.prisma.guest.create({ data: { podcastId, email: profile.user.email, fullName, company, title: null, bio: profile.fullBio, socialLinks: (profile.socialProof || {}), status: desiredStatus, ...(desiredStatus === shared_types_1.GuestStatus.CONTACTED || desiredStatus === shared_types_1.GuestStatus.SCHEDULED ? { lastContactAt: new Date() } : {}), }, }); const eventType = this.journeyEventForStatus(desiredStatus); if (eventType) { await this.prisma.guestJourneyEvent.create({ data: { guestId: createdGuest.id, eventType, title: `Guest marked as ${desiredStatus}`, details: `Guest lifecycle moved to ${desiredStatus} via network sync.`, metadata: { source: "network.ensureGuestPipelineEntry", profileId: profile.id, }, }, }); } return createdGuest; } async ensureSchedulingPipelineEntry(params) { const { podcastId, guestId, fullName, timezone, marker, action, proposedDate, message, topics, } = params; const noteSections = [marker]; if (message) { noteSections.push(`Network message: ${message}`); } if (topics && topics.length > 0) { noteSections.push(`Proposed topics: ${topics.join(", ")}`); } const hostNotes = noteSections.join("\n\n"); let episode = await this.prisma.episode.findFirst({ where: { podcastId, guestId, hostNotes: { contains: marker }, }, orderBy: { createdAt: "desc" }, }); if (!episode) { episode = await this.prisma.episode.create({ data: { podcastId, guestId, title: action === "request" ? `Network booking: ${fullName}` : `Network lead: ${fullName}`, status: proposedDate ? "scheduled" : "draft", scheduledAt: proposedDate, durationMinutes: 60, hostNotes, }, }); } else if (proposedDate) { await this.prisma.episode.update({ where: { id: episode.id }, data: { status: "scheduled", scheduledAt: episode.scheduledAt || proposedDate, hostNotes: episode.hostNotes && episode.hostNotes.includes(marker) ? episode.hostNotes : `${episode.hostNotes || ""}\n\n${marker}`.trim(), }, }); } if (!proposedDate) { return; } const existingBooking = await this.prisma.booking.findFirst({ where: { episodeId: episode.id, }, }); if (existingBooking) { return; } const endDate = new Date(proposedDate.getTime() + 60 * 60 * 1000); await this.prisma.booking.create({ data: { episodeId: episode.id, startTime: proposedDate, endTime: endDate, timezone: timezone || "UTC", meetLink: null, isConfirmed: false, }, }); } async syncProfileToPipelines(params) { const { podcastId, profile, action, requestId, message, proposedTopics, proposedDates } = params; const proposedDate = this.extractFirstProposedDate(proposedDates); const desiredStatus = action === "bookmark" ? shared_types_1.GuestStatus.PROSPECT : proposedDate ? shared_types_1.GuestStatus.SCHEDULED : shared_types_1.GuestStatus.CONTACTED; const guest = await this.ensureGuestPipelineEntry({ podcastId, profile, desiredStatus, }); const { fullName } = this.parseProfileIdentity(profile); const marker = action === "bookmark" ? `[network-bookmark:${profile.id}]` : `[network-request:${requestId || profile.id}]`; await this.ensureSchedulingPipelineEntry({ podcastId, guestId: guest.id, fullName, timezone: profile.timezone, marker, action, proposedDate, message, topics: proposedTopics, }); this.logger.debug(`Synced network ${action} into pipelines: podcast=${podcastId} profile=${profile.id} guest=${guest.id}`); } async createBookmark(data, userId) { await this.authorizationService.checkPodcastAccess(data.podcastId, userId); const bookmark = await this.prisma.networkBookmark.upsert({ where: { podcastId_guestProfileId: { podcastId: data.podcastId, guestProfileId: data.guestProfileId, }, }, create: { podcastId: data.podcastId, guestProfileId: data.guestProfileId, notes: data.notes, }, update: { ...(data.notes !== undefined ? { notes: data.notes } : {}), }, include: { guestProfile: { include: { expertiseTags: true, user: { select: { email: true } }, }, }, }, }); if (!bookmark.guestProfile || !this.isProfileDiscoverable(bookmark.guestProfile)) { throw new common_1.NotFoundException("Guest profile not found"); } await this.syncProfileToPipelines({ podcastId: data.podcastId, profile: bookmark.guestProfile, action: "bookmark", }); return bookmark; } async updateBookmark(userId, id, data) { const bookmark = await this.prisma.networkBookmark.findUnique({ where: { id }, include: { podcast: { select: { workspaceId: true } }, }, }); if (!bookmark) { throw new common_1.NotFoundException("Bookmark not found"); } const membership = await this.prisma.workspaceMember.findFirst({ where: { userId, workspaceId: bookmark.podcast.workspaceId }, }); if (!membership) { throw new common_1.ForbiddenException("Not authorized to update this bookmark"); } return this.prisma.networkBookmark.update({ where: { id }, data: { status: data.status, notes: data.notes, }, }); } async removeBookmark(userId, id) { const bookmark = await this.prisma.networkBookmark.findUnique({ where: { id }, include: { podcast: { select: { workspaceId: true } }, }, }); if (!bookmark) { throw new common_1.NotFoundException("Bookmark not found"); } const membership = await this.prisma.workspaceMember.findFirst({ where: { userId, workspaceId: bookmark.podcast.workspaceId }, }); if (!membership) { throw new common_1.ForbiddenException("Not authorized to remove this bookmark"); } return this.prisma.networkBookmark.delete({ where: { id } }); } async listBookmarks(podcastId, userId, status) { await this.authorizationService.checkPodcastAccess(podcastId, userId); const where = { podcastId }; if (status) where.status = status; return this.prisma.networkBookmark.findMany({ where, include: { guestProfile: { include: { expertiseTags: true }, }, }, orderBy: { createdAt: "desc" }, }); } async checkViewRateLimit(profileId, maxViewsPerMinute = 10) { const result = await this.rateLimiter.checkLimit(profileId, { max: maxViewsPerMinute, windowMs: 60_000, keyPrefix: "network:view", }); return result.allowed; } isValidPhoneNumber(phone) { if (!phone) return true; return /^[\d\s\+\-\(\)]{7,20}$/.test(phone); } async checkDuplicatePendingRequest(fromPodcastId, toProfileId, maxPending = 3) { const existingPendingCount = await this.prisma.networkBookingRequest.count({ where: { fromPodcastId, toProfileId, status: "pending", }, }); if (existingPendingCount >= maxPending) { throw new common_1.ConflictException(`You already have ${existingPendingCount} pending request(s) to this profile. Complete or cancel existing requests first.`); } } async createBookingRequest(data, userId) { await this.authorizationService.checkPodcastAccess(data.fromPodcastId, userId); this.logger.log(`Booking request from podcast ${data.fromPodcastId} to profile ${data.toProfileId}`); const outboundLimit = await this.rateLimiter.checkLimit(`user:${userId}:booking-request`, { max: 20, windowMs: 3_600_000, keyPrefix: "network:booking", }); if (!outboundLimit.allowed) { throw new common_1.BadRequestException("Too many booking requests sent recently. Please wait a while before sending more."); } const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: data.toProfileId }, include: { user: { select: { email: true } } }, }); if (!profile || !this.isProfileDiscoverable(profile)) { throw new common_1.NotFoundException("Guest profile not found"); } const podcast = await this.prisma.podcast.findUnique({ where: { id: data.fromPodcastId }, select: { workspace: { select: { members: { select: { userId: true } } } } }, }); if (podcast?.workspace?.members?.some((m) => m.userId === profile.userId)) { throw new common_1.ForbiddenException("You cannot send a booking request to your own guest profile"); } await this.checkDuplicatePendingRequest(data.fromPodcastId, data.toProfileId); if (data.proposedDates && data.proposedDates.length > 0) { const now = new Date(); for (const dateStr of data.proposedDates) { const date = new Date(dateStr); if (date < now) { throw new common_1.BadRequestException(`Proposed date "${dateStr}" is in the past. All proposed dates must be in the future.`); } } } const request = await this.prisma.networkBookingRequest.create({ data: { fromPodcastId: data.fromPodcastId, toProfileId: data.toProfileId, message: data.message, proposedTopics: data.proposedTopics || [], proposedDates: data.proposedDates || [], }, include: { fromPodcast: { select: { title: true } }, toProfile: { select: { headline: true, visibilitySettings: true, phoneNumber: true, whatsappNumber: true, user: { select: { email: true } }, }, }, }, }); const visibilitySettings = request.toProfile.visibilitySettings || {}; const pii = { email: "", phone: "", whatsapp: "" }; const isEmailHidden = visibilitySettings.email === "hidden" || visibilitySettings.showEmail === false; if (!isEmailHidden) { pii.email = request.toProfile.user.email; } const isPhoneHidden = visibilitySettings.phone === "hidden" || visibilitySettings.showPhone === false; if (!isPhoneHidden) { pii.phone = request.toProfile.phoneNumber || ""; } const isWhatsappHidden = visibilitySettings.whatsapp === "hidden" || visibilitySettings.showPhone === false; if (!isWhatsappHidden) { pii.whatsapp = request.toProfile.whatsappNumber || ""; } await this.prisma.networkBookmark.upsert({ where: { podcastId_guestProfileId: { podcastId: data.fromPodcastId, guestProfileId: data.toProfileId, }, }, create: { podcastId: data.fromPodcastId, guestProfileId: data.toProfileId, status: "contacted", notes: "Auto-created from booking request", }, update: { status: "contacted", }, }); try { await this.syncProfileToPipelines({ podcastId: data.fromPodcastId, profile, action: "request", requestId: request.id, message: data.message, proposedTopics: data.proposedTopics || [], proposedDates: data.proposedDates, }); } catch (syncError) { this.logger.error(`Pipeline sync failed for booking request ${request.id}: ${syncError}`); } await this.networkQueue.add("booking-request.notify", { requestId: request.id, guestEmail: pii.email, guestPhone: pii.phone, guestWhatsapp: pii.whatsapp, podcastTitle: request.fromPodcast.title, message: data.message, }); const { toProfile: _, ...requestData } = request; return { ...requestData, toProfile: { headline: request.toProfile.headline, ...(pii.email ? { email: pii.email } : {}), ...(pii.phone ? { phoneNumber: pii.phone } : {}), ...(pii.whatsapp ? { whatsappNumber: pii.whatsapp } : {}), }, }; } async respondToBookingRequest(requestId, userId, status) { const request = await this.prisma.networkBookingRequest.findUnique({ where: { id: requestId }, include: { toProfile: { select: { userId: true } }, fromPodcast: { select: { id: true, title: true, workspaceId: true }, }, }, }); if (!request) { throw new common_1.NotFoundException("Booking request not found"); } if (request.toProfile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to respond to this request"); } if (request.status !== "pending") { if (request.status === "accepted") { throw new common_1.ConflictException("You have already accepted this booking request"); } if (request.status === "declined") { throw new common_1.ConflictException("You have already declined this booking request"); } if (request.status === "expired") { throw new common_1.ConflictException("This booking request has expired and can no longer be responded to"); } throw new common_1.ConflictException(`Request has status "${request.status}" and cannot be responded to`); } const requestAge = Date.now() - request.createdAt.getTime(); const maxAgeMs = 30 * 24 * 60 * 60 * 1000; if (requestAge > maxAgeMs) { await this.prisma.networkBookingRequest.update({ where: { id: requestId }, data: { status: "expired" }, }); throw new common_1.ConflictException("This booking request has expired (older than 30 days)"); } this.logger.log(`Responding to booking request ${requestId} from userId ${userId}`, { requestId, respondentId: userId, targetStatus: status, }); const transition = await this.prisma.networkBookingRequest.updateMany({ where: { id: requestId, status: "pending" }, data: { status, respondedAt: new Date(), }, }); if (transition.count === 0) { const current = await this.prisma.networkBookingRequest.findUnique({ where: { id: requestId }, select: { status: true }, }); throw new common_1.ConflictException(current?.status === "accepted" ? "You have already accepted this booking request" : current?.status === "declined" ? "You have already declined this booking request" : "This booking request is no longer pending and cannot be responded to"); } const updated = await this.prisma.networkBookingRequest.findUnique({ where: { id: requestId }, }); if (status === "accepted") { await this.prisma.networkBookmark.updateMany({ where: { podcastId: request.fromPodcast.id, guestProfileId: request.toProfileId, }, data: { status: "booked" }, }); await this.networkQueue.add("booking-request.accepted", { requestId: request.id, podcastId: request.fromPodcast.id, profileId: request.toProfileId, }); } await this.networkQueue.add("booking-request.response-notify", { requestId: request.id, status, podcastId: request.fromPodcast.id, }); return updated; } async listBookingRequests(userId, profileId, status) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to view these booking requests"); } const where = { toProfileId: profileId }; if (status) where.status = status; return this.prisma.networkBookingRequest.findMany({ where, include: { fromPodcast: { select: { id: true, title: true } }, }, orderBy: { createdAt: "desc" }, }); } async listSentBookingRequests(userId, podcastId, status) { const membership = await this.prisma.workspaceMember.findFirst({ where: { userId, workspace: { podcasts: { some: { id: podcastId } } }, }, }); if (!membership) { throw new common_1.ForbiddenException("Not authorized to view booking requests for this podcast"); } const where = { fromPodcastId: podcastId }; if (status) where.status = status; return this.prisma.networkBookingRequest.findMany({ where, include: { toProfile: { select: { id: true, vanityUrl: true, avatarUrl: true, headline: true, tier: true, reliabilityScore: true, }, }, }, orderBy: { createdAt: "desc" }, }); } async submitReview(userId, data) { const request = await this.prisma.networkBookingRequest.findUnique({ where: { id: data.bookingRequestId }, include: { fromPodcast: { select: { id: true, workspaceId: true } }, }, }); if (!request || request.status !== "accepted") { throw new common_1.NotFoundException("Accepted booking request not found"); } const hostPodcastId = request.fromPodcast?.id; const reviewerIsHostMember = await this.prisma.workspaceMember.findFirst({ where: { userId: userId, workspace: { podcasts: { some: { id: hostPodcastId } }, }, }, }); if (!reviewerIsHostMember) { throw new common_1.ForbiddenException("Not authorized to review this booking"); } const existingReview = await this.prisma.hostReview.findUnique({ where: { bookingRequestId: data.bookingRequestId }, }); if (existingReview) { throw new common_1.ConflictException("A review has already been submitted for this booking request"); } if (request.toProfileId !== data.profileId) { throw new common_1.BadRequestException("Profile ID does not match the booking request's target profile"); } const review = await this.prisma.hostReview.create({ data: { bookingRequestId: data.bookingRequestId, profileId: data.profileId, contentRating: data.contentRating, prepQuality: data.prepQuality, overallRating: data.overallRating, comment: data.comment, }, }); await this.networkQueue.add("reputation.recalculate", { profileId: data.profileId, trigger: "review", }); return review; } async getPodcastNetworkStats(podcastId, userId) { await this.authorizationService.checkPodcastAccess(podcastId, userId); const [totalBookmarks, sentRequests, acceptedRequests, avgResponseHours,] = await Promise.all([ this.prisma.networkBookmark.count({ where: { podcastId } }), this.prisma.networkBookingRequest.count({ where: { fromPodcastId: podcastId } }), this.prisma.networkBookingRequest.count({ where: { fromPodcastId: podcastId, status: "accepted" }, }), this.prisma.$queryRaw ` SELECT AVG(EXTRACT(EPOCH FROM (responded_at - created_at)) / 3600)::numeric(10,2) as avg_hours FROM network_booking_requests WHERE from_podcast_id = ${podcastId}::uuid AND responded_at IS NOT NULL `, ]); return { totalBookmarks, sentRequests, acceptedRequests, conversionRate: sentRequests > 0 ? (acceptedRequests / sentRequests) * 100 : 0, avgResponseHours: avgResponseHours[0]?.avg_hours || null, }; } async getReputationInsights(userId, profileId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to view reputation insights for this profile"); } return this.reputationEngine.getInsights(profileId); } async recalculateReputation(userId, profileId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to recalculate reputation for this profile"); } return this.reputationEngine.calculate(profileId); } async getRecommendations(userId, profileId, limit = 5) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to view recommendations for this profile"); } return this.graphService.getRecommendations(profileId, limit); } async getProfileNetworkStats(userId, profileId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, select: { userId: true }, }); if (!profile) { throw new common_1.NotFoundException("Profile not found"); } if (profile.userId !== userId) { throw new common_1.ForbiddenException("Not authorized to view network stats for this profile"); } return this.graphService.getNetworkStats(profileId); } async verifyProfile(adminUserId, profileId, status) { await (0, platform_admin_1.assertPlatformAdmin)(this.prisma, adminUserId); const updated = await this.prisma.guestPublicProfile.update({ where: { id: profileId }, data: { verificationStatus: status, isPublic: status === "basic" ? false : true, }, }); if (this.isProfileDiscoverable(updated)) { await this.networkQueue.add("search.index-profile", { profileId: updated.id }); } else { await this.networkQueue.add("search.remove-profile", { profileId: updated.id }); } return updated; } async checkAutoVerification(profileId) { const profile = await this.prisma.guestPublicProfile.findUnique({ where: { id: profileId }, include: { bookingHistory: true, hostReviews: true, }, }); if (!profile) return; if (profile.verificationStatus === "basic" && profile.bookingHistory.length >= 3 && profile.averageRating.toNumber() >= 4.5) { const updated = await this.prisma.guestPublicProfile.update({ where: { id: profileId }, data: { verificationStatus: "verified", isPublic: true, }, }); await this.meilisearch.indexProfile(updated); this.logger.log(`Profile ${profileId} auto-verified to VERIFIED tier`); } } async getNetworkHealth() { const [totalProfiles, publicProfiles, verifiedProfiles, featuredProfiles, totalBookings, acceptedBookings, totalReviews, avgRatingResult, badgeDistribution, trustScoreStats,] = await Promise.all([ this.prisma.guestPublicProfile.count(), this.prisma.guestPublicProfile.count({ where: { isPublic: true } }), this.prisma.guestPublicProfile.count({ where: { verificationStatus: "verified" } }), this.prisma.guestPublicProfile.count({ where: { verificationStatus: "featured" } }), this.prisma.networkBookingRequest.count(), this.prisma.networkBookingRequest.count({ where: { status: "accepted" } }), this.prisma.hostReview.count(), this.prisma.guestPublicProfile.aggregate({ _avg: { averageRating: true }, }), this.prisma.guestPublicProfile.findMany({ select: { verificationBadges: true }, }), this.prisma.trustScore.aggregate({ _avg: { score: true }, _min: { score: true }, _max: { score: true }, _count: true, }), ]); const badgeCounts = { linkedin: 0, email: 0, podcast_link: 0, identity: 0, website: 0, }; for (const profile of badgeDistribution) { const badges = (profile.verificationBadges ?? []); for (const badge of badges) { if (badgeCounts[badge] !== undefined) { badgeCounts[badge]++; } } } return { profiles: { total: totalProfiles, public: publicProfiles, verified: verifiedProfiles, featured: featuredProfiles, basic: totalProfiles - verifiedProfiles - featuredProfiles, }, bookings: { total: totalBookings, accepted: acceptedBookings, acceptanceRate: totalBookings > 0 ? acceptedBookings / totalBookings : 0, }, reviews: { total: totalReviews, averageRating: avgRatingResult._avg.averageRating?.toNumber?.() ?? Number(avgRatingResult._avg.averageRating || 0), }, badgeDistribution: badgeCounts, trustScore: { average: trustScoreStats._avg.score?.toNumber?.() ?? Number(trustScoreStats._avg.score || 0), min: trustScoreStats._min.score?.toNumber?.() ?? Number(trustScoreStats._min.score || 0), max: trustScoreStats._max.score?.toNumber?.() ?? Number(trustScoreStats._max.score || 0), computedCount: trustScoreStats._count, }, }; } }; exports.NetworkService = NetworkService; exports.NetworkService = NetworkService = NetworkService_1 = __decorate([ (0, common_1.Injectable)(), __param(6, (0, bullmq_1.InjectQueue)("network")), __metadata("design:paramtypes", [prisma_service_1.PrismaService, authorization_service_1.AuthorizationService, redis_rate_limiter_service_1.RedisRateLimiterService, meilisearch_service_1.MeilisearchService, reputation_service_1.ReputationEngine, graph_service_1.GraphService, bullmq_2.Queue]) ], NetworkService); //# sourceMappingURL=network.service.js.map
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var NetworkService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NetworkService = void 0;
const common_1 = require("@nestjs/common");
const bullmq_1 = require("@nestjs/bullmq");
const bullmq_2 = require("bullmq");
const crypto_1 = require("crypto");
const prisma_service_1 = require("../prisma/prisma.service");
const authorization_service_1 = require("../common/authorization.service");
const platform_admin_1 = require("../common/platform-admin");
const redis_rate_limiter_service_1 = require("../common/redis-rate-limiter.service");
const shared_types_1 = require("@micprotocol/shared-types");
const meilisearch_service_1 = require("./meilisearch.service");
const reputation_service_1 = require("./reputation.service");
const graph_service_1 = require("./graph.service");
let NetworkService = NetworkService_1 = class NetworkService {
prisma;
authorizationService;
rateLimiter;
meilisearch;
reputationEngine;
graphService;
networkQueue;
logger = new common_1.Logger(NetworkService_1.name);
allowedVerificationStatuses = ["verified", "featured"];
constructor(prisma, authorizationService, rateLimiter, meilisearch, reputationEngine, graphService, networkQueue) {
this.prisma = prisma;
this.authorizationService = authorizationService;
this.rateLimiter = rateLimiter;
this.meilisearch = meilisearch;
this.reputationEngine = reputationEngine;
this.graphService = graphService;
this.networkQueue = networkQueue;
}
slugify(text) {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/[\s_]+/g, "-")
.replace(/-+/g, "-")
.substring(0, 60);
}
async generateVanityUrl(name) {
const base = this.slugify(name);
const existing = await this.prisma.guestPublicProfile.findUnique({ where: { vanityUrl: base } });
if (!existing) {
return base;
}
const suffix = (0, crypto_1.createHash)("sha256").update(`${base}-${Date.now()}`).digest("hex").substring(0, 8);
return `${base}-${suffix}`;
}
isVerificationEligible(status) {
return status === "verified" || status === "featured";
}
isProfileDiscoverable(profile) {
return profile.isPublic && this.isVerificationEligible(profile.verificationStatus);
}
async createProfile(userId, data) {
this.logger.log(`Creating guest public profile for user ${userId}`);
const existing = await this.prisma.guestPublicProfile.findUnique({
where: { userId },
});
if (existing) {
throw new common_1.ConflictException("User already has a public profile");
}
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new common_1.NotFoundException("User not found");
}
const displayName = user.profile?.fullName || user.email.split("@")[0];
let profile = null;
let attempt = 0;
while (!profile && attempt < 5) {
attempt++;
const baseVanity = await this.generateVanityUrl(displayName);
const vanityUrl = baseVanity +
(attempt > 1 ? `-${attempt}` : "");
try {
profile = await this.prisma.guestPublicProfile.create({
data: {
userId,
vanityUrl,
isPublic: false,
headline: data.headline,
fullBio: data.fullBio,
country: data.country,