use std::fmt;
use renox::money::Money;
use renox::prelude::*;
use serde::Serialize;
use crate::{Billing, Owner};
#[derive(DbEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum PaymentKind {
#[default]
Charge,
Link,
}
#[derive(DbEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum PaymentStatus {
#[default]
Pending,
Succeeded,
Failed,
Expired,
Refunded,
PartiallyRefunded,
Disputed,
}
#[derive(DbEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum RefundStatus {
#[default]
Pending,
Succeeded,
Failed,
}
#[derive(Model, Serialize, Debug, Clone)]
#[model(table = "billing_payments")]
pub struct BillingPayment {
pub id: i64,
pub billable_type: Option<String>,
pub billable_id: Option<i64>,
pub reference_type: Option<String>,
pub reference_id: Option<String>,
#[model(money(currency = "currency"))]
pub amount: Money,
pub gateway: String,
pub account: Option<String>,
pub gateway_id: Option<String>,
pub gateway_intent: Option<String>,
pub kind: PaymentKind,
pub status: PaymentStatus,
pub refunded_amount: i64,
pub url: Option<String>,
pub expires_at: Option<DateTime>,
pub evidence_due_by: Option<DateTime>,
#[serde(skip)]
pub synced_at: Option<i64>,
pub created_at: Option<DateTime>,
pub updated_at: Option<DateTime>,
}
impl BillingPayment {
pub fn new(gateway: impl Into<String>, kind: PaymentKind, amount: Money) -> Self {
Self {
id: 0,
billable_type: None,
billable_id: None,
reference_type: None,
reference_id: None,
amount,
gateway: gateway.into(),
account: None,
gateway_id: None,
gateway_intent: None,
kind,
status: PaymentStatus::Pending,
refunded_amount: 0,
url: None,
expires_at: None,
evidence_due_by: None,
synced_at: None,
created_at: None,
updated_at: None,
}
}
pub async fn find_named(db: &Db, gateway: &str, id: &str) -> Result<Option<Self>> {
if let Some(row) = Self::find_at(db, gateway, id).await? {
return Ok(Some(row));
}
Self::where_eq("gateway", gateway)
.where_eq("gateway_intent", id)
.order_by_desc("id")
.first(db)
.await
}
pub fn refunded(&self) -> Money {
Money::new(self.refunded_amount, self.amount.currency)
}
pub fn refundable(&self) -> Money {
let paid = matches!(
self.status,
PaymentStatus::Succeeded | PaymentStatus::PartiallyRefunded | PaymentStatus::Disputed
);
let left = if paid {
(self.amount.minor - self.refunded_amount).max(0)
} else {
0
};
Money::new(left, self.amount.currency)
}
pub fn owner(&self) -> Option<Owner> {
Some(Owner::new(self.billable_type.clone()?, self.billable_id?))
}
pub async fn find_at(db: &Db, gateway: &str, gateway_id: &str) -> Result<Option<Self>> {
Self::where_eq("gateway", gateway)
.where_eq("gateway_id", gateway_id)
.first(db)
.await
}
pub async fn for_reference(
db: &Db,
reference_type: &str,
reference_id: &str,
) -> Result<Vec<Self>> {
Self::where_eq("reference_type", reference_type)
.where_eq("reference_id", reference_id)
.order_by_desc("id")
.get(db)
.await
}
pub async fn refunds(&self, db: &Db) -> Result<Vec<BillingRefund>> {
BillingRefund::where_eq("payment_id", self.id)
.order_by("id")
.get(db)
.await
}
}
#[derive(Model, Serialize, Default, Debug, Clone)]
#[model(table = "billing_refunds")]
pub struct BillingRefund {
pub id: i64,
pub payment_id: i64,
pub gateway_id: Option<String>,
pub amount: i64,
pub status: RefundStatus,
pub reason: Option<String>,
pub created_at: Option<DateTime>,
pub updated_at: Option<DateTime>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsupported {
pub gateway: String,
pub operation: String,
}
impl Unsupported {
pub fn new(gateway: impl Into<String>, operation: impl Into<String>) -> Self {
Self {
gateway: gateway.into(),
operation: operation.into(),
}
}
pub fn of(err: &Error) -> Option<&Unsupported> {
match err {
Error::Internal(inner) => inner.downcast_ref::<Unsupported>(),
_ => None,
}
}
}
impl fmt::Display for Unsupported {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"The gateway {} does not support {}.",
self.gateway, self.operation
)
}
}
impl std::error::Error for Unsupported {}
pub(crate) async fn start(
state: &AppState,
gateway: Option<&str>,
mut request: ChargeRequest,
) -> Result<BillingPayment> {
if request.amount.minor <= 0 {
return Err(Error::BadRequest(
"A payment must be for more than zero.".into(),
));
}
let gateway = crate::setup(state)?.payment_gateway(state, gateway)?;
let mut row = BillingPayment::new(gateway.name(), request.kind, request.amount);
row.account = request.account.clone();
row.expires_at = request.expires_at;
row.reference_type = request.reference_type.clone();
row.reference_id = request.reference_id.clone();
if let Some(owner) = &request.owner {
row.billable_type = Some(owner.kind.clone());
row.billable_id = Some(owner.id);
}
let mut row = BillingPayment::create(&state.db, row).await?;
request.payment_id = row.id;
let page = match request.kind {
PaymentKind::Charge => gateway.charge(state, &request).await,
PaymentKind::Link => gateway.payment_link(state, &request).await,
};
let page = match page {
Ok(page) => page,
Err(err) => {
BillingPayment::query()
.where_eq("id", row.id)
.delete(&state.db)
.await?;
return Err(err);
}
};
row.gateway_id = Some(page.gateway_id);
row.url = page.url;
if page.expires_at.is_some() {
row.expires_at = page.expires_at;
}
row.save(&state.db).await?;
Ok(row)
}
impl Billing {
pub async fn payment_link(state: &AppState, link: PaymentLink) -> Result<BillingPayment> {
start(state, link.gateway(), link.request().clone()).await
}
pub async fn refund(
state: &AppState,
payment_id: i64,
refund: Refund,
) -> Result<BillingRefund> {
let mut payment = BillingPayment::find(&state.db, payment_id)
.await?
.ok_or(Error::NotFound)?;
if refund.amount.currency != payment.amount.currency || refund.amount.minor <= 0 {
return Err(Error::BadRequest(
"A refund is a positive amount in the payment's currency.".into(),
));
}
let pending: i64 = BillingRefund::where_eq("payment_id", payment.id)
.where_eq("status", RefundStatus::Pending)
.sum(&state.db, "amount")
.await?;
if refund.amount.minor > payment.refundable().minor - pending {
return Err(Error::BadRequest(
"That is more than is left to refund.".into(),
));
}
let gateway = crate::setup(state)?.payment_gateway(state, Some(&payment.gateway))?;
let mut row = BillingRefund::create(
&state.db,
BillingRefund {
payment_id: payment.id,
amount: refund.amount.minor,
reason: refund.reason.clone(),
..Default::default()
},
)
.await?;
let result = match gateway.refund(state, &payment, &refund).await {
Ok(result) => result,
Err(err) => {
BillingRefund::query()
.where_eq("id", row.id)
.delete(&state.db)
.await?;
return Err(err);
}
};
row.gateway_id = result.gateway_id;
row.status = result.status;
row.save(&state.db).await?;
if row.status == RefundStatus::Succeeded {
crate::sync::refund_done(state, &mut payment, row.amount).await?;
}
Ok(row)
}
pub async fn expire_links(state: &AppState) -> Result<usize> {
let due = BillingPayment::where_eq("kind", PaymentKind::Link)
.where_eq("status", PaymentStatus::Pending)
.where_op("expires_at", "<=", renox::db::now())
.order_by("id")
.get(&state.db)
.await?;
let setup = crate::setup(state)?;
let mut expired = 0;
for link in due {
let id = link.id;
if link.gateway_id.is_some() {
let asked = match setup.payment_gateway(state, Some(&link.gateway)) {
Ok(gateway) => gateway.payment_status(state, &link).await,
Err(err) => Err(err),
};
match asked {
Ok(reported) => crate::sync::apply_state(state, link, &reported).await?,
Err(err) if Unsupported::of(&err).is_some() => {}
Err(err) => {
tracing::warn!(error = ?err, payment = id, "billing: couldn't check a payment link before expiring it");
continue;
}
}
}
let Some(link) = BillingPayment::find(&state.db, id).await? else {
continue;
};
if link.status == PaymentStatus::Pending {
crate::sync::apply_status(state, link, PaymentStatus::Expired, None).await?;
expired += 1;
}
}
Ok(expired)
}
pub async fn payment_status(state: &AppState, payment_id: i64) -> Result<PaymentState> {
let payment = BillingPayment::find(&state.db, payment_id)
.await?
.ok_or(Error::NotFound)?;
let gateway = crate::setup(state)?.payment_gateway(state, Some(&payment.gateway))?;
let reported = gateway.payment_status(state, &payment).await?;
crate::sync::apply_state(state, payment, &reported).await?;
Ok(reported)
}
}
macro_rules! request_builder {
($name:ident) => {
impl $name {
pub fn owner(mut self, owner: Owner) -> Self {
self.request.owner = Some(owner);
self
}
pub fn reference(mut self, kind: impl Into<String>, id: impl ToString) -> Self {
self.request.reference_type = Some(kind.into());
self.request.reference_id = Some(id.to_string());
self
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.request.description = Some(text.into());
self
}
pub fn success_url(mut self, url: impl Into<String>) -> Self {
self.request.success_url = Some(url.into());
self
}
pub fn cancel_url(mut self, url: impl Into<String>) -> Self {
self.request.cancel_url = Some(url.into());
self
}
pub fn expires_at(mut self, at: DateTime) -> Self {
self.request.expires_at = Some(at);
self
}
pub fn via(mut self, gateway: impl Into<String>) -> Self {
self.gateway = Some(gateway.into());
self
}
pub fn account(mut self, account: impl Into<String>) -> Self {
self.request.account = Some(account.into());
self
}
pub fn gateway(&self) -> Option<&str> {
self.gateway.as_deref()
}
pub fn request(&self) -> &ChargeRequest {
&self.request
}
}
};
}
#[derive(Debug, Clone)]
pub struct Charge {
gateway: Option<String>,
request: ChargeRequest,
}
impl Charge {
pub fn new(amount: Money) -> Self {
Self {
gateway: None,
request: ChargeRequest::new(PaymentKind::Charge, amount),
}
}
}
request_builder!(Charge);
#[derive(Debug, Clone)]
pub struct PaymentLink {
gateway: Option<String>,
request: ChargeRequest,
}
impl PaymentLink {
pub fn new(amount: Money) -> Self {
Self {
gateway: None,
request: ChargeRequest::new(PaymentKind::Link, amount),
}
}
}
request_builder!(PaymentLink);
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ChargeRequest {
pub kind: PaymentKind,
pub payment_id: i64,
pub amount: Money,
pub owner: Option<Owner>,
pub reference_type: Option<String>,
pub reference_id: Option<String>,
pub description: Option<String>,
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub expires_at: Option<DateTime>,
pub account: Option<String>,
}
impl ChargeRequest {
pub fn new(kind: PaymentKind, amount: Money) -> Self {
Self {
kind,
payment_id: 0,
amount,
owner: None,
reference_type: None,
reference_id: None,
description: None,
success_url: None,
cancel_url: None,
expires_at: None,
account: None,
}
}
pub fn metadata(&self) -> Vec<(&'static str, String)> {
let mut meta = vec![("renox_payment", self.payment_id.to_string())];
if let Some(owner) = &self.owner {
meta.push(("renox_billable", owner.key()));
}
if let Some(kind) = &self.reference_type {
meta.push(("renox_reference_type", kind.clone()));
}
if let Some(id) = &self.reference_id {
meta.push(("renox_reference_id", id.clone()));
}
meta
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PaymentPage {
pub gateway_id: String,
pub url: Option<String>,
pub expires_at: Option<DateTime>,
}
impl PaymentPage {
pub fn new(gateway_id: impl Into<String>, url: impl Into<String>) -> Self {
Self {
gateway_id: gateway_id.into(),
url: Some(url.into()),
expires_at: None,
}
}
pub fn expires_at(mut self, at: DateTime) -> Self {
self.expires_at = Some(at);
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Refund {
pub amount: Money,
pub reason: Option<String>,
}
impl Refund {
pub fn new(amount: Money) -> Self {
Self {
amount,
reason: None,
}
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RefundResult {
pub gateway_id: Option<String>,
pub status: RefundStatus,
}
impl RefundResult {
pub fn pending(gateway_id: impl Into<String>) -> Self {
Self {
gateway_id: Some(gateway_id.into()),
status: RefundStatus::Pending,
}
}
pub fn succeeded(gateway_id: impl Into<String>) -> Self {
Self {
gateway_id: Some(gateway_id.into()),
status: RefundStatus::Succeeded,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PaymentState {
pub status: PaymentStatus,
pub at: Option<i64>,
pub refunds: Vec<RefundUpdate>,
pub intent: Option<String>,
}
impl PaymentState {
pub fn new(status: PaymentStatus) -> Self {
Self {
status,
at: None,
refunds: Vec::new(),
intent: None,
}
}
pub fn intent(mut self, id: impl Into<String>) -> Self {
self.intent = Some(id.into());
self
}
pub fn at(mut self, unix_seconds: i64) -> Self {
self.at = Some(unix_seconds);
self
}
pub fn refund(mut self, update: RefundUpdate) -> Self {
self.refunds.push(update);
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PaymentUpdate {
pub gateway_id: String,
pub status: PaymentStatus,
pub at: Option<i64>,
pub intent: Option<String>,
}
impl PaymentUpdate {
pub fn new(gateway_id: impl Into<String>, status: PaymentStatus) -> Self {
Self {
gateway_id: gateway_id.into(),
status,
at: None,
intent: None,
}
}
pub fn at(mut self, unix_seconds: i64) -> Self {
self.at = Some(unix_seconds);
self
}
pub fn intent(mut self, id: impl Into<String>) -> Self {
self.intent = Some(id.into());
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RefundUpdate {
pub gateway_id: String,
pub payment_gateway_id: Option<String>,
pub status: RefundStatus,
pub amount: Option<i64>,
pub reason: Option<String>,
pub at: Option<i64>,
}
impl RefundUpdate {
pub fn new(gateway_id: impl Into<String>, status: RefundStatus) -> Self {
Self {
gateway_id: gateway_id.into(),
payment_gateway_id: None,
status,
amount: None,
reason: None,
at: None,
}
}
pub fn payment(mut self, id: impl Into<String>) -> Self {
self.payment_gateway_id = Some(id.into());
self
}
pub fn amount(mut self, minor: i64) -> Self {
self.amount = Some(minor);
self
}
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
pub fn at(mut self, unix_seconds: i64) -> Self {
self.at = Some(unix_seconds);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DisputeState {
Opened,
Won,
Lost,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DisputeUpdate {
pub payment_gateway_id: String,
pub state: DisputeState,
pub evidence_due_by: Option<DateTime>,
pub at: Option<i64>,
}
impl DisputeUpdate {
pub fn new(payment_gateway_id: impl Into<String>, state: DisputeState) -> Self {
Self {
payment_gateway_id: payment_gateway_id.into(),
state,
evidence_due_by: None,
at: None,
}
}
pub fn evidence_due_by(mut self, at: DateTime) -> Self {
self.evidence_due_by = Some(at);
self
}
pub fn at(mut self, unix_seconds: i64) -> Self {
self.at = Some(unix_seconds);
self
}
}