Skip to content

Automatically cancel servers with failed payments older than 30d #3695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions apps/labrinth/src/database/models/charge_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,27 @@ impl DBCharge {
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}

pub async fn get_cancellable(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<DBCharge>, DatabaseError> {
let charge_type = ChargeType::Subscription.as_str();
let res = select_charges_with_predicate!(
r#"
WHERE
charge_type = $1 AND
status = 'failed' AND due < NOW() - INTERVAL '30 days'
"#,
charge_type
)
.fetch_all(exec)
.await?;

Ok(res
.into_iter()
.map(|r| r.try_into())
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}

pub async fn remove(
id: DBChargeId,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
Expand Down
17 changes: 12 additions & 5 deletions apps/labrinth/src/routes/internal/billing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2284,12 +2284,19 @@ pub async fn index_billing(
) {
info!("Indexing billing queue");
let res = async {
// If a charge has continuously failed for more than a month, it should be cancelled
let charges_to_cancel = DBCharge::get_cancellable(&pool).await?;

for mut charge in charges_to_cancel {
charge.status = ChargeStatus::Cancelled;

let mut transaction = pool.begin().await?;
charge.upsert(&mut transaction).await?;
transaction.commit().await?;
}

// If a charge is open and due or has been attempted more than two days ago, it should be processed
let charges_to_do =
crate::database::models::charge_item::DBCharge::get_chargeable(
&pool,
)
.await?;
let charges_to_do = DBCharge::get_chargeable(&pool).await?;

let prices = product_item::DBProductPrice::get_many(
&charges_to_do
Expand Down
Loading