lila/modules/plan/src/main/PlanApi.scala

371 lines
15 KiB
Scala
Raw Normal View History

2016-07-12 11:19:30 -06:00
package lila.plan
2016-06-06 03:36:21 -06:00
2016-06-06 08:41:04 -06:00
import lila.db.dsl._
2016-07-18 15:24:32 -06:00
import lila.memo._
2016-06-06 08:41:04 -06:00
import lila.user.{ User, UserRepo }
2016-06-06 03:36:21 -06:00
2016-06-06 08:41:04 -06:00
import org.joda.time.DateTime
2016-07-14 13:50:18 -06:00
import reactivemongo.api.collections.bson.BSONBatchCommands.AggregationFramework._
2016-07-18 15:24:32 -06:00
import scala.concurrent.duration._
2016-06-06 03:36:21 -06:00
2016-07-12 11:19:30 -06:00
final class PlanApi(
stripeClient: StripeClient,
patronColl: Coll,
2016-07-12 10:33:22 -06:00
chargeColl: Coll,
2016-08-21 03:37:48 -06:00
tracking: PlanTracking,
2016-07-14 04:58:34 -06:00
notifier: PlanNotifier,
lightUserApi: lila.user.LightUserApi,
2016-07-14 15:11:42 -06:00
bus: lila.common.Bus,
payPalIpnKey: PayPalIpnKey,
monthlyGoalApi: MonthlyGoalApi) {
2016-06-06 08:41:04 -06:00
2016-07-12 10:58:39 -06:00
import BsonHandlers._
import PatronHandlers._
import ChargeHandlers._
2016-06-06 08:41:04 -06:00
def checkout(userOption: Option[User], data: Checkout): Funit =
getOrMakePlan(data.cents, data.freq) flatMap { plan =>
2016-08-29 16:34:18 -06:00
userOption.fold(anonCheckout(plan, data)) { user =>
userCheckout(user, plan, data)
2016-07-13 08:46:25 -06:00
}
} void
2016-07-13 08:14:20 -06:00
def switch(user: User, cents: Cents): Fu[StripeSubscription] =
2016-06-06 08:41:04 -06:00
userCustomer(user) flatMap {
2016-06-06 12:18:40 -06:00
case None => fufail(s"Can't switch non-existent customer ${user.id}")
2016-06-06 08:41:04 -06:00
case Some(customer) =>
customer.firstSubscription match {
2016-07-13 08:14:20 -06:00
case None => fufail(s"Can't switch non-existent subscription of ${user.id}")
case Some(sub) if sub.plan.cents == cents => fuccess(sub)
case Some(sub) =>
getOrMakePlan(cents, Freq.Monthly) flatMap { plan =>
2016-07-13 08:14:20 -06:00
stripeClient.updateSubscription(sub, plan, none)
}
2016-06-06 08:41:04 -06:00
}
}
2016-06-06 12:18:40 -06:00
def cancel(user: User): Funit =
userCustomer(user) flatMap {
case None => fufail(s"Can't cancel non-existent customer ${user.id}")
case Some(customer) =>
customer.firstSubscription match {
case None => fufail(s"Can't cancel non-existent subscription of ${user.id}")
2016-07-12 11:19:30 -06:00
case Some(sub) => stripeClient.cancelSubscription(sub) >>
setDbUserPlan(user, user.plan.disable) >>
2016-07-16 03:31:26 -06:00
patronColl.update($id(user.id), $unset("stripe", "payPal", "expiresAt")).void >>-
logger.info(s"Canceled subscription $sub of ${user.username}")
2016-06-06 12:18:40 -06:00
}
}
2016-08-21 03:37:48 -06:00
def onStripeCharge(stripeCharge: StripeCharge): Funit =
customerIdPatron(stripeCharge.customer) flatMap { patronOption =>
val charge = Charge.make(
2016-07-14 04:03:04 -06:00
userId = patronOption.map(_.userId),
2016-08-21 03:37:48 -06:00
stripe = Charge.Stripe(stripeCharge.id, stripeCharge.customer).some,
cents = stripeCharge.amount)
addCharge(charge) >> {
2016-07-12 10:33:22 -06:00
patronOption match {
2016-07-13 08:46:25 -06:00
case None =>
logger.info(s"Charged anon customer $charge")
funit
2016-07-14 14:43:04 -06:00
case Some(patron) =>
logger.info(s"Charged $charge $patron")
2016-08-21 03:37:48 -06:00
stripeClient getCustomer stripeCharge.customer foreach {
_ foreach { customer => tracking.charge(charge, renew = customer.renew) }
}
2016-07-14 04:03:04 -06:00
UserRepo byId patron.userId flatten s"Missing user for $patron" flatMap { user =>
2016-07-14 14:43:04 -06:00
val p2 = patron.copy(
2016-08-21 03:37:48 -06:00
stripe = Patron.Stripe(stripeCharge.customer).some
).levelUpIfPossible
2016-07-14 14:43:04 -06:00
patronColl.update($id(patron.id), p2) >>
setDbUserPlan(user,
2016-07-14 14:43:04 -06:00
if (patron.canLevelUp) user.plan.incMonths
else user.plan.enable)
2016-07-10 14:12:22 -06:00
}
2016-06-06 08:41:04 -06:00
}
2016-07-12 10:33:22 -06:00
}
2016-06-06 08:41:04 -06:00
}
2016-07-14 13:31:41 -06:00
def onPaypalCharge(
2016-07-14 13:50:18 -06:00
userId: Option[String],
2016-07-14 13:31:41 -06:00
email: Option[Patron.PayPal.Email],
subId: Option[Patron.PayPal.SubId],
cents: Cents,
name: Option[String],
2016-07-14 14:52:38 -06:00
txnId: Option[String],
2016-07-14 15:11:42 -06:00
ip: String,
key: PayPalIpnKey): Funit =
if (key != payPalIpnKey) {
logger.error(s"Invalid PayPal IPN key $key from $ip $userId $cents")
funit
}
else (cents.value >= 100) ?? {
2016-08-21 03:37:48 -06:00
val charge = Charge.make(
2016-07-14 15:11:42 -06:00
userId = userId,
payPal = Charge.PayPal(
name = name,
email = email.map(_.value),
txnId = txnId,
subId = subId.map(_.value),
ip = ip.some).some,
2016-08-21 03:37:48 -06:00
cents = cents)
tracking.charge(charge, renew = subId.isDefined)
addCharge(charge) >>
2016-07-16 03:49:10 -06:00
(userId ?? UserRepo.named) flatMap { userOption =>
userOption ?? { user =>
2016-07-14 15:11:42 -06:00
val payPal = Patron.PayPal(email, subId, DateTime.now)
userPatron(user).flatMap {
case None => patronColl.insert(Patron(
_id = Patron.UserId(user.id),
payPal = payPal.some,
lastLevelUp = DateTime.now
).expireInOneMonth) >>
setDbUserPlan(user, lila.user.Plan.start) >>
2016-08-21 03:37:48 -06:00
notifier.onStart(user) >>-
tracking.newDonation(user, cents, renew = subId.isDefined)
2016-07-14 15:11:42 -06:00
case Some(patron) =>
2016-08-21 03:37:48 -06:00
if (subId.isDefined) tracking.upgrade(user, cents)
else tracking.reDonation(user, cents)
2016-07-14 15:11:42 -06:00
val p2 = patron.copy(
payPal = payPal.some
).levelUpIfPossible.expireInOneMonth
patronColl.update($id(patron.id), p2) >>
setDbUserPlan(user,
2016-07-14 15:11:42 -06:00
if (patron.canLevelUp) user.plan.incMonths
else user.plan.enable)
} >>- logger.info(s"Charged ${user.username} with paypal: $cents")
2016-07-12 11:19:30 -06:00
}
2016-07-12 10:33:22 -06:00
}
2016-07-14 15:11:42 -06:00
}
2016-06-06 08:41:04 -06:00
def onSubscriptionDeleted(sub: StripeSubscription): Funit =
customerIdPatron(sub.customer) flatMap {
2016-07-16 03:31:26 -06:00
case None =>
logger.warn(s"Deleted subscription of unknown patron $sub")
funit
case Some(patron) =>
2016-07-14 04:03:04 -06:00
UserRepo byId patron.userId flatten s"Missing user for $patron" flatMap { user =>
setDbUserPlan(user, user.plan.disable) >>
patronColl.update($id(user.id), patron.removeStripe).void >>
notifier.onExpire(user) >>-
2016-07-14 04:03:04 -06:00
logger.info(s"Unsubed ${user.username} ${sub}")
2016-06-06 08:41:04 -06:00
}
}
2016-07-12 11:19:30 -06:00
def getEvent = stripeClient.getEvent _
2016-07-14 10:27:07 -06:00
def customerInfo(user: User, customer: StripeCustomer): Fu[Option[CustomerInfo]] =
stripeClient.getNextInvoice(customer.id) zip
stripeClient.getPastInvoices(customer.id) map {
case (Some(nextInvoice), pastInvoices) =>
customer.firstSubscription match {
case Some(sub) => MonthlyCustomerInfo(sub, nextInvoice, pastInvoices).some
case None =>
logger.warn(s"Can't identify ${user.username} monthly subscription $customer")
none
}
case (None, _) =>
customer.firstSubscription match {
case Some(sub) => OneTimeCustomerInfo(customer, sub).some
case None =>
logger.warn(s"Can't identify ${user.username} one-time subscription $customer")
none
}
2016-06-06 11:50:13 -06:00
}
import PlanApi.SyncResult.{ ReloadUser, Synced }
def sync(user: User): Fu[PlanApi.SyncResult] = userPatron(user) flatMap {
2016-07-11 16:55:35 -06:00
2016-07-12 10:58:39 -06:00
case None if user.plan.active =>
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: disable plan of non-patron")
setDbUserPlan(user, user.plan.disable) inject ReloadUser
2016-07-11 16:55:35 -06:00
2016-07-14 10:27:07 -06:00
case None => fuccess(Synced(none, none))
2016-07-11 16:55:35 -06:00
2016-10-07 08:51:08 -06:00
case Some(patron) if patron.isLifetime => fuccess(Synced(patron.some, none))
2016-07-11 16:55:35 -06:00
case Some(patron) => (patron.stripe, patron.payPal) match {
2016-07-12 11:19:30 -06:00
case (Some(stripe), _) => stripeClient.getCustomer(stripe.customerId) flatMap {
2016-07-11 16:55:35 -06:00
case None =>
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: unset DB patron that's not in stripe")
patronColl.update($id(patron.id), patron.removeStripe) >> sync(user)
2016-07-11 16:55:35 -06:00
case Some(customer) if customer.firstSubscription.isEmpty =>
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: unset DB patron of customer without a subscription")
patronColl.update($id(patron.id), patron.removeStripe) >> sync(user)
2016-07-11 16:55:35 -06:00
case Some(customer) if customer.firstSubscription.isDefined && !user.plan.active =>
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: enable plan of customer with a subscription")
setDbUserPlan(user, user.plan.enable) inject ReloadUser
2016-07-14 10:27:07 -06:00
case customer => fuccess(Synced(patron.some, customer))
2016-07-11 16:55:35 -06:00
}
case (_, Some(paypal)) =>
2016-07-14 11:24:45 -06:00
if (!user.plan.active) {
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: enable plan of customer with paypal")
setDbUserPlan(user, user.plan.enable) inject ReloadUser
2016-07-11 16:55:35 -06:00
}
2016-07-14 10:27:07 -06:00
else fuccess(Synced(patron.some, none))
2016-07-11 16:55:35 -06:00
case (None, None) if user.plan.active =>
2016-10-07 08:51:08 -06:00
logger.warn(s"${user.username} sync: disable plan of patron with no paypal or stripe")
setDbUserPlan(user, user.plan.disable) inject ReloadUser
2016-07-11 16:55:35 -06:00
2016-07-14 10:27:07 -06:00
case _ => fuccess(Synced(patron.some, none))
2016-06-06 11:50:13 -06:00
}
}
2016-06-06 11:50:13 -06:00
2016-07-18 15:24:32 -06:00
private val recentChargeUserIdsCache = AsyncCache[Int, List[User.ID]](
f = nb => chargeColl.primitive[User.ID](
$empty, sort = $doc("date" -> -1), nb = nb, "userId"
) flatMap filterUserIds,
2016-07-18 15:24:32 -06:00
timeToLive = 1 hour)
def recentChargeUserIds(nb: Int): Fu[List[User.ID]] = recentChargeUserIdsCache(nb)
2016-07-14 08:41:51 -06:00
def recentChargesOf(user: User): Fu[List[Charge]] =
chargeColl.find($doc("userId" -> user.id)).sort($doc("date" -> -1)).list[Charge]()
2016-07-18 15:24:32 -06:00
private val topPatronUserIdsCache = AsyncCache[Int, List[User.ID]](
f = nb => chargeColl.aggregate(
Match($doc("userId" $exists true)), List(
GroupField("userId")("total" -> SumField("cents")),
Sort(Descending("total")),
Limit(nb))).map {
_.firstBatch.flatMap { _.getAs[User.ID]("_id") }
} flatMap filterUserIds,
2016-07-18 15:24:32 -06:00
timeToLive = 1 hour)
def topPatronUserIds(nb: Int): Fu[List[User.ID]] = topPatronUserIdsCache(nb)
2016-07-14 13:50:18 -06:00
private def filterUserIds(ids: List[User.ID]): Fu[List[User.ID]] = {
val dedup = ids.distinct
UserRepo.filterByEnabled(dedup) map { enableds =>
val set = enableds.toSet
dedup filter set.contains
}
}
private def addCharge(charge: Charge): Funit =
2016-07-19 00:04:29 -06:00
chargeColl.insert(charge) >>
recentChargeUserIdsCache.clear >>
topPatronUserIdsCache.clear >>- {
monthlyGoalApi.get foreach { m =>
bus.publish(lila.hub.actorApi.plan.ChargeEvent(
username = charge.userId.flatMap(lightUserApi.get).fold("Anonymous")(_.name),
amount = charge.cents.value,
2016-10-02 08:59:43 -06:00
percent = m.percent,
DateTime.now), 'plan)
lila.mon.plan.goal(m.goal.value)
lila.mon.plan.current(m.current.value)
lila.mon.plan.percent(m.percent)
2016-07-19 11:29:56 -06:00
if (charge.isPayPal) {
lila.mon.plan.amount.paypal(charge.cents.value)
lila.mon.plan.count.paypal()
}
else if (charge.isStripe) {
lila.mon.plan.amount.stripe(charge.cents.value)
lila.mon.plan.count.stripe()
}
}
}
2016-07-19 00:04:29 -06:00
private def getOrMakePlan(cents: Cents, freq: Freq): Fu[StripePlan] =
stripeClient.getPlan(cents, freq) getOrElse stripeClient.makePlan(cents, freq)
2016-07-13 08:14:20 -06:00
2016-08-29 16:34:18 -06:00
private def anonCheckout(plan: StripePlan, data: Checkout): Funit =
2016-07-13 08:46:25 -06:00
stripeClient.createAnonCustomer(plan, data) map { customer =>
logger.info(s"Subed anon $customer to ${plan} freq=${data.freq}")
2016-07-13 08:46:25 -06:00
customer.firstSubscription err s"Can't create anon $customer subscription to $plan"
} flatMap { subscription =>
if (data.freq.renew) funit
else stripeClient dontRenewSubscription subscription void
2016-07-13 08:46:25 -06:00
}
private def userCheckout(user: User, plan: StripePlan, data: Checkout): Funit =
2016-06-06 08:41:04 -06:00
userCustomer(user) flatMap {
case None => createCustomer(user, data, plan) map { customer =>
2016-07-14 04:03:04 -06:00
customer.firstSubscription err s"Can't create ${user.username} subscription for customer $customer"
} flatMap withNewSubscription(user, data)
2016-08-21 03:37:48 -06:00
case Some(customer) =>
// tracking: user did one-time before, goes for monthly now
if (!customer.renew && data.freq.renew) tracking.upgrade(user, plan.amount)
// tracking: one-time
2016-08-21 03:37:48 -06:00
if (!data.freq.renew) tracking.reDonation(user, plan.amount)
// user has a monthly going on and is making an extra one-time
// let's not change the user plan to one-time, or else
// it would only cancel the monthly
if (customer.renew && !data.freq.renew) stripeClient.addOneTime(customer, data.amount)
// or else, set this new plan to the customer
else setCustomerPlan(customer, plan, data.source) flatMap { sub =>
2016-08-21 03:37:48 -06:00
saveStripePatron(user, customer.id, data.freq) inject sub
} flatMap withNewSubscription(user, data)
2016-06-06 08:41:04 -06:00
}
private def withNewSubscription(user: User, data: Checkout)(subscription: StripeSubscription): Funit = {
logger.info(s"Subed user ${user.username} $subscription freq=${data.freq}")
if (data.freq.renew) funit
else stripeClient dontRenewSubscription subscription void
}
private def setDbUserPlan(user: User, plan: lila.user.Plan): Funit =
UserRepo.setPlan(user, plan) >> lightUserApi.invalidate(user.id)
private def createCustomer(user: User, data: Checkout, plan: StripePlan): Fu[StripeCustomer] =
stripeClient.createCustomer(user, data, plan) flatMap { customer =>
saveStripePatron(user, customer.id, data.freq) >>
setDbUserPlan(user, lila.user.Plan.start) >>
2016-07-14 04:58:34 -06:00
notifier.onStart(user) >>-
2016-08-21 03:37:48 -06:00
tracking.newDonation(user, plan.amount, renew = data.freq.renew) >>-
logger.info(s"Create ${user.username} customer $customer") inject customer
2016-06-06 08:41:04 -06:00
}
private def saveStripePatron(user: User, customerId: CustomerId, freq: Freq): Funit = userPatron(user) flatMap {
2016-07-12 12:25:58 -06:00
case None => patronColl.insert(Patron(
_id = Patron.UserId(user.id),
stripe = Patron.Stripe(customerId).some,
lastLevelUp = DateTime.now
).expireInOneMonth(!freq.renew))
2016-07-12 12:25:58 -06:00
case Some(patron) => patronColl.update(
$id(patron.id),
patron.copy(stripe = Patron.Stripe(customerId).some).expireInOneMonth(!freq.renew))
2016-07-12 12:25:58 -06:00
} void
2016-06-06 08:41:04 -06:00
private def setCustomerPlan(customer: StripeCustomer, plan: StripePlan, source: Source): Fu[StripeSubscription] =
customer.subscriptions.data.find(_.plan == plan) match {
case Some(sub) => fuccess(sub)
case None => customer.firstSubscription match {
2016-07-12 11:19:30 -06:00
case None => stripeClient.createSubscription(customer, plan, source)
case Some(sub) => stripeClient.updateSubscription(sub, plan, source.some)
2016-06-06 08:41:04 -06:00
}
}
private def userCustomerId(user: User): Fu[Option[CustomerId]] =
2016-07-12 12:25:58 -06:00
userPatron(user) map {
_.flatMap { _.stripe.map(_.customerId) }
}
2016-06-06 08:41:04 -06:00
private def userCustomer(user: User): Fu[Option[StripeCustomer]] =
userCustomerId(user) flatMap {
2016-07-12 11:19:30 -06:00
_ ?? stripeClient.getCustomer
2016-06-06 08:41:04 -06:00
}
def patronCustomer(patron: Patron): Fu[Option[StripeCustomer]] =
patron.stripe.map(_.customerId) ?? stripeClient.getCustomer
private def customerIdPatron(id: CustomerId): Fu[Option[Patron]] =
2016-08-21 03:37:48 -06:00
patronColl.uno[Patron]($doc("stripe.customerId" -> id))
2016-07-20 02:08:16 -06:00
def userPatron(user: User): Fu[Option[Patron]] = patronColl.uno[Patron]($id(user.id))
2016-06-06 03:36:21 -06:00
}
object PlanApi {
sealed trait SyncResult
object SyncResult {
case object ReloadUser extends SyncResult
2016-07-14 10:27:07 -06:00
case class Synced(patron: Option[Patron], customer: Option[StripeCustomer]) extends SyncResult
}
}