Eneza API Services
The API contains 65+ service files handling all business logic. Services are organized by domain and follow a class-based pattern.
Core Business Services
AdService (adService.ts)
Manages ad campaigns for advertisers.
class AdService {
// Calculate campaign pricing based on tier
async calculatePricingForCampaign(amountUsd: number, countryCode: string): Promise<PricingCalculation>
// Validate minimum budget
async validateMinimumBudget(amountUsd: number, countryCode: string): Promise<void>
// Create new ad campaign
async createAd(advertiserId: string, adData: CreateAdData): Promise<Ad>
// Get ads matching user demographics
async getAdsForUser(userId: string, page: number, limit: number): Promise<Ad[]>
// Get advertiser's campaigns
async getAdsByAdvertiser(advertiserId: string, filters: AdFilters): Promise<Ad[]>
// Update ad status (approve, reject, pause)
async updateAdStatus(adId: string, status: AdStatus, reason?: string): Promise<Ad>
// Calculate and update delivered views
async incrementDeliveredViews(adId: string, views: number): Promise<void>
// Process refunds for underdelivered campaigns
async processRefund(adId: string): Promise<void>
}Key Features:
- USD-based tiered pricing
- Demographic filtering (age, gender, country, city)
- Soft delete support
- Video variant management
- Campaign lifecycle management
SubscriptionService (subscriptionService.ts)
Handles user subscriptions to ads.
class SubscriptionService {
// Create subscription (user downloads ad)
async createSubscription(data: SubscriptionRequestData): Promise<Subscription>
// Select best video variant for device
selectVideoVariant(ad: Ad, displayWidth: number, displayHeight: number): string
// Get user's active subscriptions
async getUserSubscriptions(userId: string): Promise<Subscription[]>
// Update subscription status after screenshot
async updateSubscriptionStatus(id: string, status: SubscriptionStatus): Promise<void>
// Send screenshot reminder
async sendScreenshotReminder(subscriptionId: string): Promise<void>
}
// Video variant selection based on device
function selectVideoVariant(ad: Ad, displayWidth: number, displayHeight: number): string {
const variants = ad.videoVariants; // { '1080p': {...}, '720p': {...}, '480p': {...} }
const deviceMax = Math.max(displayWidth, displayHeight);
// Returns best variant that doesn't exceed device resolution
}ScreenshotService (screenshotService.ts)
Manages screenshot submissions and verification.
class ScreenshotService {
// Create screenshot record
async createScreenshot(screenshotData: CreateScreenshotData): Promise<Screenshot>
// Mark as verified (after AI verification)
async markScreenshotAsVerified(screenshotId: string): Promise<Screenshot>
// Mark as failed with reason
async markScreenshotAsFailed(screenshotId: string, reason: string): Promise<Screenshot>
// Get screenshots by ad (for admin review)
async getScreenshotsByAd(adId: string, page: number, limit: number): Promise<PaginatedScreenshots>
// Mark as paid
async markScreenshotAsPaid(screenshotId: string): Promise<void>
}UserService (userService.ts)
User management and profile operations.
class UserService {
// Get user with relations
async getUserById(userId: string): Promise<UserWithRelations | null>
// Validate user data for country
async validateUserForCountry(userData: any, countryId: string): Promise<ValidationResult>
// Create new user
async createUser(userData: CreateUserData): Promise<User>
// Update user profile
async updateUser(userId: string, updateData: UpdateUserData): Promise<User>
// Get user earnings balance
async getUserBalance(userId: string): Promise<{ balance: number; currency: string }>
// Check if user can withdraw
async canWithdraw(userId: string, amount: number): Promise<{ allowed: boolean; reason?: string }>
}AdvertiserService (advertiserService.ts)
Advertiser account management.
class AdvertiserService {
// Get advertiser profile
async getAdvertiserById(id: string): Promise<Advertiser | null>
// Update advertiser
async updateAdvertiser(id: string, data: UpdateAdvertiserData): Promise<Advertiser>
// Credit advertiser balance (after Stripe payment)
async creditBalance(advertiserId: string, amountUsd: number): Promise<void>
// Deduct balance for campaign
async deductBalance(advertiserId: string, amountUsd: number): Promise<void>
// Get advertiser balance
async getBalance(advertiserId: string): Promise<{ usdBalance: number }>
}Financial Services
PricingService (pricingService.ts)
Database-driven pricing calculations.
class PricingService {
// Get pricing tier for country
async getTierForCountry(countryCode: string): Promise<PricingTier | null>
// Calculate pricing for campaign
async calculatePricing(amountUsd: number, countryCode: string): Promise<PricingCalculation>
// Get minimum budget for country
async getMinimumBudget(countryCode: string): Promise<number>
// Calculate poster payout for views
async calculatePosterPayout(countryCode: string, verifiedViews: number): Promise<number>
// Get all tiers with countries
async getAllTiers(): Promise<TierWithCountries[]>
}
// Pricing calculation result
interface PricingCalculation {
amountUsd: number;
guaranteedViews: number; // (amountUsd / cpm) * 1000
estimatedViews: number; // guaranteedViews * 1.25 (25% buffer)
effectiveCpm: number;
pricingTierId: string;
tierName: string;
minimumBudget: number;
}InvoiceService (invoiceService.ts)
Invoice generation and management.
class InvoiceService {
// Generate invoice for campaign
async createInvoice(advertiserId: string, adId: string, amountUsd: number): Promise<Invoice>
// Generate PDF invoice
async generatePdfInvoice(invoiceId: string): Promise<Buffer>
// Mark invoice as paid
async markAsPaid(invoiceId: string, paymentReference: string): Promise<Invoice>
// Send invoice via email
async sendInvoiceEmail(invoiceId: string): Promise<void>
// Get invoices for advertiser
async getAdvertiserInvoices(advertiserId: string): Promise<Invoice[]>
}TransactionService (transactionService.ts)
User payout transactions.
class TransactionService {
// Create withdrawal request
async createWithdrawal(userId: string, amount: number, paymentMethodId: string): Promise<Transaction>
// Process withdrawal (admin)
async processWithdrawal(transactionId: string, status: 'paid' | 'cancelled'): Promise<Transaction>
// Get user transactions
async getUserTransactions(userId: string, type?: TransactionType): Promise<Transaction[]>
// Credit user for verified views
async creditUserForViews(userId: string, adId: string, views: number, payoutAmount: number): Promise<void>
}ExchangeRateService (exchangeRateService.ts)
Currency conversion using Swychr API.
class ExchangeRateService {
// Initialize rates from DB
async initialize(): Promise<void>
// Refresh rates from external API
async refreshRates(): Promise<void>
// Convert USD to local currency
async convertFromUsd(amountUsd: number, currencyCode: string): Promise<number>
// Get rate for currency
async getRate(currencyCode: string): Promise<{ rate: number; source: string }>
// Check if refresh needed (>24h old)
needsRefresh(): boolean
}Notification Services
MessagingService (messagingService.ts)
Unified message broker interface.
class MessagingService {
// Publish to any topic
async publish(topic: string, data: any, attributes?: Record<string, string>): Promise<void>
// Subscribe to topic
async subscribe(topic: string, handler: MessageHandler): Promise<void>
// Get broker type
getBrokerType(): 'pubsub' | 'rabbitmq' | 'inmemory'
}
// Topics
const TOPICS = {
VIDEO_PROCESSING: 'video-processing',
VIDEO_PROCESSED: 'video-processed',
SCREENSHOT_VERIFY: 'screenshot-verify',
SCREENSHOT_PROCESSED: 'screenshot-processed',
PUSH_NOTIFICATION: 'push-notification',
WHATSAPP_MESSAGE: 'whatsapp-message',
EMAIL_VERIFICATION: 'email-verification',
INVOICE_EMAIL: 'invoice-email',
PAYMENT_REMINDER: 'payment-reminder',
AD_LIVE: 'ad-live',
AD_REJECTED: 'ad-rejected',
ADVERTISER_DRIP_EMAIL: 'advertiser-drip-email',
};PushNotificationService (pushNotificationService.ts)
Firebase Cloud Messaging integration.
class PushNotificationService {
// Send push notification
async send(deviceToken: string, title: string, body: string, data?: object): Promise<void>
// Send to multiple devices
async sendMulticast(deviceTokens: string[], title: string, body: string, data?: object): Promise<void>
// Register device token
async registerToken(userId: string, token: string, platform: 'android' | 'ios'): Promise<void>
// Remove invalid token
async removeToken(token: string): Promise<void>
}BroadcastNotificationService (broadcastNotificationService.ts)
Bulk notification broadcasts.
class BroadcastNotificationService {
// Send broadcast to users matching criteria
async sendBroadcast(broadcast: NotificationBroadcast): Promise<BroadcastResult>
// Schedule broadcast
async scheduleBroadcast(broadcast: NotificationBroadcast, scheduledAt: Date): Promise<void>
// Process scheduled broadcasts
async processScheduledBroadcasts(): Promise<void>
}Auth Services
AuthService (authService.ts)
User authentication (phone + OTP).
class AuthService {
// Request OTP
async requestOtp(phoneNumber: string, countryId: string): Promise<{ success: boolean }>
// Verify OTP and create session
async verifyOtp(phoneNumber: string, code: string): Promise<{ user: User; token: string }>
// Generate referral code
async generateReferralCode(): Promise<string>
// Process referral on signup
async processReferral(userId: string, referralCode: string): Promise<void>
}AdminAuthService (adminAuthService.ts)
Admin authentication and role management.
class AdminAuthService {
// Login
async login(email: string, password: string): Promise<{ admin: AdminUser; token: string }>
// Create admin invitation
async createInvitation(email: string, role: AdminRole, invitedById: string): Promise<string>
// Accept invitation
async acceptInvitation(token: string, password: string, fullName: string): Promise<AdminUser>
// Seed initial admin
static async seedInitialAdmin(): Promise<void>
// Update permissions
async updatePermissions(adminId: string, permissions: string[]): Promise<void>
}PermissionService (permissionService.ts)
Role-based access control.
const ADMIN_ROLES = {
SUPER_ADMIN: ['*'], // All permissions
MODERATOR: ['ads:read', 'ads:moderate', 'screenshots:review'],
SUPPORT_AGENT: ['users:read', 'tickets:manage'],
FINANCE: ['transactions:manage', 'invoices:manage'],
};
class PermissionService {
// Check if admin has permission
hasPermission(admin: AdminUser, permission: string): boolean
// Get all permissions for role
getPermissionsForRole(role: AdminRole): string[]
// Get custom permissions
getEffectivePermissions(admin: AdminUser): string[]
}Fraud Detection Services
GeoVerificationService (geoVerificationService.ts)
IP-based location verification.
class GeoVerificationService {
// Verify user location matches target
async verifyLocation(userId: string, targetCountry: string, eventType: string): Promise<GeoVerificationResult>
// Check for VPN/proxy
async detectVpn(asn: number): Promise<boolean>
// Log verification event
async logVerification(data: GeoVerificationData): Promise<void>
}OtpFraudDetectionService (otpFraudDetectionService.ts)
Prevents OTP abuse.
class OtpFraudDetectionService {
// Check if can send OTP
async canSendOtp(phoneNumber: string): Promise<{ allowed: boolean; reason?: string }>
// Record OTP attempt
async recordAttempt(phoneNumber: string, success: boolean): Promise<void>
// Check lockout status
async isLockedOut(phoneNumber: string): Promise<boolean>
}Other Services
VideoProcessingService (videoProcessingService.ts)
Coordinates video processing jobs.
class VideoProcessingService {
// Submit video for processing
async submitForProcessing(adId: string, videoUrl: string): Promise<string>
// Handle processing completion
async handleProcessingComplete(adId: string, processedUrl: string): Promise<void>
// Handle processing failure
async handleProcessingFailure(adId: string, error: string): Promise<void>
}ReferralService (referralService.ts)
Referral program management.
class ReferralService {
// Process new referral
async processReferral(referrerId: string, refereeId: string, referralCode: string): Promise<void>
// Credit referral bonus
async creditReferralBonus(referralId: string): Promise<void>
// Get referral stats
async getReferralStats(userId: string): Promise<ReferralStats>
// Update referral tier
async updateUserTier(userId: string): Promise<void>
}AchievementService (achievementService.ts)
Gamification achievements.
class AchievementService {
// Check and unlock achievements
async checkAchievements(userId: string): Promise<Achievement[]>
// Credit achievement bonus
async creditAchievementBonus(userId: string, achievementId: string): Promise<void>
// Get user achievements
async getUserAchievements(userId: string): Promise<UserAchievement[]>
}StreakService (streakService.ts)
Daily activity streaks.
class StreakService {
// Update user streak
async updateStreak(userId: string): Promise<UserStreak>
// Check streak expiry
async checkStreakExpiry(userId: string): Promise<boolean>
// Award streak bonus
async awardStreakBonus(userId: string, streakDays: number): Promise<void>
}