| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
use std::sync::Arc; |
| 16 |
|
| 17 |
use sqlx::PgPool; |
| 18 |
|
| 19 |
use crate::auth::SessionUser; |
| 20 |
use crate::db::{self, ItemId, TransactionId}; |
| 21 |
use crate::error::{AppError, Result}; |
| 22 |
use crate::payments::Refundable; |
| 23 |
use crate::routes::api::verify_item_ownership; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
#[tracing::instrument(skip_all, name = "payments::refund")] |
| 38 |
pub async fn refund( |
| 39 |
db: &PgPool, |
| 40 |
stripe: Option<&Arc<dyn Refundable>>, |
| 41 |
user: &SessionUser, |
| 42 |
item: ItemId, |
| 43 |
transaction: TransactionId, |
| 44 |
) -> Result<()> { |
| 45 |
user.check_not_suspended()?; |
| 46 |
verify_item_ownership(db, item, user.id).await?; |
| 47 |
|
| 48 |
|
| 49 |
let tx = db::transactions::get_transaction_by_id(db, transaction) |
| 50 |
.await? |
| 51 |
.ok_or(AppError::NotFound)?; |
| 52 |
|
| 53 |
if tx.item_id != Some(item) { |
| 54 |
return Err(AppError::Forbidden); |
| 55 |
} |
| 56 |
if tx.seller_id != Some(user.id) { |
| 57 |
return Err(AppError::Forbidden); |
| 58 |
} |
| 59 |
if tx.status != db::TransactionStatus::Completed { |
| 60 |
return Err(AppError::BadRequest( |
| 61 |
"Transaction is not in a refundable state".into(), |
| 62 |
)); |
| 63 |
} |
| 64 |
|
| 65 |
let payment_intent_id = tx.stripe_payment_intent_id.as_deref().ok_or_else(|| { |
| 66 |
AppError::BadRequest("No payment intent, free claims cannot be refunded".into()) |
| 67 |
})?; |
| 68 |
|
| 69 |
|
| 70 |
let seller = db::users::get_user_by_id(db, user.id) |
| 71 |
.await? |
| 72 |
.ok_or(AppError::NotFound)?; |
| 73 |
let stripe_account_id = seller |
| 74 |
.stripe_account_id |
| 75 |
.as_deref() |
| 76 |
.ok_or_else(|| AppError::BadRequest("No Stripe account connected".into()))?; |
| 77 |
|
| 78 |
let stripe = stripe |
| 79 |
.ok_or_else(|| AppError::ServiceUnavailable("Stripe is not configured".to_string()))?; |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
if db::transactions::claim_transaction_for_refund(db, tx.id) |
| 87 |
.await? |
| 88 |
.is_none() |
| 89 |
{ |
| 90 |
return Err(AppError::BadRequest( |
| 91 |
"A refund for this transaction is already in progress".into(), |
| 92 |
)); |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
if let Err(e) = stripe |
| 99 |
.create_refund_for_transaction( |
| 100 |
payment_intent_id, |
| 101 |
stripe_account_id, |
| 102 |
tx.amount_cents.as_i64(), |
| 103 |
tx.id, |
| 104 |
) |
| 105 |
.await |
| 106 |
{ |
| 107 |
db::transactions::release_refund_claim(db, tx.id).await?; |
| 108 |
return Err(e); |
| 109 |
} |
| 110 |
|
| 111 |
Ok(()) |
| 112 |
} |
| 113 |
|