You've already forked AstralRinth
forked from didirus/AstralRinth
Payouts finish (#470)
* Almost done * More work on midas * Finish payouts backend * Update Cargo.lock * Run fmt + prepare
This commit is contained in:
@@ -1,11 +1,16 @@
|
||||
use crate::models::ids::ProjectId;
|
||||
use crate::routes::ApiError;
|
||||
use crate::util::auth::check_is_admin_from_headers;
|
||||
use crate::util::guards::admin_key_guard;
|
||||
use crate::util::payout_calc::get_claimable_time;
|
||||
use crate::DownloadQueue;
|
||||
use actix_web::{patch, web, HttpResponse};
|
||||
use actix_web::{get, patch, post, web, HttpRequest, HttpResponse};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rust_decimal::Decimal;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -80,5 +85,294 @@ pub async fn count_download(
|
||||
.await
|
||||
.ok();
|
||||
|
||||
Ok(HttpResponse::Ok().body(""))
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PayoutData {
|
||||
amount: Decimal,
|
||||
date: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[post("/_process_payout", guard = "admin_key_guard")]
|
||||
pub async fn process_payout(
|
||||
pool: web::Data<PgPool>,
|
||||
data: web::Json<PayoutData>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let start = data.date.date().and_hms(0, 0, 0);
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let mut transaction = pool.begin().await?;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PayoutMultipliers {
|
||||
sum: u64,
|
||||
values: HashMap<i64, u64>,
|
||||
}
|
||||
|
||||
let multipliers: PayoutMultipliers = client
|
||||
.get(format!(
|
||||
"{}multipliers?start_date=\"{}\"",
|
||||
dotenvy::var("ARIADNE_URL")?,
|
||||
start.to_rfc3339(),
|
||||
))
|
||||
.header("Modrinth-Admin", dotenvy::var("ARIADNE_ADMIN_KEY")?)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Analytics(
|
||||
"Error while fetching payout multipliers!".to_string(),
|
||||
)
|
||||
})?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Analytics(
|
||||
"Error while deserializing payout multipliers!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM payouts_values
|
||||
WHERE created = $1
|
||||
",
|
||||
start
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
struct Project {
|
||||
project_type: String,
|
||||
// user_id, payouts_split
|
||||
team_members: Vec<(i64, Decimal)>,
|
||||
// user_id, payouts_split
|
||||
split_team_members: Vec<(i64, Decimal)>,
|
||||
}
|
||||
|
||||
let mut projects_map: HashMap<i64, Project> = HashMap::new();
|
||||
|
||||
use futures::TryStreamExt;
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT m.id id, tm.user_id user_id, tm.payouts_split payouts_split, pt.name project_type
|
||||
FROM mods m
|
||||
INNER JOIN team_members tm on m.team_id = tm.team_id
|
||||
INNER JOIN project_types pt ON pt.id = m.project_type
|
||||
WHERE m.id = ANY($1)
|
||||
",
|
||||
&multipliers.values.keys().map(|x| *x).collect::<Vec<i64>>()
|
||||
)
|
||||
.fetch_many(&mut *transaction)
|
||||
.try_for_each(|e| {
|
||||
if let Some(row) = e.right() {
|
||||
if let Some(project) = projects_map.get_mut(&row.id) {
|
||||
project.team_members.push((row.user_id, row.payouts_split));
|
||||
} else {
|
||||
projects_map.insert(row.id, Project {
|
||||
project_type: row.project_type,
|
||||
team_members: vec![(row.user_id, row.payouts_split)],
|
||||
split_team_members: Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
futures::future::ready(Ok(()))
|
||||
})
|
||||
.await?;
|
||||
|
||||
// Specific Payout Conditions (ex: modpack payout split)
|
||||
let mut projects_split_dependencies = Vec::new();
|
||||
|
||||
for (id, project) in &projects_map {
|
||||
if project.project_type == "modpack" {
|
||||
projects_split_dependencies.push(*id);
|
||||
}
|
||||
}
|
||||
|
||||
if !projects_split_dependencies.is_empty() {
|
||||
// (dependent_id, (dependency_id, times_depended))
|
||||
let mut project_dependencies: HashMap<i64, Vec<(i64, i64)>> =
|
||||
HashMap::new();
|
||||
// dependency_ids to fetch team members from
|
||||
let mut fetch_team_members: Vec<i64> = Vec::new();
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT mv.mod_id, m.id, COUNT(m.id) times_depended FROM versions mv
|
||||
INNER JOIN dependencies d ON d.dependent_id = mv.id
|
||||
INNER JOIN versions v ON d.dependency_id = v.id
|
||||
INNER JOIN mods m ON v.mod_id = m.id OR d.mod_dependency_id = m.id
|
||||
WHERE mv.mod_id = ANY($1)
|
||||
group by mv.mod_id, m.id;
|
||||
",
|
||||
&projects_split_dependencies
|
||||
)
|
||||
.fetch_many(&mut *transaction)
|
||||
.try_for_each(|e| {
|
||||
if let Some(row) = e.right() {
|
||||
fetch_team_members.push(row.id);
|
||||
|
||||
if let Some(project) = project_dependencies.get_mut(&row.mod_id)
|
||||
{
|
||||
project.push((row.id, row.times_depended.unwrap_or(0)));
|
||||
} else {
|
||||
project_dependencies.insert(
|
||||
row.mod_id,
|
||||
vec![(row.id, row.times_depended.unwrap_or(0))],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
futures::future::ready(Ok(()))
|
||||
})
|
||||
.await?;
|
||||
|
||||
// (project_id, (user_id, payouts_split))
|
||||
let mut team_members: HashMap<i64, Vec<(i64, Decimal)>> =
|
||||
HashMap::new();
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
SELECT m.id id, tm.user_id user_id, tm.payouts_split payouts_split
|
||||
FROM mods m
|
||||
INNER JOIN team_members tm on m.team_id = tm.team_id
|
||||
WHERE m.id = ANY($1)
|
||||
",
|
||||
&*fetch_team_members
|
||||
)
|
||||
.fetch_many(&mut *transaction)
|
||||
.try_for_each(|e| {
|
||||
if let Some(row) = e.right() {
|
||||
if let Some(project) = team_members.get_mut(&row.id) {
|
||||
project.push((row.user_id, row.payouts_split));
|
||||
} else {
|
||||
team_members
|
||||
.insert(row.id, vec![(row.user_id, row.payouts_split)]);
|
||||
}
|
||||
}
|
||||
|
||||
futures::future::ready(Ok(()))
|
||||
})
|
||||
.await?;
|
||||
|
||||
for (project, dependencies) in project_dependencies {
|
||||
let dep_sum: i64 = dependencies.iter().map(|x| x.1).sum();
|
||||
|
||||
let project = projects_map.get_mut(&project);
|
||||
|
||||
if let Some(project) = project {
|
||||
for dependency in dependencies {
|
||||
let project_multiplier: Decimal =
|
||||
Decimal::from(dependency.1) / Decimal::from(dep_sum);
|
||||
|
||||
if let Some(members) = team_members.get(&dependency.0) {
|
||||
let members_sum: Decimal =
|
||||
members.iter().map(|x| x.1).sum();
|
||||
|
||||
for member in members {
|
||||
let member_multiplier: Decimal =
|
||||
member.1 / members_sum;
|
||||
project.split_team_members.push((
|
||||
member.0,
|
||||
member_multiplier * project_multiplier,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (id, project) in projects_map {
|
||||
if let Some(value) = &multipliers.values.get(&id) {
|
||||
let project_multiplier: Decimal =
|
||||
Decimal::from(**value) / Decimal::from(multipliers.sum);
|
||||
|
||||
let default_split_given = Decimal::from(1);
|
||||
let split_given = Decimal::from(1) / Decimal::from(5);
|
||||
let split_retention = Decimal::from(4) / Decimal::from(5);
|
||||
|
||||
let sum_splits: Decimal =
|
||||
project.team_members.iter().map(|x| x.1).sum();
|
||||
let sum_tm_splits: Decimal =
|
||||
project.split_team_members.iter().map(|x| x.1).sum();
|
||||
|
||||
for (user_id, split) in project.team_members {
|
||||
let payout: Decimal = data.amount
|
||||
* project_multiplier
|
||||
* (split / sum_splits)
|
||||
* (if !project.split_team_members.is_empty() {
|
||||
&split_given
|
||||
} else {
|
||||
&default_split_given
|
||||
});
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO payouts_values (user_id, mod_id, amount, created)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
",
|
||||
user_id,
|
||||
id,
|
||||
payout,
|
||||
start
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
|
||||
for (user_id, split) in project.split_team_members {
|
||||
let payout: Decimal = data.amount
|
||||
* project_multiplier
|
||||
* (split / sum_tm_splits)
|
||||
* split_retention;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO payouts_values (user_id, amount, created)
|
||||
VALUES ($1, $2, $3)
|
||||
",
|
||||
user_id,
|
||||
payout,
|
||||
start
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
}
|
||||
|
||||
#[get("/_get-payout-data")]
|
||||
pub async fn get_payout_data(
|
||||
req: HttpRequest,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
check_is_admin_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
let payouts = sqlx::query!(
|
||||
"
|
||||
SELECT u.paypal_email, SUM(pv.amount) amount
|
||||
FROM payouts_values pv
|
||||
INNER JOIN users u ON pv.user_id = u.id AND u.paypal_email IS NOT NULL
|
||||
WHERE pv.created <= $1 AND pv.claimed = FALSE
|
||||
GROUP BY u.paypal_email
|
||||
",
|
||||
get_claimable_time(Utc::now(), false)
|
||||
)
|
||||
.fetch_many(&**pool)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right().map(|r| (r.paypal_email.unwrap_or_default(), r.amount.unwrap_or_default())))
|
||||
})
|
||||
.try_collect::<HashMap<String, Decimal>>()
|
||||
.await?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(payouts))
|
||||
}
|
||||
|
||||
@@ -273,6 +273,7 @@ pub async fn auth_callback(
|
||||
created: Utc::now(),
|
||||
role: Role::Developer.to_string(),
|
||||
badges: Badges::default(),
|
||||
paypal_email: None,
|
||||
}
|
||||
.insert(&mut transaction)
|
||||
.await?;
|
||||
|
||||
336
src/routes/midas.rs
Normal file
336
src/routes/midas.rs
Normal file
@@ -0,0 +1,336 @@
|
||||
use crate::models::users::UserId;
|
||||
use crate::routes::ApiError;
|
||||
use crate::util::auth::get_user_from_headers;
|
||||
use actix_web::{post, web, HttpRequest, HttpResponse};
|
||||
use chrono::{DateTime, Duration, NaiveDateTime, Utc};
|
||||
use hmac::{Hmac, Mac, NewMac};
|
||||
use itertools::Itertools;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CheckoutData {
|
||||
pub price_id: String,
|
||||
}
|
||||
|
||||
#[post("/_stripe-init-checkout")]
|
||||
pub async fn init_checkout(
|
||||
req: HttpRequest,
|
||||
pool: web::Data<PgPool>,
|
||||
data: web::Json<CheckoutData>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Session {
|
||||
url: Option<String>,
|
||||
}
|
||||
|
||||
let session = client
|
||||
.post("https://api.stripe.com/v1/checkout/sessions")
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Bearer {}", dotenvy::var("STRIPE_TOKEN")?),
|
||||
)
|
||||
.form(&[
|
||||
("mode", "subscription"),
|
||||
("line_items[0][price]", &*data.price_id),
|
||||
("line_items[0][quantity]", "1"),
|
||||
("success_url", "https://modrinth.com/welcome-to-midas"),
|
||||
("cancel_url", "https://modrinth.com/midas"),
|
||||
("metadata[user_id]", &user.id.to_string()),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Payments(
|
||||
"Error while creating checkout session!".to_string(),
|
||||
)
|
||||
})?
|
||||
.json::<Session>()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Payments(
|
||||
"Error while deserializing checkout response!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(json!(
|
||||
{
|
||||
"url": session.url
|
||||
}
|
||||
)))
|
||||
}
|
||||
|
||||
#[post("/_stripe-init-portal")]
|
||||
pub async fn init_customer_portal(
|
||||
req: HttpRequest,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let customer_id = sqlx::query!(
|
||||
"
|
||||
SELECT u.stripe_customer_id
|
||||
FROM users u
|
||||
WHERE u.id = $1
|
||||
",
|
||||
user.id.0 as i64,
|
||||
)
|
||||
.fetch_optional(&**pool)
|
||||
.await?
|
||||
.and_then(|x| x.stripe_customer_id)
|
||||
.ok_or_else(|| {
|
||||
ApiError::InvalidInput(
|
||||
"User is not linked to stripe account!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Session {
|
||||
url: Option<String>,
|
||||
}
|
||||
|
||||
let session = client
|
||||
.post("https://api.stripe.com/v1/billing_portal/sessions")
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Bearer {}", dotenvy::var("STRIPE_TOKEN")?),
|
||||
)
|
||||
.form(&[
|
||||
("customer", &*customer_id),
|
||||
("return_url", "https://modrinth.com/settings/billing"),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Payments(
|
||||
"Error while creating billing session!".to_string(),
|
||||
)
|
||||
})?
|
||||
.json::<Session>()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Payments(
|
||||
"Error while deserializing billing response!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(json!(
|
||||
{
|
||||
"url": session.url
|
||||
}
|
||||
)))
|
||||
}
|
||||
|
||||
#[post("/_stripe-webook")]
|
||||
pub async fn handle_stripe_webhook(
|
||||
body: String,
|
||||
req: HttpRequest,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
if let Some(signature_raw) = req
|
||||
.headers()
|
||||
.get("Stripe-Signature")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
{
|
||||
let mut timestamp = None;
|
||||
let mut signature = None;
|
||||
for val in signature_raw.split(',') {
|
||||
let key_val = val.split('=').collect_vec();
|
||||
|
||||
if key_val.len() == 2 {
|
||||
if key_val[0] == "v1" {
|
||||
signature = hex::decode(key_val[1]).ok()
|
||||
} else if key_val[0] == "t" {
|
||||
timestamp = key_val[1].parse::<i64>().ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(timestamp) = timestamp {
|
||||
if let Some(signature) = signature {
|
||||
type HmacSha256 = Hmac<sha2::Sha256>;
|
||||
|
||||
let mut key = HmacSha256::new_from_slice(dotenvy::var("STRIPE_WEBHOOK_SECRET")?.as_bytes()).map_err(|_| {
|
||||
ApiError::Crypto(
|
||||
"Unable to initialize HMAC instance due to invalid key length!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
key.update(format!("{}.{}", timestamp, body).as_bytes());
|
||||
|
||||
key.verify(&signature).map_err(|_| {
|
||||
ApiError::Crypto(
|
||||
"Unable to verify webhook signature!".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
if timestamp < (Utc::now() - Duration::minutes(5)).timestamp()
|
||||
|| timestamp
|
||||
> (Utc::now() + Duration::minutes(5)).timestamp()
|
||||
{
|
||||
return Err(ApiError::Crypto(
|
||||
"Webhook signature expired!".to_string(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Err(ApiError::Crypto("Missing signature!".to_string()));
|
||||
}
|
||||
} else {
|
||||
return Err(ApiError::Crypto("Missing timestamp!".to_string()));
|
||||
}
|
||||
} else {
|
||||
return Err(ApiError::Crypto("Missing signature header!".to_string()));
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct StripeWebhookBody {
|
||||
#[serde(rename = "type")]
|
||||
type_: String,
|
||||
data: StripeWebhookObject,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct StripeWebhookObject {
|
||||
object: Value,
|
||||
}
|
||||
|
||||
let webhook: StripeWebhookBody = serde_json::from_str(&*body)?;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CheckoutSession {
|
||||
customer: String,
|
||||
metadata: SessionMetadata,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct SessionMetadata {
|
||||
user_id: UserId,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Invoice {
|
||||
customer: String,
|
||||
// paid: bool,
|
||||
lines: InvoiceLineItems,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct InvoiceLineItems {
|
||||
pub data: Vec<InvoiceLineItem>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct InvoiceLineItem {
|
||||
period: Period,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Period {
|
||||
// start: i64,
|
||||
end: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Subscription {
|
||||
customer: String,
|
||||
}
|
||||
|
||||
let mut transaction = pool.begin().await?;
|
||||
|
||||
// TODO: Currently hardcoded to midas-only. When we add more stuff should include price IDs
|
||||
match &*webhook.type_ {
|
||||
"checkout.session.completed" => {
|
||||
let session: CheckoutSession =
|
||||
serde_json::from_value(webhook.data.object)?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE users
|
||||
SET stripe_customer_id = $1
|
||||
WHERE (id = $2)
|
||||
",
|
||||
session.customer,
|
||||
session.metadata.user_id.0 as i64,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
"invoice.paid" => {
|
||||
let invoice: Invoice = serde_json::from_value(webhook.data.object)?;
|
||||
|
||||
if let Some(item) = invoice.lines.data.first() {
|
||||
let expires: DateTime<Utc> = DateTime::from_utc(
|
||||
NaiveDateTime::from_timestamp(item.period.end, 0),
|
||||
Utc,
|
||||
) + Duration::days(1);
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE users
|
||||
SET midas_expires = $1, is_overdue = FALSE
|
||||
WHERE (stripe_customer_id = $2)
|
||||
",
|
||||
expires,
|
||||
invoice.customer,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
"invoice.payment_failed" => {
|
||||
let invoice: Invoice = serde_json::from_value(webhook.data.object)?;
|
||||
|
||||
let customer_id = sqlx::query!(
|
||||
"
|
||||
SELECT u.id
|
||||
FROM users u
|
||||
WHERE u.stripe_customer_id = $1
|
||||
",
|
||||
invoice.customer,
|
||||
)
|
||||
.fetch_optional(&**pool)
|
||||
.await?
|
||||
.map(|x| x.id);
|
||||
|
||||
if let Some(user_id) = customer_id {
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE users
|
||||
SET is_overdue = TRUE
|
||||
WHERE (id = $1)
|
||||
",
|
||||
user_id,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
"customer.subscription.deleted" => {
|
||||
let session: Subscription =
|
||||
serde_json::from_value(webhook.data.object)?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE users
|
||||
SET stripe_customer_id = NULL, midas_expires = NULL, is_overdue = NULL
|
||||
WHERE (stripe_customer_id = $1)
|
||||
",
|
||||
session.customer,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
|
||||
transaction.commit().await?;
|
||||
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod auth;
|
||||
mod health;
|
||||
mod index;
|
||||
mod maven;
|
||||
mod midas;
|
||||
mod moderation;
|
||||
mod not_found;
|
||||
mod notifications;
|
||||
@@ -41,7 +42,8 @@ pub fn v2_config(cfg: &mut web::ServiceConfig) {
|
||||
.configure(moderation_config)
|
||||
.configure(reports_config)
|
||||
.configure(notifications_config)
|
||||
.configure(admin_config),
|
||||
.configure(admin_config)
|
||||
.configure(midas_config),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -169,6 +171,15 @@ pub fn admin_config(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(web::scope("admin").service(admin::count_download));
|
||||
}
|
||||
|
||||
pub fn midas_config(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(
|
||||
web::scope("midas")
|
||||
.service(midas::init_checkout)
|
||||
.service(midas::init_customer_portal)
|
||||
.service(midas::handle_stripe_webhook),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum ApiError {
|
||||
#[error("Environment Error")]
|
||||
@@ -195,6 +206,12 @@ pub enum ApiError {
|
||||
Search(#[from] meilisearch_sdk::errors::Error),
|
||||
#[error("Indexing Error: {0}")]
|
||||
Indexing(#[from] crate::search::indexing::IndexingError),
|
||||
#[error("Ariadne Error: {0}")]
|
||||
Analytics(String),
|
||||
#[error("Crypto Error: {0}")]
|
||||
Crypto(String),
|
||||
#[error("Payments Error: {0}")]
|
||||
Payments(String),
|
||||
}
|
||||
|
||||
impl actix_web::ResponseError for ApiError {
|
||||
@@ -234,6 +251,13 @@ impl actix_web::ResponseError for ApiError {
|
||||
ApiError::Validation(..) => {
|
||||
actix_web::http::StatusCode::BAD_REQUEST
|
||||
}
|
||||
ApiError::Analytics(..) => {
|
||||
actix_web::http::StatusCode::FAILED_DEPENDENCY
|
||||
}
|
||||
ApiError::Crypto(..) => actix_web::http::StatusCode::FORBIDDEN,
|
||||
ApiError::Payments(..) => {
|
||||
actix_web::http::StatusCode::FAILED_DEPENDENCY
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,6 +277,9 @@ impl actix_web::ResponseError for ApiError {
|
||||
ApiError::FileHosting(..) => "file_hosting_error",
|
||||
ApiError::InvalidInput(..) => "invalid_input",
|
||||
ApiError::Validation(..) => "invalid_input",
|
||||
ApiError::Analytics(..) => "analytics_error",
|
||||
ApiError::Crypto(..) => "crypto_error",
|
||||
ApiError::Payments(..) => "payments_error",
|
||||
},
|
||||
description: &self.to_string(),
|
||||
},
|
||||
|
||||
@@ -17,6 +17,7 @@ use actix_web::web::Data;
|
||||
use actix_web::{post, HttpRequest, HttpResponse};
|
||||
use chrono::Utc;
|
||||
use futures::stream::StreamExt;
|
||||
use rust_decimal::Decimal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::postgres::PgPool;
|
||||
use std::sync::Arc;
|
||||
@@ -274,9 +275,7 @@ pub async fn project_create(
|
||||
// fix multipart error bug:
|
||||
payload.for_each(|_| ready(())).await;
|
||||
|
||||
if let Err(e) = undo_result {
|
||||
return Err(e);
|
||||
}
|
||||
undo_result?;
|
||||
if let Err(e) = rollback_result {
|
||||
return Err(e.into());
|
||||
}
|
||||
@@ -628,7 +627,7 @@ pub async fn project_create_inner(
|
||||
role: crate::models::teams::OWNER_ROLE.to_owned(),
|
||||
permissions: crate::models::teams::Permissions::ALL,
|
||||
accepted: true,
|
||||
payouts_split: 100.0,
|
||||
payouts_split: Decimal::from(100),
|
||||
}],
|
||||
};
|
||||
|
||||
@@ -793,7 +792,8 @@ pub async fn project_create_inner(
|
||||
let _project_id = project_builder.insert(&mut *transaction).await?;
|
||||
|
||||
if status == ProjectStatus::Processing {
|
||||
if let Ok(webhook_url) = dotenvy::var("MODERATION_DISCORD_WEBHOOK") {
|
||||
if let Ok(webhook_url) = dotenvy::var("MODERATION_DISCORD_WEBHOOK")
|
||||
{
|
||||
crate::util::webhook::send_discord_webhook(
|
||||
response.clone(),
|
||||
webhook_url,
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::models::users::UserId;
|
||||
use crate::routes::ApiError;
|
||||
use crate::util::auth::get_user_from_headers;
|
||||
use actix_web::{delete, get, patch, post, web, HttpRequest, HttpResponse};
|
||||
use rust_decimal::Decimal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
|
||||
@@ -216,7 +217,7 @@ pub struct NewTeamMember {
|
||||
#[serde(default = "Permissions::default")]
|
||||
pub permissions: Permissions,
|
||||
#[serde(default)]
|
||||
pub payouts_split: f32,
|
||||
pub payouts_split: Decimal,
|
||||
}
|
||||
|
||||
#[post("{id}/members")]
|
||||
@@ -259,7 +260,9 @@ pub async fn add_team_member(
|
||||
));
|
||||
}
|
||||
|
||||
if !(0.0..=5000.0).contains(&new_member.payouts_split) {
|
||||
if new_member.payouts_split < Decimal::from(0)
|
||||
|| new_member.payouts_split > Decimal::from(5000)
|
||||
{
|
||||
return Err(ApiError::InvalidInput(
|
||||
"Payouts split must be between 0 and 5000!".to_string(),
|
||||
));
|
||||
@@ -360,7 +363,7 @@ pub async fn add_team_member(
|
||||
pub struct EditTeamMember {
|
||||
pub permissions: Option<Permissions>,
|
||||
pub role: Option<String>,
|
||||
pub payouts_split: Option<f32>,
|
||||
pub payouts_split: Option<Decimal>,
|
||||
}
|
||||
|
||||
#[patch("{id}/members/{user_id}")]
|
||||
@@ -419,7 +422,9 @@ pub async fn edit_team_member(
|
||||
}
|
||||
|
||||
if let Some(payouts_split) = edit_member.payouts_split {
|
||||
if !(0.0..=5000.0).contains(&payouts_split) {
|
||||
if payouts_split < Decimal::from(0)
|
||||
|| payouts_split > Decimal::from(5000)
|
||||
{
|
||||
return Err(ApiError::InvalidInput(
|
||||
"Payouts split must be between 0 and 5000!".to_string(),
|
||||
));
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
use crate::database::models::User;
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::models::notifications::Notification;
|
||||
use crate::models::projects::{Project, ProjectStatus};
|
||||
use crate::models::projects::{Project, ProjectId, ProjectStatus};
|
||||
use crate::models::users::{Badges, Role, UserId};
|
||||
use crate::routes::ApiError;
|
||||
use crate::util::auth::get_user_from_headers;
|
||||
use crate::util::auth::{check_is_admin_from_headers, get_user_from_headers};
|
||||
use crate::util::payout_calc::get_claimable_time;
|
||||
use crate::util::routes::read_from_payload;
|
||||
use crate::util::validate::validation_errors_to_string;
|
||||
use actix_web::{delete, get, patch, web, HttpRequest, HttpResponse};
|
||||
use chrono::{DateTime, Utc};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use rust_decimal::Decimal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use validator::Validate;
|
||||
@@ -20,10 +24,8 @@ pub async fn user_auth_get(
|
||||
req: HttpRequest,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
Ok(HttpResponse::Ok().json(
|
||||
get_user_from_headers(req.headers(), &mut *pool.acquire().await?)
|
||||
.await?,
|
||||
))
|
||||
Ok(HttpResponse::Ok()
|
||||
.json(get_user_from_headers(req.headers(), &**pool).await?))
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -155,6 +157,8 @@ pub struct EditUser {
|
||||
pub bio: Option<Option<String>>,
|
||||
pub role: Option<Role>,
|
||||
pub badges: Option<Badges>,
|
||||
#[validate(email, length(max = 128))]
|
||||
pub paypal_email: Option<Option<String>>,
|
||||
}
|
||||
|
||||
#[patch("{id}")]
|
||||
@@ -299,6 +303,20 @@ pub async fn user_edit(
|
||||
.await?;
|
||||
}
|
||||
|
||||
if let Some(paypal_email) = &new_user.paypal_email {
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE users
|
||||
SET paypal_email = $1
|
||||
WHERE (id = $2)
|
||||
",
|
||||
paypal_email.as_deref(),
|
||||
id as crate::database::models::ids::UserId,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
|
||||
transaction.commit().await?;
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
} else {
|
||||
@@ -542,3 +560,102 @@ pub async fn user_notifications(
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Payout {
|
||||
pub claimed: bool,
|
||||
pub claimable: bool,
|
||||
pub created: DateTime<Utc>,
|
||||
pub project: Option<ProjectId>,
|
||||
pub amount: Decimal,
|
||||
}
|
||||
|
||||
#[get("{id}/payouts")]
|
||||
pub async fn user_payouts(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(String,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
let id_option =
|
||||
User::get_id_from_username_or_id(&*info.into_inner().0, &**pool)
|
||||
.await?;
|
||||
|
||||
if let Some(id) = id_option {
|
||||
if !user.role.is_admin() && user.id != id.into() {
|
||||
return Err(ApiError::CustomAuthentication(
|
||||
"You do not have permission to see the payouts of this user!"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
use futures::TryStreamExt;
|
||||
|
||||
let payouts: Vec<Payout> = sqlx::query!(
|
||||
"
|
||||
SELECT pv.mod_id, pv.created, pv.claimed, pv.amount
|
||||
FROM payouts_values pv
|
||||
WHERE pv.user_id = $1
|
||||
ORDER BY pv.created DESC
|
||||
",
|
||||
id as crate::database::models::UserId
|
||||
)
|
||||
.fetch_many(&**pool)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right().map(|row| {
|
||||
let claimable_time: DateTime<Utc> =
|
||||
get_claimable_time(row.created, true);
|
||||
|
||||
Payout {
|
||||
claimed: row.claimed,
|
||||
claimable: Utc::now() > claimable_time,
|
||||
created: row.created,
|
||||
project: row.mod_id.map(|x| ProjectId(x as u64)),
|
||||
amount: row.amount,
|
||||
}
|
||||
}))
|
||||
})
|
||||
.try_collect::<Vec<Payout>>()
|
||||
.await?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(json!({
|
||||
"all_time": payouts.iter().map(|x| x.amount).sum::<Decimal>(),
|
||||
"current_period": payouts.iter().filter(|x| !x.claimed && !x.claimable).map(|x| x.amount).sum::<Decimal>(),
|
||||
"withdrawable": payouts.iter().filter(|x| x.claimable && !x.claimed).map(|x| x.amount).sum::<Decimal>(),
|
||||
"payouts": payouts,
|
||||
})))
|
||||
} else {
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
|
||||
#[get("{id}/payouts")]
|
||||
pub async fn finish_user_payout(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(String,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
check_is_admin_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
let id_option =
|
||||
User::get_id_from_username_or_id(&*info.into_inner().0, &**pool)
|
||||
.await?;
|
||||
|
||||
if let Some(id) = id_option {
|
||||
sqlx::query!(
|
||||
"
|
||||
UPDATE payouts_values
|
||||
SET claimed = TRUE
|
||||
WHERE (claimed = FALSE AND user_id = $1 AND created <= $2)
|
||||
",
|
||||
id as crate::database::models::ids::UserId,
|
||||
get_claimable_time(Utc::now(), false)
|
||||
)
|
||||
.execute(&**pool)
|
||||
.await?;
|
||||
|
||||
Ok(HttpResponse::NoContent().body(""))
|
||||
} else {
|
||||
Ok(HttpResponse::NotFound().body(""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,9 +136,7 @@ pub async fn mod_create(
|
||||
let undo_result = undo_uploads(&***file_host, &uploaded_files).await;
|
||||
let rollback_result = transaction.rollback().await;
|
||||
|
||||
if let Err(e) = undo_result {
|
||||
return Err(e);
|
||||
}
|
||||
undo_result?;
|
||||
if let Err(e) = rollback_result {
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::database;
|
||||
use crate::models::ids::{ProjectId, UserId, VersionId};
|
||||
use crate::models::projects::{
|
||||
Dependency, GameVersion, Loader, Version, VersionFile, VersionType,
|
||||
@@ -7,12 +7,10 @@ use crate::models::teams::Permissions;
|
||||
use crate::routes::versions::{VersionIds, VersionListFilters};
|
||||
use crate::routes::ApiError;
|
||||
use crate::util::auth::get_user_from_headers;
|
||||
use crate::{database, models};
|
||||
use actix_web::{delete, get, web, HttpRequest, HttpResponse};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A specific version of a mod
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -286,7 +284,6 @@ pub async fn delete_file(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(String,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
file_host: web::Data<Arc<dyn FileHost + Send + Sync>>,
|
||||
algorithm: web::Query<Algorithm>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
@@ -92,9 +92,7 @@ pub async fn version_create(
|
||||
|
||||
payload.for_each(|_| ready(())).await;
|
||||
|
||||
if let Err(e) = undo_result {
|
||||
return Err(e);
|
||||
}
|
||||
undo_result?;
|
||||
if let Err(e) = rollback_result {
|
||||
return Err(e.into());
|
||||
}
|
||||
@@ -461,9 +459,7 @@ pub async fn upload_file_to_version(
|
||||
|
||||
payload.for_each(|_| ready(())).await;
|
||||
|
||||
if let Err(e) = undo_result {
|
||||
return Err(e);
|
||||
}
|
||||
undo_result?;
|
||||
if let Err(e) = rollback_result {
|
||||
return Err(e.into());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use super::ApiError;
|
||||
use crate::database::models::{version_item::QueryVersion, DatabaseError};
|
||||
use crate::file_hosting::FileHost;
|
||||
use crate::models::projects::{GameVersion, Loader, Version};
|
||||
use crate::models::teams::Permissions;
|
||||
use crate::util::auth::get_user_from_headers;
|
||||
@@ -10,7 +9,6 @@ use actix_web::{delete, get, post, web, HttpRequest, HttpResponse};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -114,7 +112,6 @@ pub async fn delete_file(
|
||||
req: HttpRequest,
|
||||
info: web::Path<(String,)>,
|
||||
pool: web::Data<PgPool>,
|
||||
file_host: web::Data<Arc<dyn FileHost + Send + Sync>>,
|
||||
algorithm: web::Query<Algorithm>,
|
||||
) -> Result<HttpResponse, ApiError> {
|
||||
let user = get_user_from_headers(req.headers(), &**pool).await?;
|
||||
|
||||
Reference in New Issue
Block a user