#![warn(missing_docs)]
use std::fmt;
use std::sync::Arc;
use renox::Config;
use renox::auth::events::AccountDeleted;
use renox::db::Migration;
use renox::prelude::*;
mod customer;
pub mod events;
pub mod gateway;
mod guard;
mod handlers;
mod model;
pub mod ngenius;
pub mod payment;
mod plan;
pub mod stripe;
mod sync;
mod webhook;
pub mod xendit;
pub use customer::{Billable, Customer, Owner};
pub use events::{
DisputeLost, DisputeOpened, DisputeWon, PaymentFailed, PaymentLinkExpired, PaymentRefunded,
PaymentSucceeded, RefundFailed, RefundSucceeded, SubscriptionCanceled, SubscriptionCreated,
SubscriptionPaused, SubscriptionUnpaused, SubscriptionUpdated,
};
pub use gateway::{BoxFuture, Checkout, CheckoutRequest, Gateway, Notice, Payment, Remote};
pub use guard::SubscriptionRoutes;
pub use model::{BillingCustomer, Subscription, SubscriptionStatus};
pub use ngenius::Ngenius;
pub use payment::{
BillingPayment, BillingRefund, Charge, ChargeRequest, DisputeState, DisputeUpdate, PaymentKind,
PaymentLink, PaymentPage, PaymentState, PaymentStatus, PaymentUpdate, Refund, RefundResult,
RefundStatus, RefundUpdate, Unsupported,
};
pub use plan::{Interval, Plan};
pub use stripe::Stripe;
pub use xendit::Xendit;
const MIGRATIONS: &[Migration] = &[
Migration::new(
"00010101000900_create_billing_tables",
"",
Some(include_str!(
"../migrations/00010101000900_create_billing_tables.down.sql"
)),
)
.sqlite(
include_str!("../migrations/00010101000900_create_billing_tables.up.sql"),
None,
)
.postgres(
include_str!("../migrations/00010101000900_create_billing_tables.postgres.up.sql"),
None,
),
Migration::new(
"00010101000910_create_billing_payments",
"",
Some(include_str!(
"../migrations/00010101000910_create_billing_payments.down.sql"
)),
)
.sqlite(
include_str!("../migrations/00010101000910_create_billing_payments.up.sql"),
None,
)
.postgres(
include_str!("../migrations/00010101000910_create_billing_payments.postgres.up.sql"),
None,
),
Migration::new(
"00010101000920_add_gateway_intent_to_billing_payments",
"",
Some(include_str!(
"../migrations/00010101000920_add_gateway_intent_to_billing_payments.down.sql"
)),
)
.sqlite(
include_str!("../migrations/00010101000920_add_gateway_intent_to_billing_payments.up.sql"),
None,
)
.postgres(
include_str!(
"../migrations/00010101000920_add_gateway_intent_to_billing_payments.postgres.up.sql"
),
None,
),
];
const VIEWS: &[(&str, &str)] = &[
("billing/plans.html", include_str!("../views/plans.html")),
(
"billing/section.html",
include_str!("../views/section.html"),
),
];
#[derive(Clone)]
pub struct Billing {
setup: Setup,
}
impl Default for Billing {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Default)]
pub(crate) struct Setup {
pub(crate) plans: Vec<Plan>,
pub(crate) gateways: Vec<Arc<dyn Gateway>>,
pub(crate) generic_trials: bool,
pub(crate) prorate: bool,
pub(crate) redirect_to: Option<String>,
}
impl Billing {
pub fn new() -> Self {
Self {
setup: Setup {
prorate: true,
..Setup::default()
},
}
}
pub fn plan(mut self, plan: Plan) -> Self {
self.setup.plans.retain(|p| p.key != plan.key);
self.setup.plans.push(plan);
self
}
pub fn stripe(self) -> Self {
self.gateway(Stripe::from_config())
}
pub fn xendit(self) -> Self {
self.gateway(Xendit::from_config())
}
pub fn ngenius(self) -> Self {
self.gateway(Ngenius::from_config())
}
pub fn gateway(mut self, gateway: impl Gateway) -> Self {
self.setup.gateways.retain(|g| g.name() != gateway.name());
self.setup.gateways.push(Arc::new(gateway));
self
}
pub fn generic_trials(mut self) -> Self {
self.setup.generic_trials = true;
self
}
pub fn without_proration(mut self) -> Self {
self.setup.prorate = false;
self
}
pub fn redirect_to(mut self, path: impl Into<String>) -> Self {
self.setup.redirect_to = Some(path.into());
self
}
}
impl fmt::Debug for Billing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Billing")
.field(
"plans",
&self.setup.plans.iter().map(|p| &p.key).collect::<Vec<_>>(),
)
.field(
"gateways",
&self
.setup
.gateways
.iter()
.map(|g| g.name().to_owned())
.collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
impl Setup {
pub(crate) fn plan(&self, key: &str) -> Result<&Plan> {
self.plans
.iter()
.find(|p| p.key == key)
.ok_or_else(|| Error::BadRequest(format!("There's no plan `{key}`.")))
}
pub(crate) fn gateway(&self, state: &AppState, name: &str) -> Option<Arc<dyn Gateway>> {
self.gateways
.iter()
.find(|g| g.name() == name && g.configured(&state.config))
.cloned()
}
pub(crate) fn payment_gateway(
&self,
state: &AppState,
name: Option<&str>,
) -> Result<Arc<dyn Gateway>> {
let found = match name {
Some(name) => self.gateway(state, name),
None => self
.gateways
.iter()
.find(|g| g.configured(&state.config))
.cloned(),
};
found.ok_or_else(|| {
renox::anyhow::anyhow!(
"no payment gateway is set up{}: set its keys in .env",
name.map(|n| format!(" for `{n}`")).unwrap_or_default()
)
.into()
})
}
pub(crate) fn gateway_for(&self, state: &AppState, plan: &Plan) -> Result<Arc<dyn Gateway>> {
let found = match &plan.gateway {
Some(name) => self.gateway(state, name),
None => self
.gateways
.iter()
.find(|g| g.configured(&state.config))
.cloned(),
};
found.ok_or_else(|| {
renox::anyhow::anyhow!(
"no payment gateway is set up for the plan `{}`: set its keys in .env \
(STRIPE_SECRET, XENDIT_SECRET_KEY, …)",
plan.key
)
.into()
})
}
pub(crate) fn plan_by_price(
&self,
config: &Config,
gateway: &str,
price: &str,
) -> Option<&Plan> {
self.plans
.iter()
.find(|p| p.price_id_for(gateway, config).as_deref() == Some(price))
}
}
pub(crate) fn setup(state: &AppState) -> Result<Arc<Setup>> {
state.provided::<Setup>().ok_or_else(|| {
renox::anyhow::anyhow!("renox-billing: add the module with App::module(Billing::new()…)")
.into()
})
}
impl Module for Billing {
fn name(&self) -> &'static str {
"billing"
}
fn migrations(&self) -> &'static [Migration] {
MIGRATIONS
}
fn routes(&self) -> Routes {
handlers::routes()
}
fn register(&self, app: &mut Registry) {
app.provide(self.setup.clone());
app.webhook::<webhook::BillingWebhook>();
app.templates(|env| {
for (name, source) in VIEWS {
if env.get_template(name).is_err() {
renox::view::add_template(env, *name, *source)
.expect("a built-in template compiles");
}
}
});
app.command(
"billing:expire-links",
"Expire payment links that ran out unpaid",
|_args, state| async move {
let expired = Billing::expire_links(&state).await?;
println!("Expired {expired} payment links.");
Ok(())
},
);
app.schedule()
.hourly("billing:expire-links", |state| async move {
Billing::expire_links(&state).await.map(|_| ())
});
app.account_section("billing/section.html", 30, |user, state| async move {
let setup = setup(&state)?;
let billing = Billing::of(&state, &user);
let current = match billing.subscription().await? {
Some(s) => Some(handlers::Current::of(&state, &setup, &billing, s).await?),
None => None,
};
Ok(renox::serde_json::json!({
"current": current,
"plans_url": state.url("billing.plans", &[])?,
}))
});
app.listen(|e: AccountDeleted, state| async move {
forget(&state, &Owner::new("user", e.user_id)).await
});
app.listen(|e: SubscriptionCreated, state| async move {
let s = &e.subscription;
audit(&state, s.owner(), "billing.subscribed", s, None).await
})
.listen(|e: SubscriptionCanceled, state| async move {
let s = &e.subscription;
audit(&state, s.owner(), "billing.canceled", s, None).await
})
.listen(|e: PaymentFailed, state| async move {
match (&e.owner, &e.subscription) {
(Some(owner), Some(s)) => {
audit(
&state,
owner.clone(),
"billing.payment_failed",
s,
Some(e.amount),
)
.await
}
_ => Ok(()),
}
});
}
}
async fn forget(state: &AppState, owner: &Owner) -> Result {
let setup = setup(state)?;
for subscription in Subscription::of(&state.db, owner).await? {
if subscription.ended() || subscription.gateway_id.is_none() {
continue;
}
if let Some(gateway) = setup.gateway(state, &subscription.gateway)
&& let Err(err) = gateway.cancel(state, &subscription, false).await
{
tracing::warn!(error = ?err, subscription = subscription.id, "billing: couldn't cancel a deleted account's subscription");
}
}
for table in ["subscriptions", "billing_customers"] {
renox::db::sql(format!(
"DELETE FROM {table} WHERE billable_type = ? AND billable_id = ?"
))
.bind(owner.kind.as_str())
.bind(owner.id)
.execute(&state.db)
.await?;
}
Ok(())
}
async fn audit(
state: &AppState,
owner: Owner,
action: &str,
subscription: &Subscription,
amount: Option<i64>,
) -> Result {
if owner.kind != "user" {
return Ok(());
}
let has_log = renox::db::sql("SELECT COUNT(*) FROM audit_logs WHERE 1 = 0")
.scalar::<i64>(&state.db)
.await
.is_ok();
if has_log {
let entry =
renox::audit::Entry::new(action)
.user(owner.id)
.data(renox::serde_json::json!({
"plan": subscription.plan,
"gateway": subscription.gateway,
"amount": amount,
}));
renox::audit::record(&state.db, entry).await?;
}
Ok(())
}
#[cfg(doctest)]
#[doc = include_str!("../../../docs/billing.md")]
pub struct Guide;