|
| 1 | +package services |
| 2 | + |
| 3 | +import jakarta.inject.{Inject, Singleton} |
| 4 | +import models.domain.billing.{PatronSubscription, PatronSummary, PatronTier} |
| 5 | +import play.api.Logging |
| 6 | +import repositories.PatronSubscriptionRepository |
| 7 | + |
| 8 | +import java.time.LocalDateTime |
| 9 | +import java.util.UUID |
| 10 | +import scala.concurrent.{ExecutionContext, Future} |
| 11 | + |
| 12 | +@Singleton |
| 13 | +class PatronageService @Inject()( |
| 14 | + subscriptionRepo: PatronSubscriptionRepository |
| 15 | + )(implicit ec: ExecutionContext) extends Logging { |
| 16 | + |
| 17 | + def createSubscription( |
| 18 | + userId: UUID, |
| 19 | + tier: String, |
| 20 | + billingInterval: String, |
| 21 | + paymentProvider: String, |
| 22 | + providerSubscriptionId: Option[String] = None, |
| 23 | + providerCustomerId: Option[String] = None |
| 24 | + ): Future[Either[String, PatronSubscription]] = { |
| 25 | + if (!PatronSubscription.ValidTiers.contains(tier)) |
| 26 | + return Future.successful(Left(s"Invalid patron tier: $tier")) |
| 27 | + if (!PatronSubscription.ValidIntervals.contains(billingInterval)) |
| 28 | + return Future.successful(Left(s"Invalid billing interval: $billingInterval")) |
| 29 | + if (!PatronSubscription.ValidProviders.contains(paymentProvider)) |
| 30 | + return Future.successful(Left(s"Invalid payment provider: $paymentProvider")) |
| 31 | + |
| 32 | + subscriptionRepo.findActiveByUserId(userId).flatMap { |
| 33 | + case Some(existing) => |
| 34 | + Future.successful(Left(s"User already has an active subscription (tier: ${existing.patronTier})")) |
| 35 | + case None => |
| 36 | + val amountCents = PatronTier.amountCents(tier, billingInterval) |
| 37 | + val now = LocalDateTime.now() |
| 38 | + val periodEnd = billingInterval match { |
| 39 | + case "MONTHLY" => now.plusMonths(1) |
| 40 | + case "YEARLY" => now.plusYears(1) |
| 41 | + } |
| 42 | + |
| 43 | + val subscription = PatronSubscription( |
| 44 | + userId = userId, |
| 45 | + patronTier = tier, |
| 46 | + paymentProvider = paymentProvider, |
| 47 | + providerSubscriptionId = providerSubscriptionId, |
| 48 | + providerCustomerId = providerCustomerId, |
| 49 | + amountCents = amountCents, |
| 50 | + billingInterval = billingInterval, |
| 51 | + currentPeriodStart = Some(now), |
| 52 | + currentPeriodEnd = Some(periodEnd) |
| 53 | + ) |
| 54 | + subscriptionRepo.create(subscription).map(Right(_)) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + def cancelSubscription(subscriptionId: Int, userId: UUID): Future[Either[String, Boolean]] = { |
| 59 | + subscriptionRepo.findById(subscriptionId).flatMap { |
| 60 | + case None => |
| 61 | + Future.successful(Left("Subscription not found")) |
| 62 | + case Some(sub) if sub.userId != userId => |
| 63 | + Future.successful(Left("Not authorized to cancel this subscription")) |
| 64 | + case Some(sub) if sub.status != "ACTIVE" => |
| 65 | + Future.successful(Left(s"Cannot cancel subscription with status: ${sub.status}")) |
| 66 | + case Some(_) => |
| 67 | + subscriptionRepo.cancel(subscriptionId).map(Right(_)) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + def getActiveSubscription(userId: UUID): Future[Option[PatronSubscription]] = |
| 72 | + subscriptionRepo.findActiveByUserId(userId) |
| 73 | + |
| 74 | + def getUserSubscriptions(userId: UUID): Future[Seq[PatronSubscription]] = |
| 75 | + subscriptionRepo.findByUserId(userId) |
| 76 | + |
| 77 | + def handlePaymentWebhook(event: WebhookEvent, provider: String): Future[Either[String, Boolean]] = { |
| 78 | + subscriptionRepo.findByProviderSubscriptionId(provider, event.providerSubscriptionId).flatMap { |
| 79 | + case None => |
| 80 | + logger.warn(s"Webhook for unknown subscription: ${event.providerSubscriptionId}") |
| 81 | + Future.successful(Left("Subscription not found")) |
| 82 | + case Some(sub) => |
| 83 | + event.eventType match { |
| 84 | + case "subscription.renewed" | "invoice.paid" => |
| 85 | + val start = event.periodStart.getOrElse(LocalDateTime.now()) |
| 86 | + val end = event.periodEnd.getOrElse( |
| 87 | + if (sub.billingInterval == "MONTHLY") start.plusMonths(1) else start.plusYears(1) |
| 88 | + ) |
| 89 | + for { |
| 90 | + _ <- subscriptionRepo.updateStatus(sub.id.get, "ACTIVE") |
| 91 | + _ <- subscriptionRepo.updatePeriod(sub.id.get, start, end) |
| 92 | + } yield Right(true) |
| 93 | + |
| 94 | + case "subscription.cancelled" | "subscription.deleted" => |
| 95 | + subscriptionRepo.cancel(sub.id.get).map(Right(_)) |
| 96 | + |
| 97 | + case "invoice.payment_failed" => |
| 98 | + subscriptionRepo.updateStatus(sub.id.get, "PAST_DUE").map(Right(_)) |
| 99 | + |
| 100 | + case other => |
| 101 | + logger.debug(s"Unhandled webhook event type: $other") |
| 102 | + Future.successful(Right(true)) |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + def expireOverdueSubscriptions(): Future[Int] = { |
| 108 | + subscriptionRepo.findByStatus("ACTIVE").flatMap { active => |
| 109 | + val now = LocalDateTime.now() |
| 110 | + val expired = active.filter { sub => |
| 111 | + sub.currentPeriodEnd.exists(_.isBefore(now)) |
| 112 | + } |
| 113 | + |
| 114 | + Future.sequence(expired.map { sub => |
| 115 | + subscriptionRepo.updateStatus(sub.id.get, "EXPIRED") |
| 116 | + }).map(_.count(_ == true)) |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + def getPatronSummary: Future[PatronSummary] = { |
| 121 | + for { |
| 122 | + activeCount <- subscriptionRepo.countActive() |
| 123 | + tierCounts <- subscriptionRepo.countByTier() |
| 124 | + } yield { |
| 125 | + val monthlyRevenue = tierCounts.map { case (tier, count) => |
| 126 | + val monthlyAmount = PatronTier.amountCents(tier, "MONTHLY") |
| 127 | + monthlyAmount * count |
| 128 | + }.sum |
| 129 | + |
| 130 | + PatronSummary( |
| 131 | + activePatrons = activeCount, |
| 132 | + tierCounts = tierCounts, |
| 133 | + monthlyRevenueCents = monthlyRevenue |
| 134 | + ) |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + def isPatron(userId: UUID): Future[Boolean] = |
| 139 | + subscriptionRepo.findActiveByUserId(userId).map(_.isDefined) |
| 140 | + |
| 141 | + def getPatronTier(userId: UUID): Future[Option[String]] = |
| 142 | + subscriptionRepo.findActiveByUserId(userId).map(_.map(_.patronTier)) |
| 143 | +} |
0 commit comments