use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::whop_case::{
WhopResolutionCase, WhopResolutionCaseActionResponse, WhopResolutionCaseEventList,
WhopResolutionCaseList,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct WhopResolutionCases {
inner: Arc<Inner>,
}
impl WhopResolutionCases {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(
&self,
params: &WhopResolutionCaseListParams,
) -> Result<WhopResolutionCaseList> {
self.inner
.request(
HttpMethod::Get,
"/disputes/whop/cases",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn retrieve(
&self,
case_id: &str,
locator: &WhopResolutionCaseLocator,
) -> Result<WhopResolutionCase> {
self.inner
.request(
HttpMethod::Get,
&case_path(case_id),
None,
&locator.to_query(),
None,
)
.await
}
pub async fn events(
&self,
case_id: &str,
params: &WhopResolutionCaseEventsParams,
) -> Result<WhopResolutionCaseEventList> {
let path = format!("{}/events", case_path(case_id));
self.inner
.request(HttpMethod::Get, &path, None, ¶ms.to_query(), None)
.await
}
pub async fn act(
&self,
case_id: &str,
params: &WhopResolutionCaseActionRequest,
) -> Result<WhopResolutionCaseActionResponse> {
params.validate()?;
let path = format!("{}/actions", case_path(case_id));
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
}
fn case_path(case_id: &str) -> String {
format!("/disputes/whop/cases/{}", encode_segment(case_id))
}
fn push_locator(
q: &mut Vec<(&'static str, String)>,
merchant_connector_id: &str,
test_mode: Option<bool>,
) {
q.push(("merchant_connector_id", merchant_connector_id.to_string()));
if let Some(v) = test_mode {
q.push(("test_mode", v.to_string()));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WhopResolutionCaseStatus {
AwaitingMerchant,
AwaitingCustomer,
UnderReview,
Closed,
}
impl WhopResolutionCaseStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::AwaitingMerchant => "awaiting_merchant",
Self::AwaitingCustomer => "awaiting_customer",
Self::UnderReview => "under_review",
Self::Closed => "closed",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseLocator {
pub merchant_connector_id: String,
pub test_mode: Option<bool>,
}
impl WhopResolutionCaseLocator {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
test_mode: None,
}
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
push_locator(&mut q, &self.merchant_connector_id, self.test_mode);
q
}
}
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseListParams {
pub merchant_connector_id: String,
pub test_mode: Option<bool>,
pub profile_id: Option<String>,
pub status: Option<WhopResolutionCaseStatus>,
pub limit: Option<u32>,
pub cursor: Option<String>,
}
impl WhopResolutionCaseListParams {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
..Default::default()
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
push_locator(&mut q, &self.merchant_connector_id, self.test_mode);
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = self.status {
q.push(("status", v.as_str().to_string()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = &self.cursor {
q.push(("cursor", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct WhopResolutionCaseEventsParams {
pub merchant_connector_id: String,
pub test_mode: Option<bool>,
pub limit: Option<u32>,
pub cursor: Option<String>,
}
impl WhopResolutionCaseEventsParams {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
..Default::default()
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
push_locator(&mut q, &self.merchant_connector_id, self.test_mode);
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = &self.cursor {
q.push(("cursor", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum WhopResolutionCaseAction {
Accept,
Deny,
Reply,
RequestInfo,
}
#[derive(Debug, Clone, Serialize)]
pub struct WhopResolutionCaseActionRequest {
pub merchant_connector_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
pub action: WhopResolutionCaseAction,
pub request_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub terminate_membership: Option<bool>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl WhopResolutionCaseActionRequest {
pub fn new(
merchant_connector_id: impl Into<String>,
action: WhopResolutionCaseAction,
request_id: impl Into<String>,
) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
test_mode: None,
action,
request_id: request_id.into(),
message: None,
terminate_membership: None,
extra: serde_json::Map::new(),
}
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
#[must_use]
pub fn message(mut self, message: impl Into<String>) -> Self {
self.message = Some(message.into());
self
}
#[must_use]
pub fn terminate_membership(mut self, terminate: bool) -> Self {
self.terminate_membership = Some(terminate);
self
}
}
const WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED: &[&str] = &[
"merchant_connector_id",
"test_mode",
"action",
"request_id",
"message",
"terminate_membership",
];
impl ValidateRequest for WhopResolutionCaseActionRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on WhopResolutionCaseActionRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const CASE_JSON: &str = r#"{
"case_id": "rc_1", "merchant_connector_id": "mca_1", "test_mode": true,
"profile_id": "pro_1", "payment_id": "pay_1", "attempt_id": null,
"connector_payment_id": "pay_whop_1", "status": "awaiting_merchant",
"reason": "product_not_received", "outcome": null, "refund": null,
"escalated": false, "customer_appealed": false, "amount": "10.00",
"currency": "USD", "response_due_at": "2026-01-05T00:00:00Z",
"created_at": "2026-01-01T00:00:00Z", "updated_at": null,
"product_id": null, "plan_id": null, "payment_method_type": "card",
"card_brand": "visa", "card_last4": "4242", "buyer_name": "Jane Buyer",
"buyer_username": "janeb", "buyer_email": "jane@example.com",
"available_actions": ["accept", "deny", "reply"], "case_surprise": 1
}"#;
#[tokio::test]
async fn list_sends_the_account_and_filters() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"cases":[{CASE_JSON}],"next_cursor":"c2","x":1}}"#
))]);
let params = WhopResolutionCaseListParams {
test_mode: Some(true),
status: Some(WhopResolutionCaseStatus::AwaitingMerchant),
limit: Some(10),
cursor: Some("c1".to_string()),
..WhopResolutionCaseListParams::new("mca_1")
};
let page = client.whop_resolution_cases().list(¶ms).await.unwrap();
assert_eq!(page.cases[0].case_id, "rc_1");
assert_eq!(page.cases[0].extra["case_surprise"], 1);
assert_eq!(page.next_cursor.as_deref(), Some("c2"));
assert_eq!(page.extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/disputes/whop/cases?merchant_connector_id=mca_1&test_mode=true\
&status=awaiting_merchant&limit=10&cursor=c1"
);
}
#[tokio::test]
async fn retrieve_encodes_the_case_id_and_redacts_the_buyer() {
let (client, mock) = client_with(vec![Step::ok(CASE_JSON)]);
let case = client
.whop_resolution_cases()
.retrieve("rc/1", &WhopResolutionCaseLocator::new("mca_1"))
.await
.unwrap();
assert_eq!(case.buyer_email.as_deref(), Some("jane@example.com"));
assert_eq!(case.available_actions, ["accept", "deny", "reply"]);
let printed = format!("{case:?}");
assert!(!printed.contains("jane@example.com"));
assert!(!printed.contains("Jane Buyer"));
assert!(!printed.contains("janeb"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/disputes/whop/cases/rc%2F1?merchant_connector_id=mca_1"
);
}
#[tokio::test]
async fn events_gets_the_events_sub_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"events":[{"event_id":"ev_1","action":"reply","reporter_type":"customer",
"details":"where is it?","viewable_by_customer":true,"created_at":null,
"attachments":[{"id":"att_1","filename":"receipt.png","content_type":"image/png","url":null}],
"x":1}],"next_cursor":null}"#,
)]);
let params = WhopResolutionCaseEventsParams {
test_mode: Some(false),
limit: Some(5),
..WhopResolutionCaseEventsParams::new("mca_1")
};
let out = client
.whop_resolution_cases()
.events("rc_1", ¶ms)
.await
.unwrap();
assert_eq!(out.events[0].attachments[0].id, "att_1");
assert_eq!(out.events[0].extra["x"], 1);
assert!(out.next_cursor.is_none());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/disputes/whop/cases/rc_1/events?merchant_connector_id=mca_1\
&test_mode=false&limit=5"
);
}
#[tokio::test]
async fn act_posts_the_action() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"request_id":"req_1","action":"deny","outcome":"submitted","case":{CASE_JSON},"x":1}}"#
))]);
let req =
WhopResolutionCaseActionRequest::new("mca_1", WhopResolutionCaseAction::Deny, "req_1")
.test_mode(true)
.message("delivered on time");
let out = client
.whop_resolution_cases()
.act("rc_1", &req)
.await
.unwrap();
assert_eq!(out.outcome, "submitted");
assert_eq!(out.case.case_id, "rc_1");
assert_eq!(out.extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/disputes/whop/cases/rc_1/actions"
);
assert_eq!(
seen[0].body_json(),
json!({
"merchant_connector_id": "mca_1",
"test_mode": true,
"action": "deny",
"request_id": "req_1",
"message": "delivered on time"
})
);
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn act_is_not_retried_on_5xx() {
let (client, mock) = client_with_retries(
vec![Step::status(500, r#"{"error":{"message":"boom"}}"#)],
2,
);
let req = WhopResolutionCaseActionRequest::new(
"mca_1",
WhopResolutionCaseAction::Accept,
"req_1",
);
client
.whop_resolution_cases()
.act("rc_1", &req)
.await
.unwrap_err();
assert_eq!(mock.call_count(), 1);
}
#[test]
fn whop_resolution_case_action_request_named_fields_are_complete() {
let req = WhopResolutionCaseActionRequest::new(
"mca_1",
WhopResolutionCaseAction::Accept,
"req_1",
)
.test_mode(true)
.message("m")
.terminate_membership(true);
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED.contains(&key.as_str()),
"WHOP_RESOLUTION_CASE_ACTION_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn act_validate_rejects_colliding_extra_key() {
let mut req =
WhopResolutionCaseActionRequest::new("mca_1", WhopResolutionCaseAction::Reply, "r");
req.extra.insert("action".to_string(), json!("accept"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("action")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn writes_ignore_the_client_wide_idempotency_key() {
let steps = (0..1)
.map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
.collect();
let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
let client = client.with_idempotency_key("client-key");
client
.whop_resolution_cases()
.act(
"rc_1",
&WhopResolutionCaseActionRequest::new(
"mca_1",
WhopResolutionCaseAction::Accept,
"req_1",
),
)
.await
.unwrap_err();
assert_eq!(mock.call_count(), 1);
for seen in mock.seen.lock().unwrap().iter() {
assert!(
!seen.had_idempotency_key(),
"{} sent the client key",
seen.url
);
}
}
}