Spaces:
Sleeping
Sleeping
File size: 15,566 Bytes
4433399 da13799 068485b 1a7e978 ee79726 068485b da13799 6469525 7fe61c9 6469525 ee79726 068485b ee79726 6469525 068485b da13799 1a7e978 ee79726 068485b ee79726 068485b 1a7e978 ee79726 068485b ee79726 068485b 7fe61c9 25f925e 068485b da13799 068485b da13799 b8cc5e6 da13799 7fe61c9 b8cc5e6 7fe61c9 25f925e 7fe61c9 b8cc5e6 7fe61c9 ec76476 7fe61c9 b8cc5e6 7fe61c9 b8cc5e6 7fe61c9 6469525 068485b ee79726 25f925e ee79726 068485b 25f925e ee79726 068485b ee79726 068485b 25f925e 6469525 ec76476 6469525 068485b 6469525 068485b 1a7e978 ee79726 6469525 068485b ee79726 6469525 ee79726 6469525 798b4ec 6469525 798b4ec 6469525 ee79726 7fe61c9 068485b 798b4ec 7fe61c9 068485b ec76476 6469525 ec76476 068485b 6469525 068485b | 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 | using LibraryManagement.Shared.Models;
using DbConnect.Data;
using DbConnect.Entities;
using Microsoft.EntityFrameworkCore;
using Backend.Features.Loyalty;
using Backend.Features.Wallet;
namespace Backend.Features.Subscriptions
{
public interface ISubscriptionService
{
Task<IEnumerable<MembershipDto>> GetMembershipsAsync();
Task<SubscriptionDto?> GetUserSubscriptionAsync(Guid userId);
Task<IEnumerable<SubscriptionDto>> GetUserAllSubscriptionsAsync(Guid userId);
Task<bool> HandleLoyaltyRedemptionAsync(Guid userId, string rewardId, string rewardName, string redemptionId);
Task<SubscriptionDto> SubscribeUserAsync(Guid userId, int membershipId, string? redemptionId = null, string status = "Active", string paymentMethod = "Cash");
Task<IEnumerable<SubscriptionDto>> GetAllSubscriptionsAsync();
Task<IEnumerable<SubscriptionDto>> GetPendingSubscriptionsAsync();
Task<SubscriptionDto> CreatePendingSubscriptionAsync(Guid userId, int membershipId);
Task<bool> ApproveSubscriptionAsync(Guid subscriptionId, bool approve);
Task<SubscriptionUpgradePreviewDto> GetUpgradePreviewAsync(Guid userId, int newMembershipId);
Task<SubscriptionDto> SubscribeWithWalletAsync(Guid userId, int membershipId);
}
public class SubscriptionService : ISubscriptionService
{
private readonly AppDbContext _context;
private readonly ILoyaltyService _loyaltyService;
private readonly IWalletService _walletService;
public SubscriptionService(AppDbContext context, ILoyaltyService loyaltyService, IWalletService walletService)
{
_context = context;
_loyaltyService = loyaltyService;
_walletService = walletService;
}
public async Task<IEnumerable<MembershipDto>> GetMembershipsAsync()
{
return await _context.Memberships
.Select(m => new MembershipDto
{
Id = m.Id,
Type = m.Type,
MaxBooks = m.MaxBooks,
BorrowingDays = m.BorrowingDays,
Price = m.Price,
DurationMonths = m.DurationMonths,
RewardId = m.RewardId
}).ToListAsync();
}
public async Task<SubscriptionDto?> GetUserSubscriptionAsync(Guid userId)
{
var subscription = await _context.UserSubscriptions
.Include(s => s.Membership)
.Where(s => s.UserId == userId && s.IsActive)
.OrderByDescending(s => s.StartDate)
.FirstOrDefaultAsync();
if (subscription == null) return null;
return MapToDto(subscription);
}
public async Task<IEnumerable<SubscriptionDto>> GetUserAllSubscriptionsAsync(Guid userId)
{
var subscriptions = await _context.UserSubscriptions
.Include(s => s.Membership)
.Include(s => s.User)
.Where(s => s.UserId == userId && s.IsActive)
.OrderBy(s => s.StartDate)
.ToListAsync();
return subscriptions.Select(MapToDto);
}
public async Task<bool> HandleLoyaltyRedemptionAsync(Guid userId, string rewardId, string rewardName, string redemptionId)
{
try
{
var allMemberships = await _context.Memberships.ToListAsync();
Membership? membership = null;
if (!string.IsNullOrEmpty(rewardId))
{
membership = allMemberships.FirstOrDefault(m => m.RewardId == rewardId);
}
if (membership == null && !string.IsNullOrEmpty(rewardName))
{
var normalizedRewardName = rewardName.ToLowerInvariant();
membership = allMemberships.FirstOrDefault(m =>
{
var typeWords = m.Type.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
return typeWords.All(w => normalizedRewardName.Contains(w));
});
}
if (membership == null)
{
System.Diagnostics.Debug.WriteLine($"No membership matched for rewardId='{rewardId}', rewardName='{rewardName}'");
return false;
}
await SubscribeUserAsync(userId, membership.Id, redemptionId);
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"HandleLoyaltyRedemptionAsync error: {ex.Message}");
return false;
}
}
public async Task<SubscriptionDto> SubscribeUserAsync(Guid userId, int membershipId, string? redemptionId = null, string status = "Active", string paymentMethod = "Cash")
{
var membership = await _context.Memberships.FindAsync(membershipId);
if (membership == null) throw new Exception("Membership plan not found.");
// Cooldown check: Max 1 active and 1 queued subscription
var activeAndQueued = await _context.UserSubscriptions
.Where(s => s.UserId == userId && s.IsActive && s.ExpiryDate > DateTime.UtcNow)
.ToListAsync();
if (activeAndQueued.Count >= 2)
{
throw new Exception("You already have an active and a queued subscription. Please wait until one expires.");
}
var currentActive = activeAndQueued
.Where(s => s.StartDate <= DateTime.UtcNow)
.OrderByDescending(s => s.ExpiryDate)
.FirstOrDefault();
DateTime startDate = DateTime.UtcNow;
decimal discount = 0;
if (currentActive != null)
{
// If it's the same membership, we queue it
if (currentActive.MembershipId == membershipId)
{
startDate = currentActive.ExpiryDate;
}
else
{
// If it's a different membership, we treat it as an upgrade/change
// Calculate discount and deactivate old one
var preview = await GetUpgradePreviewAsync(userId, membershipId);
discount = preview.DiscountAmount;
currentActive.IsActive = false;
currentActive.Status = "Upgraded";
startDate = DateTime.UtcNow;
}
}
var subscription = new UserSubscription
{
UserId = userId,
MembershipId = membershipId,
StartDate = startDate,
ExpiryDate = startDate.AddMonths(membership.DurationMonths),
IsActive = status == "Active",
ExternalRedemptionId = redemptionId,
Status = status,
PaymentMethod = paymentMethod
};
_context.UserSubscriptions.Add(subscription);
await _context.SaveChangesAsync();
await _context.Entry(subscription).Reference(s => s.Membership).LoadAsync();
await _context.Entry(subscription).Reference(s => s.User).LoadAsync();
// Only award loyalty points for the amount actually paid (Price - Discount)
decimal paidAmount = membership.Price - discount;
if (paidAmount < 0) paidAmount = 0;
if (status == "Active")
{
await _loyaltyService.ProcessEventAsync(
externalUserId: userId.ToString(),
eventKey: "SUBSCRIBE",
eventValue: (double)paidAmount,
referenceId: $"SUB-{subscription.Id}",
description: $"Purchased Membership: {membership.Type} (Discount applied: {discount})",
email: subscription.User?.Email ?? "No Email",
mobile: subscription.User?.PhoneNumber ?? "0000000000"
);
}
return MapToDto(subscription);
}
public async Task<SubscriptionUpgradePreviewDto> GetUpgradePreviewAsync(Guid userId, int newMembershipId)
{
var newMembership = await _context.Memberships.FindAsync(newMembershipId);
if (newMembership == null) return new SubscriptionUpgradePreviewDto { CanUpgrade = false, Message = "Plan not found" };
var currentSubscription = await _context.UserSubscriptions
.Include(s => s.Membership)
.Where(s => s.UserId == userId && s.IsActive && s.StartDate <= DateTime.UtcNow && s.ExpiryDate > DateTime.UtcNow)
.OrderByDescending(s => s.StartDate)
.FirstOrDefaultAsync();
if (currentSubscription == null)
{
return new SubscriptionUpgradePreviewDto
{
OriginalPrice = newMembership.Price,
DiscountAmount = 0,
FinalPrice = newMembership.Price,
CanUpgrade = true
};
}
if (currentSubscription.MembershipId == newMembershipId)
{
return new SubscriptionUpgradePreviewDto
{
OriginalPrice = newMembership.Price,
DiscountAmount = 0,
FinalPrice = newMembership.Price,
CanUpgrade = true,
Message = "Same plan selected. This will be queued after your current subscription."
};
}
// Calculate unused value
var totalDuration = (currentSubscription.ExpiryDate - currentSubscription.StartDate).TotalDays;
var daysRemaining = (currentSubscription.ExpiryDate - DateTime.UtcNow).TotalDays;
if (daysRemaining < 0) daysRemaining = 0;
decimal dailyRate = currentSubscription.Membership.Price / (decimal)totalDuration;
decimal unusedValue = dailyRate * (decimal)daysRemaining;
// Cap discount at new price
decimal discount = Math.Min(unusedValue, newMembership.Price);
return new SubscriptionUpgradePreviewDto
{
OriginalPrice = newMembership.Price,
DiscountAmount = Math.Round(discount, 2),
FinalPrice = Math.Round(newMembership.Price - discount, 2),
CanUpgrade = true,
Message = $"Pro-rated discount applied for your current {currentSubscription.Membership.Type} plan."
};
}
public async Task<SubscriptionDto> SubscribeWithWalletAsync(Guid userId, int membershipId)
{
var preview = await GetUpgradePreviewAsync(userId, membershipId);
if (!preview.CanUpgrade) throw new Exception(preview.Message ?? "Cannot purchase this plan.");
var balance = await _walletService.GetBalanceAsync(userId);
if (balance < preview.FinalPrice)
{
throw new Exception($"Insufficient balance. You need {preview.FinalPrice - balance:N0} more MMK.");
}
var membership = await _context.Memberships.FindAsync(membershipId);
// Deduct from wallet
bool deducted = await _walletService.DeductAsync(userId, preview.FinalPrice, $"Subscription: {membership!.Type}");
if (!deducted) throw new Exception("Failed to deduct from wallet.");
// Create subscription
return await SubscribeUserAsync(userId, membershipId, status: "Active", paymentMethod: "Wallet");
}
public async Task<IEnumerable<SubscriptionDto>> GetPendingSubscriptionsAsync()
{
var pending = await _context.UserSubscriptions
.Include(s => s.Membership)
.Include(s => s.User)
.Where(s => s.Status == "PendingApproval")
.OrderByDescending(s => s.StartDate)
.ToListAsync();
return pending.Select(MapToDto);
}
public async Task<SubscriptionDto> CreatePendingSubscriptionAsync(Guid userId, int membershipId)
{
// Similar logic to SubscribeUserAsync but set to PendingApproval
return await SubscribeUserAsync(userId, membershipId, status: "PendingApproval", paymentMethod: "Cash");
}
public async Task<bool> ApproveSubscriptionAsync(Guid subscriptionId, bool approve)
{
var subscription = await _context.UserSubscriptions
.Include(s => s.Membership)
.Include(s => s.User)
.FirstOrDefaultAsync(s => s.Id == subscriptionId);
if (subscription == null) return false;
if (approve)
{
subscription.Status = "Active";
subscription.IsActive = true;
// Award points now
decimal paidAmount = 0;
if (subscription.Membership != null)
{
decimal discount = 0; // Simplified for approval flow for now
paidAmount = subscription.Membership.Price - discount;
}
await _loyaltyService.ProcessEventAsync(
externalUserId: subscription.UserId.ToString(),
eventKey: "SUBSCRIBE",
eventValue: (double)paidAmount,
referenceId: $"SUB-{subscription.Id}",
description: $"Membership Approved: {subscription.Membership?.Type ?? "Unknown Plan"}",
email: subscription.User?.Email ?? "No Email",
mobile: subscription.User?.PhoneNumber ?? "0000000000"
);
}
else
{
subscription.Status = "Rejected";
subscription.IsActive = false;
}
await _context.SaveChangesAsync();
return true;
}
public async Task<IEnumerable<SubscriptionDto>> GetAllSubscriptionsAsync()
{
var subscriptions = await _context.UserSubscriptions
.Include(s => s.Membership)
.Include(s => s.User)
.OrderByDescending(s => s.StartDate)
.ToListAsync();
return subscriptions.Select(MapToDto);
}
private static SubscriptionDto MapToDto(UserSubscription subscription)
{
return new SubscriptionDto
{
Id = subscription.Id,
UserId = subscription.UserId,
MembershipId = subscription.MembershipId,
MembershipType = subscription.Membership?.Type ?? "Unknown",
UserEmail = subscription.User?.Email ?? "Unknown",
UserName = subscription.User?.FullName ?? "Unknown",
StartDate = subscription.StartDate,
ExpiryDate = subscription.ExpiryDate,
IsActive = subscription.IsActive,
Status = subscription.Status,
PaymentMethod = subscription.PaymentMethod,
ExternalRedemptionId = subscription.ExternalRedemptionId
};
}
}
}
|