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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Retailer, RetailerDocument } from '../../../database/schemas/retailer.schema'; import { Commission, CommissionDocument } from '../../../database/schemas/commission.schema'; import { AffiliateLink, AffiliateLinkDocument } from '../../../database/schemas/affiliate-link.schema'; export interface PartnershipProposal { retailerName: string; contactEmail: string; website: string; description: string; categories: string[]; proposedCommissionRates: Array<{ category: string; rate: number; }>; minimumPayout: number; paymentTerms: string; apiAvailable: boolean; expectedVolume: string; } export interface PartnershipMetrics { retailerId: string; retailerName: string; totalRevenue: number; totalCommissions: number; totalOrders: number; conversionRate: number; averageOrderValue: number; topProducts: Array<{ productId: string; title: string; revenue: number; orders: number; }>; monthlyTrends: Array<{ month: string; revenue: number; orders: number; commissions: number; }>; performance: { responseTime: number; uptime: number; customerSatisfaction: number; }; } @Injectable() export class PartnershipService { private readonly logger = new Logger(PartnershipService.name); constructor( @InjectModel(Retailer.name) private retailerModel: Model<RetailerDocument>, @InjectModel(Commission.name) private commissionModel: Model<CommissionDocument>, @InjectModel(AffiliateLink.name) private affiliateLinkModel: Model<AffiliateLinkDocument>, ) {} async submitPartnershipProposal(proposal: PartnershipProposal): Promise<{ success: boolean; message: string; proposalId?: string; }> { try { // Check if retailer already exists const existingRetailer = await this.retailerModel.findOne({ $or: [ { website: proposal.website }, { name: proposal.retailerName }, ], }); Iif (existingRetailer) { return { success: false, message: 'A partnership with this retailer already exists or is pending', }; } // Create new retailer entry with pending status const retailer = new this.retailerModel({ name: proposal.retailerName, displayName: proposal.retailerName, website: proposal.website, description: proposal.description, regions: ['UAE'], // Default to UAE, can be updated later categories: proposal.categories, commissionRates: proposal.proposedCommissionRates.map(rate => ({ ...rate, currency: 'AED', tier: 'standard', })), paymentTerms: { frequency: proposal.paymentTerms, minimumPayout: proposal.minimumPayout, currency: 'AED', }, apiConfig: { endpoint: '', apiKey: '', rateLimits: { requestsPerMinute: 60, requestsPerDay: 10000, }, lastSync: new Date(), isActive: false, }, performance: { conversionRate: 0, averageOrderValue: 0, customerSatisfaction: 0, responseTime: 0, }, status: 'pending', createdAt: new Date(), updatedAt: new Date(), }); await retailer.save(); // Log the proposal for review this.logger.log(`New partnership proposal submitted: ${proposal.retailerName}`); return { success: true, message: 'Partnership proposal submitted successfully. We will review and contact you within 5 business days.', proposalId: retailer._id.toString(), }; } catch (error) { this.logger.error('Error submitting partnership proposal', error); return { success: false, message: 'Failed to submit partnership proposal. Please try again.', }; } } async approvePartnership( retailerId: string, approvalData: { apiEndpoint?: string; apiKey?: string; finalCommissionRates?: Array<{ category: string; rate: number; tier: string; }>; notes?: string; }, ): Promise<RetailerDocument> { try { const retailer = await this.retailerModel.findById(retailerId); Iif (!retailer) { throw new Error('Retailer not found'); } const updateData: any = { status: 'active', updatedAt: new Date(), }; Iif (approvalData.apiEndpoint) { updateData['apiConfig.endpoint'] = approvalData.apiEndpoint; updateData['apiConfig.isActive'] = true; } Iif (approvalData.apiKey) { updateData['apiConfig.apiKey'] = approvalData.apiKey; } Iif (approvalData.finalCommissionRates) { updateData.commissionRates = approvalData.finalCommissionRates; } const updatedRetailer = await this.retailerModel.findByIdAndUpdate( retailerId, updateData, { new: true } ); this.logger.log(`Approved partnership with retailer: ${retailer.name}`); return updatedRetailer!; } catch (error) { this.logger.error(`Error approving partnership for retailer ${retailerId}`, error); throw error; } } async getPartnershipMetrics(retailerId: string): Promise<PartnershipMetrics> { try { const retailer = await this.retailerModel.findById(retailerId); Iif (!retailer) { throw new Error('Retailer not found'); } const [commissions, affiliateLinks] = await Promise.all([ this.commissionModel.find({ retailerId }).populate('productId'), this.affiliateLinkModel.find({ retailerId }).populate('productId'), ]); const totalRevenue = commissions.reduce((sum, c) => sum + c.orderValue, 0); const totalCommissions = commissions.reduce((sum, c) => sum + c.commissionAmount, 0); const totalOrders = commissions.length; const totalClicks = affiliateLinks.reduce((sum, link) => sum + link.metrics.clicks, 0); const conversionRate = totalClicks > 0 ? (totalOrders / totalClicks) * 100 : 0; const averageOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0; // Top products const productPerformance = new Map(); commissions.forEach(c => { const product = c.productId as any; const existing = productPerformance.get(product._id.toString()) || { productId: product._id.toString(), title: product.title, revenue: 0, orders: 0, }; existing.revenue += c.orderValue; existing.orders += 1; productPerformance.set(product._id.toString(), existing); }); const topProducts = Array.from(productPerformance.values()) .sort((a: any, b: any) => b.revenue - a.revenue) .slice(0, 5); // Monthly trends const monthlyTrends = this.calculateMonthlyTrends(commissions); return { retailerId: retailer._id.toString(), retailerName: retailer.name, totalRevenue, totalCommissions, totalOrders, conversionRate, averageOrderValue, topProducts, monthlyTrends, performance: { responseTime: retailer.performance.responseTime, uptime: 99.5, // This would come from monitoring customerSatisfaction: retailer.performance.customerSatisfaction, }, }; } catch (error) { this.logger.error(`Error getting partnership metrics for retailer ${retailerId}`, error); throw error; } } async getAllPartnershipMetrics(): Promise<PartnershipMetrics[]> { try { const activeRetailers = await this.retailerModel.find({ status: 'active' }); const metricsPromises = activeRetailers.map(retailer => this.getPartnershipMetrics(retailer._id.toString()) ); return await Promise.all(metricsPromises); } catch (error) { this.logger.error('Error getting all partnership metrics', error); return []; } } async updatePartnershipTerms( retailerId: string, updates: { commissionRates?: Array<{ category: string; rate: number; tier: string; }>; paymentTerms?: { frequency: string; minimumPayout: number; }; apiConfig?: { endpoint: string; rateLimits: { requestsPerMinute: number; requestsPerDay: number; }; }; }, ): Promise<RetailerDocument> { try { const updateData: any = { updatedAt: new Date(), }; Iif (updates.commissionRates) { updateData.commissionRates = updates.commissionRates; } Iif (updates.paymentTerms) { updateData['paymentTerms.frequency'] = updates.paymentTerms.frequency; updateData['paymentTerms.minimumPayout'] = updates.paymentTerms.minimumPayout; } Iif (updates.apiConfig) { updateData['apiConfig.endpoint'] = updates.apiConfig.endpoint; updateData['apiConfig.rateLimits'] = updates.apiConfig.rateLimits; } const updatedRetailer = await this.retailerModel.findByIdAndUpdate( retailerId, updateData, { new: true } ); Iif (!updatedRetailer) { throw new Error('Retailer not found'); } this.logger.log(`Updated partnership terms for retailer: ${updatedRetailer.name}`); return updatedRetailer; } catch (error) { this.logger.error(`Error updating partnership terms for retailer ${retailerId}`, error); throw error; } } async suspendPartnership( retailerId: string, reason: string, ): Promise<RetailerDocument> { try { const updatedRetailer = await this.retailerModel.findByIdAndUpdate( retailerId, { status: 'inactive', 'apiConfig.isActive': false, updatedAt: new Date(), }, { new: true } ); Iif (!updatedRetailer) { throw new Error('Retailer not found'); } this.logger.log(`Suspended partnership with retailer: ${updatedRetailer.name}, Reason: ${reason}`); return updatedRetailer; } catch (error) { this.logger.error(`Error suspending partnership for retailer ${retailerId}`, error); throw error; } } async getPartnershipHealth(): Promise<{ totalPartners: number; activePartners: number; pendingPartners: number; totalRevenue: number; totalCommissions: number; averageConversionRate: number; topPerformingPartners: Array<{ name: string; revenue: number; conversionRate: number; }>; }> { try { const [retailers, commissions, affiliateLinks] = await Promise.all([ this.retailerModel.find(), this.commissionModel.find(), this.affiliateLinkModel.find(), ]); const totalPartners = retailers.length; const activePartners = retailers.filter(r => r.status === 'active').length; const pendingPartners = retailers.filter(r => r.status === 'pending').length; const totalRevenue = commissions.reduce((sum, c) => sum + c.orderValue, 0); const totalCommissions = commissions.reduce((sum, c) => sum + c.commissionAmount, 0); const totalClicks = affiliateLinks.reduce((sum, link) => sum + link.metrics.clicks, 0); const totalConversions = commissions.length; const averageConversionRate = totalClicks > 0 ? (totalConversions / totalClicks) * 100 : 0; // Calculate top performing partners const partnerPerformance = new Map(); commissions.forEach(c => { const retailerId = c.retailerId.toString(); const existing = partnerPerformance.get(retailerId) || { retailerId, revenue: 0, orders: 0, }; existing.revenue += c.orderValue; existing.orders += 1; partnerPerformance.set(retailerId, existing); }); const topPerformingPartners = []; for (const [retailerId, performance] of partnerPerformance.entries()) { const retailer = retailers.find(r => r._id.toString() === retailerId); Iif (retailer) { const retailerLinks = affiliateLinks.filter(link => link.retailerId.toString() === retailerId ); const retailerClicks = retailerLinks.reduce((sum, link) => sum + link.metrics.clicks, 0); const conversionRate = retailerClicks > 0 ? (performance.orders / retailerClicks) * 100 : 0; topPerformingPartners.push({ name: retailer.name, revenue: performance.revenue, conversionRate, }); } } topPerformingPartners.sort((a, b) => b.revenue - a.revenue); return { totalPartners, activePartners, pendingPartners, totalRevenue, totalCommissions, averageConversionRate, topPerformingPartners: topPerformingPartners.slice(0, 5), }; } catch (error) { this.logger.error('Error getting partnership health', error); throw error; } } private calculateMonthlyTrends(commissions: CommissionDocument[]): Array<{ month: string; revenue: number; orders: number; commissions: number; }> { const monthlyMap = new Map<string, { revenue: number; orders: number; commissions: number }>(); commissions.forEach(c => { const month = c.orderDate.toISOString().substring(0, 7); // YYYY-MM format const existing = monthlyMap.get(month) || { revenue: 0, orders: 0, commissions: 0 }; existing.revenue += c.orderValue; existing.orders += 1; existing.commissions += c.commissionAmount; monthlyMap.set(month, existing); }); return Array.from(monthlyMap.entries()) .map(([month, data]) => ({ month, ...data })) .sort((a, b) => a.month.localeCompare(b.month)) .slice(-12); // Last 12 months } } |