billing_customers.rs

 1use super::*;
 2
 3#[derive(Debug)]
 4pub struct CreateBillingCustomerParams {
 5    pub user_id: UserId,
 6    pub stripe_customer_id: String,
 7}
 8
 9#[derive(Debug, Default)]
10pub struct UpdateBillingCustomerParams {
11    pub user_id: ActiveValue<UserId>,
12    pub stripe_customer_id: ActiveValue<String>,
13    pub has_overdue_invoices: ActiveValue<bool>,
14}
15
16impl Database {
17    /// Creates a new billing customer.
18    pub async fn create_billing_customer(
19        &self,
20        params: &CreateBillingCustomerParams,
21    ) -> Result<billing_customer::Model> {
22        self.transaction(|tx| async move {
23            let customer = billing_customer::Entity::insert(billing_customer::ActiveModel {
24                user_id: ActiveValue::set(params.user_id),
25                stripe_customer_id: ActiveValue::set(params.stripe_customer_id.clone()),
26                ..Default::default()
27            })
28            .exec_with_returning(&*tx)
29            .await?;
30
31            Ok(customer)
32        })
33        .await
34    }
35
36    /// Updates the specified billing customer.
37    pub async fn update_billing_customer(
38        &self,
39        id: BillingCustomerId,
40        params: &UpdateBillingCustomerParams,
41    ) -> Result<()> {
42        self.transaction(|tx| async move {
43            billing_customer::Entity::update(billing_customer::ActiveModel {
44                id: ActiveValue::set(id),
45                user_id: params.user_id.clone(),
46                stripe_customer_id: params.stripe_customer_id.clone(),
47                has_overdue_invoices: params.has_overdue_invoices.clone(),
48                ..Default::default()
49            })
50            .exec(&*tx)
51            .await?;
52
53            Ok(())
54        })
55        .await
56    }
57
58    /// Returns the billing customer for the user with the specified ID.
59    pub async fn get_billing_customer_by_user_id(
60        &self,
61        user_id: UserId,
62    ) -> Result<Option<billing_customer::Model>> {
63        self.transaction(|tx| async move {
64            Ok(billing_customer::Entity::find()
65                .filter(billing_customer::Column::UserId.eq(user_id))
66                .one(&*tx)
67                .await?)
68        })
69        .await
70    }
71
72    /// Returns the billing customer for the user with the specified Stripe customer ID.
73    pub async fn get_billing_customer_by_stripe_customer_id(
74        &self,
75        stripe_customer_id: &str,
76    ) -> Result<Option<billing_customer::Model>> {
77        self.transaction(|tx| async move {
78            Ok(billing_customer::Entity::find()
79                .filter(billing_customer::Column::StripeCustomerId.eq(stripe_customer_id))
80                .one(&*tx)
81                .await?)
82        })
83        .await
84    }
85}