stripe_shared/
customer_balance_transaction.rs

1/// Each customer has a [Balance](https://stripe.com/docs/api/customers/object#customer_object-balance) value,.
2/// which denotes a debit or credit that's automatically applied to their next invoice upon finalization.
3/// You may modify the value directly by using the [update customer API](https://stripe.com/docs/api/customers/update),.
4/// or by creating a Customer Balance Transaction, which increments or decrements the customer's `balance` by the specified `amount`.
5///
6/// Related guide: [Customer balance](https://stripe.com/docs/billing/customer/balance)
7///
8/// For more details see <<https://stripe.com/docs/api/customer_balance_transactions/object>>.
9#[derive(Clone, Debug)]
10#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
11pub struct CustomerBalanceTransaction {
12    /// The amount of the transaction.
13    /// A negative value is a credit for the customer's balance, and a positive value is a debit to the customer's `balance`.
14    pub amount: i64,
15    /// The ID of the checkout session (if any) that created the transaction.
16    pub checkout_session: Option<stripe_types::Expandable<stripe_shared::CheckoutSession>>,
17    /// Time at which the object was created. Measured in seconds since the Unix epoch.
18    pub created: stripe_types::Timestamp,
19    /// The ID of the credit note (if any) related to the transaction.
20    pub credit_note: Option<stripe_types::Expandable<stripe_shared::CreditNote>>,
21    /// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
22    /// Must be a [supported currency](https://stripe.com/docs/currencies).
23    pub currency: stripe_types::Currency,
24    /// The ID of the customer the transaction belongs to.
25    pub customer: stripe_types::Expandable<stripe_shared::Customer>,
26    /// An arbitrary string attached to the object. Often useful for displaying to users.
27    pub description: Option<String>,
28    /// The customer's `balance` after the transaction was applied.
29    /// A negative value decreases the amount due on the customer's next invoice.
30    /// A positive value increases the amount due on the customer's next invoice.
31    pub ending_balance: i64,
32    /// Unique identifier for the object.
33    pub id: stripe_shared::CustomerBalanceTransactionId,
34    /// The ID of the invoice (if any) related to the transaction.
35    pub invoice: Option<stripe_types::Expandable<stripe_shared::Invoice>>,
36    /// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
37    pub livemode: bool,
38    /// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object.
39    /// This can be useful for storing additional information about the object in a structured format.
40    pub metadata: Option<std::collections::HashMap<String, String>>,
41    /// Transaction type: `adjustment`, `applied_to_invoice`, `credit_note`, `initial`, `invoice_overpaid`, `invoice_too_large`, `invoice_too_small`, `unspent_receiver_credit`, `unapplied_from_invoice`, `checkout_session_subscription_payment`, or `checkout_session_subscription_payment_canceled`.
42    /// See the [Customer Balance page](https://stripe.com/docs/billing/customer/balance#types) to learn more about transaction types.
43    #[cfg_attr(feature = "deserialize", serde(rename = "type"))]
44    pub type_: CustomerBalanceTransactionType,
45}
46#[doc(hidden)]
47pub struct CustomerBalanceTransactionBuilder {
48    amount: Option<i64>,
49    checkout_session: Option<Option<stripe_types::Expandable<stripe_shared::CheckoutSession>>>,
50    created: Option<stripe_types::Timestamp>,
51    credit_note: Option<Option<stripe_types::Expandable<stripe_shared::CreditNote>>>,
52    currency: Option<stripe_types::Currency>,
53    customer: Option<stripe_types::Expandable<stripe_shared::Customer>>,
54    description: Option<Option<String>>,
55    ending_balance: Option<i64>,
56    id: Option<stripe_shared::CustomerBalanceTransactionId>,
57    invoice: Option<Option<stripe_types::Expandable<stripe_shared::Invoice>>>,
58    livemode: Option<bool>,
59    metadata: Option<Option<std::collections::HashMap<String, String>>>,
60    type_: Option<CustomerBalanceTransactionType>,
61}
62
63#[allow(
64    unused_variables,
65    irrefutable_let_patterns,
66    clippy::let_unit_value,
67    clippy::match_single_binding,
68    clippy::single_match
69)]
70const _: () = {
71    use miniserde::de::{Map, Visitor};
72    use miniserde::json::Value;
73    use miniserde::{Deserialize, Result, make_place};
74    use stripe_types::miniserde_helpers::FromValueOpt;
75    use stripe_types::{MapBuilder, ObjectDeser};
76
77    make_place!(Place);
78
79    impl Deserialize for CustomerBalanceTransaction {
80        fn begin(out: &mut Option<Self>) -> &mut dyn Visitor {
81            Place::new(out)
82        }
83    }
84
85    struct Builder<'a> {
86        out: &'a mut Option<CustomerBalanceTransaction>,
87        builder: CustomerBalanceTransactionBuilder,
88    }
89
90    impl Visitor for Place<CustomerBalanceTransaction> {
91        fn map(&mut self) -> Result<Box<dyn Map + '_>> {
92            Ok(Box::new(Builder {
93                out: &mut self.out,
94                builder: CustomerBalanceTransactionBuilder::deser_default(),
95            }))
96        }
97    }
98
99    impl MapBuilder for CustomerBalanceTransactionBuilder {
100        type Out = CustomerBalanceTransaction;
101        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
102            Ok(match k {
103                "amount" => Deserialize::begin(&mut self.amount),
104                "checkout_session" => Deserialize::begin(&mut self.checkout_session),
105                "created" => Deserialize::begin(&mut self.created),
106                "credit_note" => Deserialize::begin(&mut self.credit_note),
107                "currency" => Deserialize::begin(&mut self.currency),
108                "customer" => Deserialize::begin(&mut self.customer),
109                "description" => Deserialize::begin(&mut self.description),
110                "ending_balance" => Deserialize::begin(&mut self.ending_balance),
111                "id" => Deserialize::begin(&mut self.id),
112                "invoice" => Deserialize::begin(&mut self.invoice),
113                "livemode" => Deserialize::begin(&mut self.livemode),
114                "metadata" => Deserialize::begin(&mut self.metadata),
115                "type" => Deserialize::begin(&mut self.type_),
116
117                _ => <dyn Visitor>::ignore(),
118            })
119        }
120
121        fn deser_default() -> Self {
122            Self {
123                amount: Deserialize::default(),
124                checkout_session: Deserialize::default(),
125                created: Deserialize::default(),
126                credit_note: Deserialize::default(),
127                currency: Deserialize::default(),
128                customer: Deserialize::default(),
129                description: Deserialize::default(),
130                ending_balance: Deserialize::default(),
131                id: Deserialize::default(),
132                invoice: Deserialize::default(),
133                livemode: Deserialize::default(),
134                metadata: Deserialize::default(),
135                type_: Deserialize::default(),
136            }
137        }
138
139        fn take_out(&mut self) -> Option<Self::Out> {
140            let (
141                Some(amount),
142                Some(checkout_session),
143                Some(created),
144                Some(credit_note),
145                Some(currency),
146                Some(customer),
147                Some(description),
148                Some(ending_balance),
149                Some(id),
150                Some(invoice),
151                Some(livemode),
152                Some(metadata),
153                Some(type_),
154            ) = (
155                self.amount,
156                self.checkout_session.take(),
157                self.created,
158                self.credit_note.take(),
159                self.currency.take(),
160                self.customer.take(),
161                self.description.take(),
162                self.ending_balance,
163                self.id.take(),
164                self.invoice.take(),
165                self.livemode,
166                self.metadata.take(),
167                self.type_,
168            )
169            else {
170                return None;
171            };
172            Some(Self::Out {
173                amount,
174                checkout_session,
175                created,
176                credit_note,
177                currency,
178                customer,
179                description,
180                ending_balance,
181                id,
182                invoice,
183                livemode,
184                metadata,
185                type_,
186            })
187        }
188    }
189
190    impl Map for Builder<'_> {
191        fn key(&mut self, k: &str) -> Result<&mut dyn Visitor> {
192            self.builder.key(k)
193        }
194
195        fn finish(&mut self) -> Result<()> {
196            *self.out = self.builder.take_out();
197            Ok(())
198        }
199    }
200
201    impl ObjectDeser for CustomerBalanceTransaction {
202        type Builder = CustomerBalanceTransactionBuilder;
203    }
204
205    impl FromValueOpt for CustomerBalanceTransaction {
206        fn from_value(v: Value) -> Option<Self> {
207            let Value::Object(obj) = v else {
208                return None;
209            };
210            let mut b = CustomerBalanceTransactionBuilder::deser_default();
211            for (k, v) in obj {
212                match k.as_str() {
213                    "amount" => b.amount = FromValueOpt::from_value(v),
214                    "checkout_session" => b.checkout_session = FromValueOpt::from_value(v),
215                    "created" => b.created = FromValueOpt::from_value(v),
216                    "credit_note" => b.credit_note = FromValueOpt::from_value(v),
217                    "currency" => b.currency = FromValueOpt::from_value(v),
218                    "customer" => b.customer = FromValueOpt::from_value(v),
219                    "description" => b.description = FromValueOpt::from_value(v),
220                    "ending_balance" => b.ending_balance = FromValueOpt::from_value(v),
221                    "id" => b.id = FromValueOpt::from_value(v),
222                    "invoice" => b.invoice = FromValueOpt::from_value(v),
223                    "livemode" => b.livemode = FromValueOpt::from_value(v),
224                    "metadata" => b.metadata = FromValueOpt::from_value(v),
225                    "type" => b.type_ = FromValueOpt::from_value(v),
226
227                    _ => {}
228                }
229            }
230            b.take_out()
231        }
232    }
233};
234#[cfg(feature = "serialize")]
235impl serde::Serialize for CustomerBalanceTransaction {
236    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
237        use serde::ser::SerializeStruct;
238        let mut s = s.serialize_struct("CustomerBalanceTransaction", 14)?;
239        s.serialize_field("amount", &self.amount)?;
240        s.serialize_field("checkout_session", &self.checkout_session)?;
241        s.serialize_field("created", &self.created)?;
242        s.serialize_field("credit_note", &self.credit_note)?;
243        s.serialize_field("currency", &self.currency)?;
244        s.serialize_field("customer", &self.customer)?;
245        s.serialize_field("description", &self.description)?;
246        s.serialize_field("ending_balance", &self.ending_balance)?;
247        s.serialize_field("id", &self.id)?;
248        s.serialize_field("invoice", &self.invoice)?;
249        s.serialize_field("livemode", &self.livemode)?;
250        s.serialize_field("metadata", &self.metadata)?;
251        s.serialize_field("type", &self.type_)?;
252
253        s.serialize_field("object", "customer_balance_transaction")?;
254        s.end()
255    }
256}
257/// Transaction type: `adjustment`, `applied_to_invoice`, `credit_note`, `initial`, `invoice_overpaid`, `invoice_too_large`, `invoice_too_small`, `unspent_receiver_credit`, `unapplied_from_invoice`, `checkout_session_subscription_payment`, or `checkout_session_subscription_payment_canceled`.
258/// See the [Customer Balance page](https://stripe.com/docs/billing/customer/balance#types) to learn more about transaction types.
259#[derive(Copy, Clone, Eq, PartialEq)]
260pub enum CustomerBalanceTransactionType {
261    Adjustment,
262    AppliedToInvoice,
263    CheckoutSessionSubscriptionPayment,
264    CheckoutSessionSubscriptionPaymentCanceled,
265    CreditNote,
266    Initial,
267    InvoiceOverpaid,
268    InvoiceTooLarge,
269    InvoiceTooSmall,
270    Migration,
271    UnappliedFromInvoice,
272    UnspentReceiverCredit,
273}
274impl CustomerBalanceTransactionType {
275    pub fn as_str(self) -> &'static str {
276        use CustomerBalanceTransactionType::*;
277        match self {
278            Adjustment => "adjustment",
279            AppliedToInvoice => "applied_to_invoice",
280            CheckoutSessionSubscriptionPayment => "checkout_session_subscription_payment",
281            CheckoutSessionSubscriptionPaymentCanceled => {
282                "checkout_session_subscription_payment_canceled"
283            }
284            CreditNote => "credit_note",
285            Initial => "initial",
286            InvoiceOverpaid => "invoice_overpaid",
287            InvoiceTooLarge => "invoice_too_large",
288            InvoiceTooSmall => "invoice_too_small",
289            Migration => "migration",
290            UnappliedFromInvoice => "unapplied_from_invoice",
291            UnspentReceiverCredit => "unspent_receiver_credit",
292        }
293    }
294}
295
296impl std::str::FromStr for CustomerBalanceTransactionType {
297    type Err = stripe_types::StripeParseError;
298    fn from_str(s: &str) -> Result<Self, Self::Err> {
299        use CustomerBalanceTransactionType::*;
300        match s {
301            "adjustment" => Ok(Adjustment),
302            "applied_to_invoice" => Ok(AppliedToInvoice),
303            "checkout_session_subscription_payment" => Ok(CheckoutSessionSubscriptionPayment),
304            "checkout_session_subscription_payment_canceled" => {
305                Ok(CheckoutSessionSubscriptionPaymentCanceled)
306            }
307            "credit_note" => Ok(CreditNote),
308            "initial" => Ok(Initial),
309            "invoice_overpaid" => Ok(InvoiceOverpaid),
310            "invoice_too_large" => Ok(InvoiceTooLarge),
311            "invoice_too_small" => Ok(InvoiceTooSmall),
312            "migration" => Ok(Migration),
313            "unapplied_from_invoice" => Ok(UnappliedFromInvoice),
314            "unspent_receiver_credit" => Ok(UnspentReceiverCredit),
315            _ => Err(stripe_types::StripeParseError),
316        }
317    }
318}
319impl std::fmt::Display for CustomerBalanceTransactionType {
320    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
321        f.write_str(self.as_str())
322    }
323}
324
325impl std::fmt::Debug for CustomerBalanceTransactionType {
326    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
327        f.write_str(self.as_str())
328    }
329}
330#[cfg(feature = "serialize")]
331impl serde::Serialize for CustomerBalanceTransactionType {
332    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
333    where
334        S: serde::Serializer,
335    {
336        serializer.serialize_str(self.as_str())
337    }
338}
339impl miniserde::Deserialize for CustomerBalanceTransactionType {
340    fn begin(out: &mut Option<Self>) -> &mut dyn miniserde::de::Visitor {
341        crate::Place::new(out)
342    }
343}
344
345impl miniserde::de::Visitor for crate::Place<CustomerBalanceTransactionType> {
346    fn string(&mut self, s: &str) -> miniserde::Result<()> {
347        use std::str::FromStr;
348        self.out = Some(CustomerBalanceTransactionType::from_str(s).map_err(|_| miniserde::Error)?);
349        Ok(())
350    }
351}
352
353stripe_types::impl_from_val_with_from_str!(CustomerBalanceTransactionType);
354#[cfg(feature = "deserialize")]
355impl<'de> serde::Deserialize<'de> for CustomerBalanceTransactionType {
356    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
357        use std::str::FromStr;
358        let s: std::borrow::Cow<'de, str> = serde::Deserialize::deserialize(deserializer)?;
359        Self::from_str(&s).map_err(|_| {
360            serde::de::Error::custom("Unknown value for CustomerBalanceTransactionType")
361        })
362    }
363}
364impl stripe_types::Object for CustomerBalanceTransaction {
365    type Id = stripe_shared::CustomerBalanceTransactionId;
366    fn id(&self) -> &Self::Id {
367        &self.id
368    }
369
370    fn into_id(self) -> Self::Id {
371        self.id
372    }
373}
374stripe_types::def_id!(CustomerBalanceTransactionId);