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 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { UserSavings, UserSavingsDocument } from '../../../database/schemas/user-savings.schema'; export interface SavingsGoal { id: string; userId: string; targetAmount: number; currentAmount: number; period: 'weekly' | 'monthly' | 'quarterly' | 'yearly' | 'custom'; deadline: Date; description?: string; category?: string; status: 'active' | 'completed' | 'paused' | 'cancelled'; progress: number; // percentage milestones: Array<{ amount: number; achieved: boolean; achievedAt?: Date; reward?: string; }>; createdAt: Date; updatedAt: Date; } @Injectable() export class GoalsService { private readonly logger = new Logger(GoalsService.name); constructor( @InjectModel(UserSavings.name) private userSavingsModel: Model<UserSavingsDocument>, ) {} async createGoal(goalData: Omit<SavingsGoal, 'id' | 'currentAmount' | 'progress' | 'status' | 'milestones' | 'createdAt' | 'updatedAt'>): Promise<SavingsGoal> { try { const goal: SavingsGoal = { ...goalData, id: `goal_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, currentAmount: 0, progress: 0, status: 'active', milestones: this.generateMilestones(goalData.targetAmount), createdAt: new Date(), updatedAt: new Date(), }; // Add goal to user savings const userSavings = await this.userSavingsModel.findOne({ userId: goalData.userId }); Iif (userSavings) { userSavings.goals.push({ targetAmount: goal.targetAmount, period: goal.period === 'weekly' || goal.period === 'quarterly' || goal.period === 'custom' ? 'monthly' : goal.period, progress: goal.progress, deadline: goal.deadline, achieved: false, reward: goal.description || '', }); await userSavings.save(); } this.logger.log(`Created savings goal for user ${goalData.userId}: ${goal.targetAmount} AED`); return goal; } catch (error) { this.logger.error('Error creating savings goal', error); throw error; } } async updateGoalProgress(userId: string, savingsAmount: number): Promise<void> { try { const userSavings = await this.userSavingsModel.findOne({ userId }); Iif (!userSavings) return; // Update progress for all active goals for (const goal of userSavings.goals) { Iif (!goal.achieved && goal.deadline > new Date()) { // Calculate progress based on period let relevantSavings = 0; switch (goal.period) { case 'monthly': relevantSavings = userSavings.monthlySaved; break; case 'yearly': relevantSavings = userSavings.yearToDateSaved; break; default: relevantSavings = userSavings.totalSaved; } goal.progress = Math.min((relevantSavings / goal.targetAmount) * 100, 100); // Check if goal is achieved Iif (goal.progress >= 100 && !goal.achieved) { goal.achieved = true; this.logger.log(`Goal achieved for user ${userId}: ${goal.targetAmount} AED`); // Award achievement points userSavings.achievements.push({ type: 'goal_achieved', title: 'Goal Crusher', description: `Achieved savings goal of ${goal.targetAmount} AED`, earnedAt: new Date(), points: Math.floor(goal.targetAmount / 10), // 1 point per 10 AED badge: 'goal-crusher', }); } } } await userSavings.save(); } catch (error) { this.logger.error(`Error updating goal progress for user ${userId}`, error); } } private generateMilestones(targetAmount: number): SavingsGoal['milestones'] { const milestones = []; const milestonePercentages = [25, 50, 75, 100]; for (const percentage of milestonePercentages) { milestones.push({ amount: (targetAmount * percentage) / 100, achieved: false, reward: this.getMilestoneReward(percentage), }); } return milestones; } private getMilestoneReward(percentage: number): string { switch (percentage) { case 25: return '25 bonus points'; case 50: return '50 bonus points + Bronze badge'; case 75: return '75 bonus points + Silver badge'; case 100: return '100 bonus points + Gold badge + Special discount'; default: return 'Bonus points'; } } } |