Refunds + Upgrading/Downgrading plans (#2983)

* Refunds + Upgrading/Downgrading plans

* Servers list route

* Finish, lint

* add GAM fee to payouts

* Sync payment intent id with stripe

* fix lint, update migrations

* Remove tauri generated files

* Register refund route

* fix refund bugs
This commit is contained in:
Geometrically
2024-12-06 19:37:17 -08:00
committed by GitHub
parent 2cfb637451
commit 2987f507fe
41 changed files with 1045 additions and 13604 deletions

View File

@@ -8,7 +8,7 @@ pub struct Success<'a> {
pub name: &'a str,
}
impl<'a> Success<'a> {
impl Success<'_> {
pub fn render(self) -> HttpResponse {
let html = include_str!("success.html");

View File

@@ -1,7 +1,9 @@
use crate::database::models::{
ChargeId, DatabaseError, ProductPriceId, UserId, UserSubscriptionId,
};
use crate::models::billing::{ChargeStatus, ChargeType, PriceDuration};
use crate::models::billing::{
ChargeStatus, ChargeType, PaymentPlatform, PriceDuration,
};
use chrono::{DateTime, Utc};
use std::convert::{TryFrom, TryInto};
@@ -18,6 +20,14 @@ pub struct ChargeItem {
pub type_: ChargeType,
pub subscription_id: Option<UserSubscriptionId>,
pub subscription_interval: Option<PriceDuration>,
pub payment_platform: PaymentPlatform,
pub payment_platform_id: Option<String>,
pub parent_charge_id: Option<ChargeId>,
// Net is always in USD
pub net: Option<i64>,
}
struct ChargeResult {
@@ -32,6 +42,10 @@ struct ChargeResult {
charge_type: String,
subscription_id: Option<i64>,
subscription_interval: Option<String>,
payment_platform: String,
payment_platform_id: Option<String>,
parent_charge_id: Option<i64>,
net: Option<i64>,
}
impl TryFrom<ChargeResult> for ChargeItem {
@@ -52,6 +66,10 @@ impl TryFrom<ChargeResult> for ChargeItem {
subscription_interval: r
.subscription_interval
.map(|x| PriceDuration::from_string(&x)),
payment_platform: PaymentPlatform::from_string(&r.payment_platform),
payment_platform_id: r.payment_platform_id,
parent_charge_id: r.parent_charge_id.map(ChargeId),
net: r.net,
})
}
}
@@ -61,7 +79,15 @@ macro_rules! select_charges_with_predicate {
sqlx::query_as!(
ChargeResult,
r#"
SELECT id, user_id, price_id, amount, currency_code, status, due, last_attempt, charge_type, subscription_id, subscription_interval
SELECT
id, user_id, price_id, amount, currency_code, status, due, last_attempt,
charge_type, subscription_id,
-- Workaround for https://github.com/launchbadge/sqlx/issues/3336
subscription_interval AS "subscription_interval?",
payment_platform,
payment_platform_id AS "payment_platform_id?",
parent_charge_id AS "parent_charge_id?",
net AS "net?"
FROM charges
"#
+ $predicate,
@@ -77,15 +103,19 @@ impl ChargeItem {
) -> Result<ChargeId, DatabaseError> {
sqlx::query!(
r#"
INSERT INTO charges (id, user_id, price_id, amount, currency_code, charge_type, status, due, last_attempt, subscription_id, subscription_interval)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
INSERT INTO charges (id, user_id, price_id, amount, currency_code, charge_type, status, due, last_attempt, subscription_id, subscription_interval, payment_platform, payment_platform_id, parent_charge_id, net)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
ON CONFLICT (id)
DO UPDATE
SET status = EXCLUDED.status,
last_attempt = EXCLUDED.last_attempt,
due = EXCLUDED.due,
subscription_id = EXCLUDED.subscription_id,
subscription_interval = EXCLUDED.subscription_interval
subscription_interval = EXCLUDED.subscription_interval,
payment_platform = EXCLUDED.payment_platform,
payment_platform_id = EXCLUDED.payment_platform_id,
parent_charge_id = EXCLUDED.parent_charge_id,
net = EXCLUDED.net
"#,
self.id.0,
self.user_id.0,
@@ -98,6 +128,10 @@ impl ChargeItem {
self.last_attempt,
self.subscription_id.map(|x| x.0),
self.subscription_interval.map(|x| x.as_str()),
self.payment_platform.as_str(),
self.payment_platform_id.as_deref(),
self.parent_charge_id.map(|x| x.0),
self.net,
)
.execute(&mut **transaction)
.await?;
@@ -135,6 +169,24 @@ impl ChargeItem {
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}
pub async fn get_children(
charge_id: ChargeId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> {
let charge_id = charge_id.0;
let res = select_charges_with_predicate!(
"WHERE parent_charge_id = $1",
charge_id
)
.fetch_all(exec)
.await?;
Ok(res
.into_iter()
.map(|r| r.try_into())
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}
pub async fn get_open_subscription(
user_subscription_id: UserSubscriptionId,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
@@ -153,9 +205,18 @@ impl ChargeItem {
pub async fn get_chargeable(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> {
let now = Utc::now();
let res = select_charges_with_predicate!("WHERE (status = 'open' AND due < $1) OR (status = 'failed' AND last_attempt < $1 - INTERVAL '2 days')", now)
let charge_type = ChargeType::Subscription.as_str();
let res = select_charges_with_predicate!(
r#"
WHERE
charge_type = $1 AND
(
(status = 'open' AND due < NOW()) OR
(status = 'failed' AND last_attempt < NOW() - INTERVAL '2 days')
)
"#,
charge_type
)
.fetch_all(exec)
.await?;
@@ -168,10 +229,18 @@ impl ChargeItem {
pub async fn get_unprovision(
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<ChargeItem>, DatabaseError> {
let now = Utc::now();
let res =
select_charges_with_predicate!("WHERE (status = 'cancelled' AND due < $1) OR (status = 'failed' AND last_attempt < $1 - INTERVAL '2 days')", now)
let charge_type = ChargeType::Subscription.as_str();
let res = select_charges_with_predicate!(
r#"
WHERE
charge_type = $1 AND
(
(status = 'cancelled' AND due < NOW()) OR
(status = 'failed' AND last_attempt < NOW() - INTERVAL '2 days')
)
"#,
charge_type
)
.fetch_all(exec)
.await?;

View File

@@ -104,6 +104,29 @@ impl UserSubscriptionItem {
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}
pub async fn get_all_servers(
status: Option<SubscriptionStatus>,
exec: impl sqlx::Executor<'_, Database = sqlx::Postgres>,
) -> Result<Vec<UserSubscriptionItem>, DatabaseError> {
let status = status.map(|x| x.as_str());
let results = select_user_subscriptions_with_predicate!(
r#"
INNER JOIN products_prices pp ON us.price_id = pp.id
INNER JOIN products p ON p.metadata @> '{"type": "pyro"}'
WHERE $1::text IS NULL OR us.status = $1::text
"#,
status
)
.fetch_all(exec)
.await?;
Ok(results
.into_iter()
.map(|r| r.try_into())
.collect::<Result<Vec<_>, serde_json::Error>>()?)
}
pub async fn upsert(
&self,
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,

View File

@@ -161,7 +161,7 @@ pub struct Charge {
pub id: ChargeId,
pub user_id: UserId,
pub price_id: ProductPriceId,
pub amount: i64,
pub amount: u64,
pub currency_code: String,
pub status: ChargeStatus,
pub due: DateTime<Utc>,
@@ -170,14 +170,16 @@ pub struct Charge {
pub type_: ChargeType,
pub subscription_id: Option<UserSubscriptionId>,
pub subscription_interval: Option<PriceDuration>,
pub platform: PaymentPlatform,
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum ChargeType {
OneTime,
Subscription,
Proration,
Refund,
}
impl ChargeType {
@@ -186,6 +188,7 @@ impl ChargeType {
ChargeType::OneTime => "one-time",
ChargeType::Subscription { .. } => "subscription",
ChargeType::Proration { .. } => "proration",
ChargeType::Refund => "refund",
}
}
@@ -194,12 +197,13 @@ impl ChargeType {
"one-time" => ChargeType::OneTime,
"subscription" => ChargeType::Subscription,
"proration" => ChargeType::Proration,
"refund" => ChargeType::Refund,
_ => ChargeType::OneTime,
}
}
}
#[derive(Serialize, Deserialize, Eq, PartialEq, Copy, Clone)]
#[derive(Serialize, Deserialize, Eq, PartialEq, Copy, Clone, Debug)]
#[serde(rename_all = "kebab-case")]
pub enum ChargeStatus {
// Open charges are for the next billing interval
@@ -232,3 +236,23 @@ impl ChargeStatus {
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaymentPlatform {
Stripe,
}
impl PaymentPlatform {
pub fn from_string(string: &str) -> PaymentPlatform {
match string {
"stripe" => PaymentPlatform::Stripe,
_ => PaymentPlatform::Stripe,
}
}
pub fn as_str(&self) -> &'static str {
match self {
PaymentPlatform::Stripe => "stripe",
}
}
}

View File

@@ -158,7 +158,7 @@ pub mod base62_impl {
{
struct Base62Visitor;
impl<'de> Visitor<'de> for Base62Visitor {
impl Visitor<'_> for Base62Visitor {
type Value = Base62Id;
fn expecting(

View File

@@ -69,11 +69,11 @@ pub enum PackFileHash {
impl From<String> for PackFileHash {
fn from(s: String) -> Self {
return match s.as_str() {
match s.as_str() {
"sha1" => PackFileHash::Sha1,
"sha512" => PackFileHash::Sha512,
_ => PackFileHash::Unknown(s),
};
}
}
}

View File

@@ -818,11 +818,13 @@ pub async fn process_payout(
// Modrinth's share of ad revenue
let modrinth_cut = Decimal::from(1) / Decimal::from(4);
// Clean.io fee (ad antimalware). Per 1000 impressions.
// Clean.io fee (ad antimalware). Per 1000 impressions. 0.008 CPM
let clean_io_fee = Decimal::from(8) / Decimal::from(1000);
// Google Ad Manager fee. Per 1000 impressions. 0.015400 CPM
let gam_fee = Decimal::from(154) / Decimal::from(10000);
let net_revenue = aditude_amount
- (clean_io_fee * Decimal::from(aditude_impressions)
- ((clean_io_fee + gam_fee) * Decimal::from(aditude_impressions)
/ Decimal::from(1000));
let payout = net_revenue * (Decimal::from(1) - modrinth_cut);

View File

@@ -6,9 +6,9 @@ use crate::database::models::{
};
use crate::database::redis::RedisPool;
use crate::models::billing::{
Charge, ChargeStatus, ChargeType, Price, PriceDuration, Product,
ProductMetadata, ProductPrice, SubscriptionMetadata, SubscriptionStatus,
UserSubscription,
Charge, ChargeStatus, ChargeType, PaymentPlatform, Price, PriceDuration,
Product, ProductMetadata, ProductPrice, SubscriptionMetadata,
SubscriptionStatus, UserSubscription,
};
use crate::models::ids::base62_impl::{parse_base62, to_base62};
use crate::models::pats::Scopes;
@@ -26,11 +26,11 @@ use sqlx::{PgPool, Postgres, Transaction};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use stripe::{
CreateCustomer, CreatePaymentIntent, CreateSetupIntent,
CreateCustomer, CreatePaymentIntent, CreateRefund, CreateSetupIntent,
CreateSetupIntentAutomaticPaymentMethods,
CreateSetupIntentAutomaticPaymentMethodsAllowRedirects, Currency,
CustomerId, CustomerInvoiceSettings, CustomerPaymentMethodRetrieval,
EventObject, EventType, PaymentIntentOffSession,
EventObject, EventType, PaymentIntentId, PaymentIntentOffSession,
PaymentIntentSetupFutureUsage, PaymentMethodId, SetupIntent,
UpdateCustomer, Webhook,
};
@@ -47,8 +47,10 @@ pub fn config(cfg: &mut web::ServiceConfig) {
.service(edit_payment_method)
.service(remove_payment_method)
.service(charges)
.service(active_servers)
.service(initiate_payment)
.service(stripe_webhook),
.service(stripe_webhook)
.service(refund_charge),
);
}
@@ -111,6 +113,169 @@ pub async fn subscriptions(
Ok(HttpResponse::Ok().json(subscriptions))
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ChargeRefundAmount {
Full,
Partial { amount: u64 },
}
#[derive(Deserialize)]
pub struct ChargeRefund {
#[serde(flatten)]
pub amount: ChargeRefundAmount,
pub unprovision: Option<bool>,
}
#[post("charge/{id}/refund")]
pub async fn refund_charge(
req: HttpRequest,
pool: web::Data<PgPool>,
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
info: web::Path<(crate::models::ids::ChargeId,)>,
body: web::Json<ChargeRefund>,
stripe_client: web::Data<stripe::Client>,
) -> Result<HttpResponse, ApiError> {
let user = get_user_from_headers(
&req,
&**pool,
&redis,
&session_queue,
Some(&[Scopes::SESSION_ACCESS]),
)
.await?
.1;
let (id,) = info.into_inner();
if !user.role.is_admin() {
return Err(ApiError::CustomAuthentication(
"You do not have permission to refund a subscription!".to_string(),
));
}
if let Some(charge) = ChargeItem::get(id.into(), &**pool).await? {
let refunds = ChargeItem::get_children(id.into(), &**pool).await?;
let refunds = -refunds
.into_iter()
.filter_map(|x| match x.status {
ChargeStatus::Open
| ChargeStatus::Processing
| ChargeStatus::Succeeded => Some(x.amount),
ChargeStatus::Failed | ChargeStatus::Cancelled => None,
})
.sum::<i64>();
let refundable = charge.amount - refunds;
let refund_amount = match body.0.amount {
ChargeRefundAmount::Full => refundable,
ChargeRefundAmount::Partial { amount } => amount as i64,
};
if charge.status != ChargeStatus::Succeeded {
return Err(ApiError::InvalidInput(
"This charge cannot be refunded!".to_string(),
));
}
if (refundable - refund_amount) < 0 || refund_amount == 0 {
return Err(ApiError::InvalidInput(
"You cannot refund more than the amount of the charge!"
.to_string(),
));
}
let (id, net) = match charge.payment_platform {
PaymentPlatform::Stripe => {
if let Some(payment_platform_id) = charge
.payment_platform_id
.and_then(|x| stripe::PaymentIntentId::from_str(&x).ok())
{
let mut metadata = HashMap::new();
metadata.insert(
"modrinth_user_id".to_string(),
to_base62(user.id.0),
);
metadata.insert(
"modrinth_charge_id".to_string(),
to_base62(charge.id.0 as u64),
);
let refund = stripe::Refund::create(
&stripe_client,
CreateRefund {
amount: Some(refund_amount),
metadata: Some(metadata),
payment_intent: Some(payment_platform_id),
expand: &["balance_transaction"],
..Default::default()
},
)
.await?;
(
refund.id.to_string(),
refund
.balance_transaction
.and_then(|x| x.into_object())
.map(|x| x.net),
)
} else {
return Err(ApiError::InvalidInput(
"Charge does not have attached payment id!".to_string(),
));
}
}
};
let mut transaction = pool.begin().await?;
let charge_id = generate_charge_id(&mut transaction).await?;
ChargeItem {
id: charge_id,
user_id: charge.user_id,
price_id: charge.price_id,
amount: -refund_amount,
currency_code: charge.currency_code,
status: ChargeStatus::Succeeded,
due: Utc::now(),
last_attempt: None,
type_: ChargeType::Refund,
subscription_id: charge.subscription_id,
subscription_interval: charge.subscription_interval,
payment_platform: charge.payment_platform,
payment_platform_id: Some(id),
parent_charge_id: Some(charge.id),
net,
}
.upsert(&mut transaction)
.await?;
if body.0.unprovision.unwrap_or(false) {
if let Some(subscription_id) = charge.subscription_id {
let open_charge =
ChargeItem::get_open_subscription(subscription_id, &**pool)
.await?;
if let Some(mut open_charge) = open_charge {
open_charge.status = ChargeStatus::Cancelled;
open_charge.due = Utc::now();
open_charge.upsert(&mut transaction).await?;
}
}
}
transaction.commit().await?;
}
Ok(HttpResponse::NoContent().body(""))
}
#[derive(Deserialize)]
pub struct SubscriptionEdit {
pub interval: Option<PriceDuration>,
@@ -264,78 +429,94 @@ pub async fn edit_subscription(
)
})?;
// TODO: Add downgrading plans
if proration <= 0 {
return Err(ApiError::InvalidInput(
"You may not downgrade plans!".to_string(),
));
}
// Plan downgrade, update future charge
if current_amount > amount {
open_charge.price_id = product_price.id;
open_charge.amount = amount as i64;
let charge_id = generate_charge_id(&mut transaction).await?;
let charge = ChargeItem {
id: charge_id,
user_id: user.id.into(),
price_id: product_price.id,
amount: proration as i64,
currency_code: current_price.currency_code.clone(),
status: ChargeStatus::Processing,
due: Utc::now(),
last_attempt: None,
type_: ChargeType::Proration,
subscription_id: Some(subscription.id),
subscription_interval: Some(duration),
};
None
} else {
// For small transactions (under 30 cents), we make a loss on the proration due to fees
if proration < 30 {
return Err(ApiError::InvalidInput(
"Proration is too small!".to_string(),
));
}
let customer_id = get_or_create_customer(
user.id,
user.stripe_customer_id.as_deref(),
user.email.as_deref(),
&stripe_client,
&pool,
&redis,
)
.await?;
let charge_id = generate_charge_id(&mut transaction).await?;
let mut charge = ChargeItem {
id: charge_id,
user_id: user.id.into(),
price_id: product_price.id,
amount: proration as i64,
currency_code: current_price.currency_code.clone(),
status: ChargeStatus::Processing,
due: Utc::now(),
last_attempt: None,
type_: ChargeType::Proration,
subscription_id: Some(subscription.id),
subscription_interval: Some(duration),
payment_platform: PaymentPlatform::Stripe,
payment_platform_id: None,
parent_charge_id: None,
net: None,
};
let currency =
Currency::from_str(&current_price.currency_code.to_lowercase())
.map_err(|_| {
ApiError::InvalidInput(
"Invalid currency code".to_string(),
)
})?;
let customer_id = get_or_create_customer(
user.id,
user.stripe_customer_id.as_deref(),
user.email.as_deref(),
&stripe_client,
&pool,
&redis,
)
.await?;
let mut intent =
CreatePaymentIntent::new(proration as i64, currency);
let currency = Currency::from_str(
&current_price.currency_code.to_lowercase(),
)
.map_err(|_| {
ApiError::InvalidInput("Invalid currency code".to_string())
})?;
let mut metadata = HashMap::new();
metadata
.insert("modrinth_user_id".to_string(), to_base62(user.id.0));
let mut intent =
CreatePaymentIntent::new(proration as i64, currency);
intent.customer = Some(customer_id);
intent.metadata = Some(metadata);
intent.receipt_email = user.email.as_deref();
intent.setup_future_usage =
Some(PaymentIntentSetupFutureUsage::OffSession);
let mut metadata = HashMap::new();
metadata.insert(
"modrinth_user_id".to_string(),
to_base62(user.id.0),
);
if let Some(payment_method) = &edit_subscription.payment_method {
let payment_method_id =
if let Ok(id) = PaymentMethodId::from_str(payment_method) {
intent.customer = Some(customer_id);
intent.metadata = Some(metadata);
intent.receipt_email = user.email.as_deref();
intent.setup_future_usage =
Some(PaymentIntentSetupFutureUsage::OffSession);
if let Some(payment_method) = &edit_subscription.payment_method
{
let payment_method_id = if let Ok(id) =
PaymentMethodId::from_str(payment_method)
{
id
} else {
return Err(ApiError::InvalidInput(
"Invalid payment method id".to_string(),
));
};
intent.payment_method = Some(payment_method_id);
intent.payment_method = Some(payment_method_id);
}
let intent =
stripe::PaymentIntent::create(&stripe_client, intent)
.await?;
charge.payment_platform_id = Some(intent.id.to_string());
charge.upsert(&mut transaction).await?;
Some((proration, 0, intent))
}
charge.upsert(&mut transaction).await?;
Some((
proration,
0,
stripe::PaymentIntent::create(&stripe_client, intent).await?,
))
} else {
None
};
@@ -423,7 +604,7 @@ pub async fn charges(
id: x.id.into(),
user_id: x.user_id.into(),
price_id: x.price_id.into(),
amount: x.amount,
amount: x.amount as u64,
currency_code: x.currency_code,
status: x.status,
due: x.due,
@@ -431,6 +612,7 @@ pub async fn charges(
type_: x.type_,
subscription_id: x.subscription_id.map(|x| x.into()),
subscription_interval: x.subscription_interval,
platform: x.payment_platform,
})
.collect::<Vec<_>>(),
))
@@ -685,6 +867,49 @@ pub async fn payment_methods(
}
}
#[derive(Deserialize)]
pub struct ActiveServersQuery {
pub subscription_status: Option<SubscriptionStatus>,
}
#[get("active_servers")]
pub async fn active_servers(
req: HttpRequest,
pool: web::Data<PgPool>,
query: web::Query<ActiveServersQuery>,
) -> Result<HttpResponse, ApiError> {
let master_key = dotenvy::var("PYRO_API_KEY")?;
if !req
.head()
.headers()
.get("X-Master-Key")
.map_or(false, |it| it.as_bytes() == master_key.as_bytes())
{
return Err(ApiError::CustomAuthentication(
"Invalid master key".to_string(),
));
}
let servers =
user_subscription_item::UserSubscriptionItem::get_all_servers(
query.subscription_status,
&**pool,
)
.await?;
let server_ids = servers
.into_iter()
.filter_map(|x| {
x.metadata.map(|x| match x {
SubscriptionMetadata::Pyro { id } => id,
})
})
.collect::<Vec<_>>();
Ok(HttpResponse::Ok().json(server_ids))
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PaymentRequestType {
@@ -1130,6 +1355,7 @@ pub async fn stripe_webhook(
}
async fn get_payment_intent_metadata(
payment_intent_id: PaymentIntentId,
metadata: HashMap<String, String>,
pool: &PgPool,
redis: &RedisPool,
@@ -1203,6 +1429,8 @@ pub async fn stripe_webhook(
charge.status = charge_status;
charge.last_attempt = Some(Utc::now());
charge.payment_platform_id =
Some(payment_intent_id.to_string());
charge.upsert(transaction).await?;
if let Some(subscription_id) = charge.subscription_id {
@@ -1229,6 +1457,11 @@ pub async fn stripe_webhook(
ChargeType::Proration => {
subscription.price_id = charge.price_id;
}
ChargeType::Refund => {
return Err(ApiError::InvalidInput(
"Invalid charge type: Refund".to_string(),
));
}
}
subscription.upsert(transaction).await?;
@@ -1332,6 +1565,12 @@ pub async fn stripe_webhook(
subscription_interval: subscription
.as_ref()
.map(|x| x.interval),
payment_platform: PaymentPlatform::Stripe,
payment_platform_id: Some(
payment_intent_id.to_string(),
),
parent_charge_id: None,
net: None,
};
if charge_status != ChargeStatus::Failed {
@@ -1364,6 +1603,7 @@ pub async fn stripe_webhook(
let mut transaction = pool.begin().await?;
let mut metadata = get_payment_intent_metadata(
payment_intent.id,
payment_intent.metadata,
&pool,
&redis,
@@ -1372,6 +1612,27 @@ pub async fn stripe_webhook(
)
.await?;
if let Some(latest_charge) = payment_intent.latest_charge {
let charge = stripe::Charge::retrieve(
&stripe_client,
&latest_charge.id(),
&["balance_transaction"],
)
.await?;
if let Some(balance_transaction) = charge
.balance_transaction
.and_then(|x| x.into_object())
{
metadata.charge_item.net =
Some(balance_transaction.net);
metadata
.charge_item
.upsert(&mut transaction)
.await?;
}
}
// Provision subscription
match metadata.product_item.metadata {
ProductMetadata::Midas => {
@@ -1415,7 +1676,20 @@ pub async fn stripe_webhook(
.await?
.error_for_status()?;
// TODO: Send plan upgrade request for proration
client.post(format!(
"https://archon.pyro.host/modrinth/v0/servers/{}/reallocate",
id
))
.header("X-Master-Key", dotenvy::var("PYRO_API_KEY")?)
.json(&serde_json::json!({
"memory_mb": ram,
"cpu": cpu,
"swap_mb": swap,
"storage_mb": storage,
}))
.send()
.await?
.error_for_status()?;
} else {
let (server_name, source) = if let Some(
PaymentRequestMetadata::Pyro {
@@ -1471,6 +1745,10 @@ pub async fn stripe_webhook(
"storage_mb": storage,
},
"source": source,
"payment_interval": metadata.charge_item.subscription_interval.map(|x| match x {
PriceDuration::Monthly => 1,
PriceDuration::Yearly => 3,
})
}))
.send()
.await?
@@ -1546,6 +1824,10 @@ pub async fn stripe_webhook(
subscription_interval: Some(
subscription.interval,
),
payment_platform: PaymentPlatform::Stripe,
payment_platform_id: None,
parent_charge_id: None,
net: None,
}
.upsert(&mut transaction)
.await?;
@@ -1569,6 +1851,7 @@ pub async fn stripe_webhook(
{
let mut transaction = pool.begin().await?;
get_payment_intent_metadata(
payment_intent.id,
payment_intent.metadata,
&pool,
&redis,
@@ -1586,6 +1869,7 @@ pub async fn stripe_webhook(
let mut transaction = pool.begin().await?;
let metadata = get_payment_intent_metadata(
payment_intent.id,
payment_intent.metadata,
&pool,
&redis,
@@ -1596,7 +1880,7 @@ pub async fn stripe_webhook(
if let Some(email) = metadata.user_item.email {
let money = rusty_money::Money::from_minor(
metadata.charge_item.amount,
metadata.charge_item.amount as i64,
rusty_money::iso::find(
&metadata.charge_item.currency_code,
)

View File

@@ -150,7 +150,12 @@ pub async fn ws_init(
{
let (status, _) = pair.value_mut();
if status.profile_name.as_ref().map(|x| x.len() > 64).unwrap_or(false) {
if status
.profile_name
.as_ref()
.map(|x| x.len() > 64)
.unwrap_or(false)
{
continue;
}

View File

@@ -21,10 +21,8 @@ pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(version_file);
}
// TODO: These were modified in v3 and should be tested
#[derive(Default, Debug, Clone, YaSerialize)]
#[yaserde(root = "metadata", rename = "metadata")]
#[yaserde(rename = "metadata")]
pub struct Metadata {
#[yaserde(rename = "groupId")]
group_id: String,
@@ -51,11 +49,11 @@ pub struct Versions {
}
#[derive(Default, Debug, Clone, YaSerialize)]
#[yaserde(rename = "project", namespace = "http://maven.apache.org/POM/4.0.0")]
#[yaserde(rename = "project", namespaces = { "" = "http://maven.apache.org/POM/4.0.0" })]
pub struct MavenPom {
#[yaserde(rename = "xsi:schemaLocation", attribute)]
#[yaserde(rename = "xsi:schemaLocation", attribute = true)]
schema_location: String,
#[yaserde(rename = "xmlns:xsi", attribute)]
#[yaserde(rename = "xmlns:xsi", attribute = true)]
xsi: String,
#[yaserde(rename = "modelVersion")]
model_version: String,

View File

@@ -861,7 +861,6 @@ pub struct GalleryEditQuery {
pub async fn edit_gallery_item(
req: HttpRequest,
web::Query(item): web::Query<GalleryEditQuery>,
info: web::Path<(String,)>,
pool: web::Data<PgPool>,
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
@@ -876,7 +875,6 @@ pub async fn edit_gallery_item(
description: item.description,
ordering: item.ordering,
}),
info,
pool,
redis,
session_queue,
@@ -894,7 +892,6 @@ pub struct GalleryDeleteQuery {
pub async fn delete_gallery_item(
req: HttpRequest,
web::Query(item): web::Query<GalleryDeleteQuery>,
info: web::Path<(String,)>,
pool: web::Data<PgPool>,
redis: web::Data<RedisPool>,
file_host: web::Data<Arc<dyn FileHost + Send + Sync>>,
@@ -904,7 +901,6 @@ pub async fn delete_gallery_item(
v3::projects::delete_gallery_item(
req,
web::Query(v3::projects::GalleryDeleteQuery { url: item.url }),
info,
pool,
redis,
file_host,

View File

@@ -1788,7 +1788,6 @@ pub struct GalleryEditQuery {
pub async fn edit_gallery_item(
req: HttpRequest,
web::Query(item): web::Query<GalleryEditQuery>,
info: web::Path<(String,)>,
pool: web::Data<PgPool>,
redis: web::Data<RedisPool>,
session_queue: web::Data<AuthQueue>,
@@ -1802,19 +1801,38 @@ pub async fn edit_gallery_item(
)
.await?
.1;
let string = info.into_inner().0;
item.validate().map_err(|err| {
ApiError::Validation(validation_errors_to_string(err, None))
})?;
let project_item = db_models::Project::get(&string, &**pool, &redis)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(
"The specified project does not exist!".to_string(),
)
})?;
let result = sqlx::query!(
"
SELECT id, mod_id FROM mods_gallery
WHERE image_url = $1
",
item.url
)
.fetch_optional(&**pool)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(format!(
"Gallery item at URL {} is not part of the project's gallery.",
item.url
))
})?;
let project_item = db_models::Project::get_id(
database::models::ProjectId(result.mod_id),
&**pool,
&redis,
)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(
"The specified project does not exist!".to_string(),
)
})?;
if !user.role.is_mod() {
let (team_member, organization_team_member) =
@@ -1845,24 +1863,6 @@ pub async fn edit_gallery_item(
));
}
}
let mut transaction = pool.begin().await?;
let id = sqlx::query!(
"
SELECT id FROM mods_gallery
WHERE image_url = $1
",
item.url
)
.fetch_optional(&mut *transaction)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(format!(
"Gallery item at URL {} is not part of the project's gallery.",
item.url
))
})?
.id;
let mut transaction = pool.begin().await?;
@@ -1887,7 +1887,7 @@ pub async fn edit_gallery_item(
SET featured = $2
WHERE id = $1
",
id,
result.id,
featured
)
.execute(&mut *transaction)
@@ -1900,7 +1900,7 @@ pub async fn edit_gallery_item(
SET name = $2
WHERE id = $1
",
id,
result.id,
name
)
.execute(&mut *transaction)
@@ -1913,7 +1913,7 @@ pub async fn edit_gallery_item(
SET description = $2
WHERE id = $1
",
id,
result.id,
description
)
.execute(&mut *transaction)
@@ -1926,7 +1926,7 @@ pub async fn edit_gallery_item(
SET ordering = $2
WHERE id = $1
",
id,
result.id,
ordering
)
.execute(&mut *transaction)
@@ -1954,7 +1954,6 @@ pub struct GalleryDeleteQuery {
pub async fn delete_gallery_item(
req: HttpRequest,
web::Query(item): web::Query<GalleryDeleteQuery>,
info: web::Path<(String,)>,
pool: web::Data<PgPool>,
redis: web::Data<RedisPool>,
file_host: web::Data<Arc<dyn FileHost + Send + Sync>>,
@@ -1969,15 +1968,34 @@ pub async fn delete_gallery_item(
)
.await?
.1;
let string = info.into_inner().0;
let project_item = db_models::Project::get(&string, &**pool, &redis)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(
"The specified project does not exist!".to_string(),
)
})?;
let item = sqlx::query!(
"
SELECT id, image_url, raw_image_url, mod_id FROM mods_gallery
WHERE image_url = $1
",
item.url
)
.fetch_optional(&**pool)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(format!(
"Gallery item at URL {} is not part of the project's gallery.",
item.url
))
})?;
let project_item = db_models::Project::get_id(
database::models::ProjectId(item.mod_id),
&**pool,
&redis,
)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(
"The specified project does not exist!".to_string(),
)
})?;
if !user.role.is_mod() {
let (team_member, organization_team_member) =
@@ -2009,23 +2027,6 @@ pub async fn delete_gallery_item(
));
}
}
let mut transaction = pool.begin().await?;
let item = sqlx::query!(
"
SELECT id, image_url, raw_image_url FROM mods_gallery
WHERE image_url = $1
",
item.url
)
.fetch_optional(&mut *transaction)
.await?
.ok_or_else(|| {
ApiError::InvalidInput(format!(
"Gallery item at URL {} is not part of the project's gallery.",
item.url
))
})?;
delete_old_images(
Some(item.image_url),