1#![warn(missing_docs)]
32
33use std::fmt;
34use std::sync::Arc;
35
36use renox::Config;
37use renox::auth::events::AccountDeleted;
38use renox::db::Migration;
39use renox::prelude::*;
40
41mod customer;
42pub mod events;
43pub mod gateway;
44mod guard;
45mod handlers;
46mod model;
47pub mod ngenius;
48pub mod payment;
49mod plan;
50pub mod stripe;
51mod sync;
52mod webhook;
53pub mod xendit;
54
55pub use customer::{Billable, Customer, Owner};
56pub use events::{
57 DisputeLost, DisputeOpened, DisputeWon, PaymentFailed, PaymentLinkExpired, PaymentRefunded,
58 PaymentSucceeded, RefundFailed, RefundSucceeded, SubscriptionCanceled, SubscriptionCreated,
59 SubscriptionPaused, SubscriptionUnpaused, SubscriptionUpdated,
60};
61pub use gateway::{BoxFuture, Checkout, CheckoutRequest, Gateway, Notice, Payment, Remote};
62pub use guard::SubscriptionRoutes;
63pub use model::{BillingCustomer, Subscription, SubscriptionStatus};
64pub use ngenius::Ngenius;
65pub use payment::{
66 BillingPayment, BillingRefund, Charge, ChargeRequest, DisputeState, DisputeUpdate, PaymentKind,
67 PaymentLink, PaymentPage, PaymentState, PaymentStatus, PaymentUpdate, Refund, RefundResult,
68 RefundStatus, RefundUpdate, Unsupported,
69};
70pub use plan::{Interval, Plan};
71pub use stripe::Stripe;
72pub use xendit::Xendit;
73
74const MIGRATIONS: &[Migration] = &[
75 Migration::new(
76 "00010101000900_create_billing_tables",
77 "",
78 Some(include_str!(
79 "../migrations/00010101000900_create_billing_tables.down.sql"
80 )),
81 )
82 .sqlite(
83 include_str!("../migrations/00010101000900_create_billing_tables.up.sql"),
84 None,
85 )
86 .postgres(
87 include_str!("../migrations/00010101000900_create_billing_tables.postgres.up.sql"),
88 None,
89 ),
90 Migration::new(
91 "00010101000910_create_billing_payments",
92 "",
93 Some(include_str!(
94 "../migrations/00010101000910_create_billing_payments.down.sql"
95 )),
96 )
97 .sqlite(
98 include_str!("../migrations/00010101000910_create_billing_payments.up.sql"),
99 None,
100 )
101 .postgres(
102 include_str!("../migrations/00010101000910_create_billing_payments.postgres.up.sql"),
103 None,
104 ),
105 Migration::new(
106 "00010101000920_add_gateway_intent_to_billing_payments",
107 "",
108 Some(include_str!(
109 "../migrations/00010101000920_add_gateway_intent_to_billing_payments.down.sql"
110 )),
111 )
112 .sqlite(
113 include_str!("../migrations/00010101000920_add_gateway_intent_to_billing_payments.up.sql"),
114 None,
115 )
116 .postgres(
117 include_str!(
118 "../migrations/00010101000920_add_gateway_intent_to_billing_payments.postgres.up.sql"
119 ),
120 None,
121 ),
122];
123
124const VIEWS: &[(&str, &str)] = &[
127 ("billing/plans.html", include_str!("../views/plans.html")),
128 (
129 "billing/section.html",
130 include_str!("../views/section.html"),
131 ),
132];
133
134#[derive(Clone)]
138pub struct Billing {
139 setup: Setup,
140}
141
142impl Default for Billing {
143 fn default() -> Self {
144 Self::new()
145 }
146}
147
148#[derive(Clone, Default)]
150pub(crate) struct Setup {
151 pub(crate) plans: Vec<Plan>,
152 pub(crate) gateways: Vec<Arc<dyn Gateway>>,
153 pub(crate) generic_trials: bool,
154 pub(crate) prorate: bool,
155 pub(crate) redirect_to: Option<String>,
156}
157
158impl Billing {
159 pub fn new() -> Self {
162 Self {
163 setup: Setup {
164 prorate: true,
165 ..Setup::default()
166 },
167 }
168 }
169
170 pub fn plan(mut self, plan: Plan) -> Self {
173 self.setup.plans.retain(|p| p.key != plan.key);
174 self.setup.plans.push(plan);
175 self
176 }
177
178 pub fn stripe(self) -> Self {
181 self.gateway(Stripe::from_config())
182 }
183
184 pub fn xendit(self) -> Self {
187 self.gateway(Xendit::from_config())
188 }
189
190 pub fn ngenius(self) -> Self {
194 self.gateway(Ngenius::from_config())
195 }
196
197 pub fn gateway(mut self, gateway: impl Gateway) -> Self {
201 self.setup.gateways.retain(|g| g.name() != gateway.name());
202 self.setup.gateways.push(Arc::new(gateway));
203 self
204 }
205
206 pub fn generic_trials(mut self) -> Self {
210 self.setup.generic_trials = true;
211 self
212 }
213
214 pub fn without_proration(mut self) -> Self {
217 self.setup.prorate = false;
218 self
219 }
220
221 pub fn redirect_to(mut self, path: impl Into<String>) -> Self {
224 self.setup.redirect_to = Some(path.into());
225 self
226 }
227}
228
229impl fmt::Debug for Billing {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.debug_struct("Billing")
232 .field(
233 "plans",
234 &self.setup.plans.iter().map(|p| &p.key).collect::<Vec<_>>(),
235 )
236 .field(
237 "gateways",
238 &self
239 .setup
240 .gateways
241 .iter()
242 .map(|g| g.name().to_owned())
243 .collect::<Vec<_>>(),
244 )
245 .finish_non_exhaustive()
246 }
247}
248
249impl Setup {
250 pub(crate) fn plan(&self, key: &str) -> Result<&Plan> {
252 self.plans
253 .iter()
254 .find(|p| p.key == key)
255 .ok_or_else(|| Error::BadRequest(format!("There's no plan `{key}`.")))
256 }
257
258 pub(crate) fn gateway(&self, state: &AppState, name: &str) -> Option<Arc<dyn Gateway>> {
260 self.gateways
261 .iter()
262 .find(|g| g.name() == name && g.configured(&state.config))
263 .cloned()
264 }
265
266 pub(crate) fn payment_gateway(
269 &self,
270 state: &AppState,
271 name: Option<&str>,
272 ) -> Result<Arc<dyn Gateway>> {
273 let found = match name {
274 Some(name) => self.gateway(state, name),
275 None => self
276 .gateways
277 .iter()
278 .find(|g| g.configured(&state.config))
279 .cloned(),
280 };
281 found.ok_or_else(|| {
282 renox::anyhow::anyhow!(
283 "no payment gateway is set up{}: set its keys in .env",
284 name.map(|n| format!(" for `{n}`")).unwrap_or_default()
285 )
286 .into()
287 })
288 }
289
290 pub(crate) fn gateway_for(&self, state: &AppState, plan: &Plan) -> Result<Arc<dyn Gateway>> {
292 let found = match &plan.gateway {
293 Some(name) => self.gateway(state, name),
294 None => self
295 .gateways
296 .iter()
297 .find(|g| g.configured(&state.config))
298 .cloned(),
299 };
300 found.ok_or_else(|| {
301 renox::anyhow::anyhow!(
302 "no payment gateway is set up for the plan `{}`: set its keys in .env \
303 (STRIPE_SECRET, XENDIT_SECRET_KEY, …)",
304 plan.key
305 )
306 .into()
307 })
308 }
309
310 pub(crate) fn plan_by_price(
312 &self,
313 config: &Config,
314 gateway: &str,
315 price: &str,
316 ) -> Option<&Plan> {
317 self.plans
318 .iter()
319 .find(|p| p.price_id_for(gateway, config).as_deref() == Some(price))
320 }
321}
322
323pub(crate) fn setup(state: &AppState) -> Result<Arc<Setup>> {
325 state.provided::<Setup>().ok_or_else(|| {
326 renox::anyhow::anyhow!("renox-billing: add the module with App::module(Billing::new()…)")
327 .into()
328 })
329}
330
331impl Module for Billing {
332 fn name(&self) -> &'static str {
333 "billing"
334 }
335
336 fn migrations(&self) -> &'static [Migration] {
337 MIGRATIONS
338 }
339
340 fn routes(&self) -> Routes {
341 handlers::routes()
342 }
343
344 fn register(&self, app: &mut Registry) {
345 app.provide(self.setup.clone());
346 app.webhook::<webhook::BillingWebhook>();
347 app.templates(|env| {
348 for (name, source) in VIEWS {
349 if env.get_template(name).is_err() {
351 renox::view::add_template(env, *name, *source)
352 .expect("a built-in template compiles");
353 }
354 }
355 });
356 app.command(
357 "billing:expire-links",
358 "Expire payment links that ran out unpaid",
359 |_args, state| async move {
360 let expired = Billing::expire_links(&state).await?;
361 println!("Expired {expired} payment links.");
362 Ok(())
363 },
364 );
365 app.schedule()
366 .hourly("billing:expire-links", |state| async move {
367 Billing::expire_links(&state).await.map(|_| ())
368 });
369 app.account_section("billing/section.html", 30, |user, state| async move {
370 let setup = setup(&state)?;
371 let billing = Billing::of(&state, &user);
372 let current = match billing.subscription().await? {
373 Some(s) => Some(handlers::Current::of(&state, &setup, &billing, s).await?),
374 None => None,
375 };
376 Ok(renox::serde_json::json!({
377 "current": current,
378 "plans_url": state.url("billing.plans", &[])?,
379 }))
380 });
381 app.listen(|e: AccountDeleted, state| async move {
383 forget(&state, &Owner::new("user", e.user_id)).await
384 });
385 app.listen(|e: SubscriptionCreated, state| async move {
387 let s = &e.subscription;
388 audit(&state, s.owner(), "billing.subscribed", s, None).await
389 })
390 .listen(|e: SubscriptionCanceled, state| async move {
391 let s = &e.subscription;
392 audit(&state, s.owner(), "billing.canceled", s, None).await
393 })
394 .listen(|e: PaymentFailed, state| async move {
395 match (&e.owner, &e.subscription) {
396 (Some(owner), Some(s)) => {
397 audit(
398 &state,
399 owner.clone(),
400 "billing.payment_failed",
401 s,
402 Some(e.amount),
403 )
404 .await
405 }
406 _ => Ok(()),
407 }
408 });
409 }
410}
411
412async fn forget(state: &AppState, owner: &Owner) -> Result {
415 let setup = setup(state)?;
416 for subscription in Subscription::of(&state.db, owner).await? {
417 if subscription.ended() || subscription.gateway_id.is_none() {
418 continue;
419 }
420 if let Some(gateway) = setup.gateway(state, &subscription.gateway)
421 && let Err(err) = gateway.cancel(state, &subscription, false).await
422 {
423 tracing::warn!(error = ?err, subscription = subscription.id, "billing: couldn't cancel a deleted account's subscription");
424 }
425 }
426 for table in ["subscriptions", "billing_customers"] {
427 renox::db::sql(format!(
428 "DELETE FROM {table} WHERE billable_type = ? AND billable_id = ?"
429 ))
430 .bind(owner.kind.as_str())
431 .bind(owner.id)
432 .execute(&state.db)
433 .await?;
434 }
435 Ok(())
436}
437
438async fn audit(
440 state: &AppState,
441 owner: Owner,
442 action: &str,
443 subscription: &Subscription,
444 amount: Option<i64>,
445) -> Result {
446 if owner.kind != "user" {
447 return Ok(());
448 }
449 let has_log = renox::db::sql("SELECT COUNT(*) FROM audit_logs WHERE 1 = 0")
450 .scalar::<i64>(&state.db)
451 .await
452 .is_ok();
453 if has_log {
454 let entry =
455 renox::audit::Entry::new(action)
456 .user(owner.id)
457 .data(renox::serde_json::json!({
458 "plan": subscription.plan,
459 "gateway": subscription.gateway,
460 "amount": amount,
461 }));
462 renox::audit::record(&state.db, entry).await?;
463 }
464 Ok(())
465}
466
467#[cfg(doctest)]
469#[doc = include_str!("../../../docs/billing.md")]
470pub struct Guide;