use std::sync::Arc;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::analytics::DrillResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct Analytics {
inner: Arc<Inner>,
}
impl Analytics {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn scope(&self, params: Option<&AnalyticsScopeParams>) -> Result<Value> {
let query = params
.map(AnalyticsScopeParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/analytics/scope", None, &query, None)
.await
}
pub async fn devices(&self, params: Option<&ClientAnalyticsParams>) -> Result<Value> {
let query = params
.map(ClientAnalyticsParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/analytics/devices", None, &query, None)
.await
}
pub async fn geo(&self, params: Option<&ClientAnalyticsParams>) -> Result<Value> {
let query = params
.map(ClientAnalyticsParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/analytics/geo", None, &query, None)
.await
}
pub async fn scope_transactions(&self, params: &ScopeDrillParams) -> Result<DrillResponse> {
params.validate()?;
self.inner
.request(
HttpMethod::Get,
"/analytics/scope/transactions",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn geo_transactions(&self, params: &GeoDrillParams) -> Result<DrillResponse> {
self.inner
.request(
HttpMethod::Get,
"/analytics/geo/transactions",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn device_transactions(&self, params: &DeviceDrillParams) -> Result<DrillResponse> {
self.inner
.request(
HttpMethod::Get,
"/analytics/devices/transactions",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn subscriptions(
&self,
params: Option<&SubscriptionAnalyticsParams>,
) -> Result<Value> {
let query = params
.map(SubscriptionAnalyticsParams::to_query)
.unwrap_or_default();
self.inner
.request(
HttpMethod::Get,
"/analytics/subscriptions",
None,
&query,
None,
)
.await
}
pub async fn subscriptions_list(
&self,
params: &SubscriptionDrillParams,
) -> Result<DrillResponse> {
params.validate()?;
self.inner
.request(
HttpMethod::Get,
"/analytics/subscriptions/list",
None,
¶ms.to_query(),
None,
)
.await
}
pub async fn search(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/analytics/search",
Some(&body),
&[],
None,
)
.await
}
pub async fn search_domain(&self, domain: &str, params: &Value) -> Result<Value> {
let path = format!("/analytics/search/{}", encode_segment(domain));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn info(&self, domain: &str) -> Result<Value> {
let path = format!("/analytics/{}/info", encode_segment(domain));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn api_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/analytics/api-event-logs",
None,
query,
None,
)
.await
}
pub async fn sdk_event_logs(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/analytics/sdk-event-logs",
Some(&body),
&[],
None,
)
.await
}
pub async fn connector_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/analytics/connector-event-logs",
None,
query,
None,
)
.await
}
pub async fn routing_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/analytics/routing-event-logs",
None,
query,
None,
)
.await
}
pub async fn outgoing_webhook_event_logs(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/analytics/outgoing-webhook-event-logs",
None,
query,
None,
)
.await
}
}
#[derive(Debug, Clone, Default)]
pub struct AnalyticsScopeParams {
pub days: Option<i64>,
pub start_date: Option<String>,
pub end_date: Option<String>,
pub merchant_id: Option<String>,
pub project_id: Option<String>,
pub shop_id: Option<String>,
pub sections: Option<String>,
pub granularity: Option<AnalyticsGranularity>,
pub test_mode: Option<bool>,
}
impl AnalyticsScopeParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.days {
q.push(("days", v.to_string()));
}
if let Some(v) = &self.start_date {
q.push(("start_date", v.clone()));
}
if let Some(v) = &self.end_date {
q.push(("end_date", v.clone()));
}
if let Some(v) = &self.merchant_id {
q.push(("merchant_id", v.clone()));
}
if let Some(v) = &self.project_id {
q.push(("project_id", v.clone()));
}
if let Some(v) = &self.shop_id {
q.push(("shop_id", v.clone()));
}
if let Some(v) = &self.sections {
q.push(("sections", v.clone()));
}
if let Some(v) = self.granularity {
q.push(("granularity", v.as_str().to_string()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsGranularity {
Day,
Hour,
HalfHour,
QuarterHour,
FiveMinutes,
}
impl AnalyticsGranularity {
pub fn as_str(self) -> &'static str {
match self {
Self::Day => "day",
Self::Hour => "hour",
Self::HalfHour => "30m",
Self::QuarterHour => "15m",
Self::FiveMinutes => "5m",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientAnalyticsGranularity {
Day,
Hour,
}
impl ClientAnalyticsGranularity {
pub fn as_str(self) -> &'static str {
match self {
Self::Day => "day",
Self::Hour => "hour",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsOutcome {
Success,
Open,
Failed,
Void,
}
impl AnalyticsOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::Success => "success",
Self::Open => "open",
Self::Failed => "failed",
Self::Void => "void",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnalyticsChannel {
Hosted,
Embedded,
Api,
Dashboard,
Sdk,
Unknown,
}
impl AnalyticsChannel {
pub fn as_str(self) -> &'static str {
match self {
Self::Hosted => "hosted",
Self::Embedded => "embedded",
Self::Api => "api",
Self::Dashboard => "dashboard",
Self::Sdk => "sdk",
Self::Unknown => "unknown",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeToPayBucket {
UnderThirtySeconds,
ThirtyToSixtySeconds,
OneToTwoMinutes,
TwoToFiveMinutes,
FiveToFifteenMinutes,
OverFifteenMinutes,
}
impl TimeToPayBucket {
pub fn as_str(self) -> &'static str {
match self {
Self::UnderThirtySeconds => "lt_30s",
Self::ThirtyToSixtySeconds => "s30_60s",
Self::OneToTwoMinutes => "m1_2",
Self::TwoToFiveMinutes => "m2_5",
Self::FiveToFifteenMinutes => "m5_15",
Self::OverFifteenMinutes => "gt_15m",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DrillChildKind {
Merchant,
Project,
Shop,
}
impl DrillChildKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Merchant => "merchant",
Self::Project => "project",
Self::Shop => "shop",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SortDirection {
Ascending,
Descending,
}
impl SortDirection {
pub fn as_str(self) -> &'static str {
match self {
Self::Ascending => "asc",
Self::Descending => "desc",
}
}
}
pub trait DrillSortKey: Copy {
fn as_str(self) -> &'static str;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeDrillSortKey {
CreatedAt,
PaymentCreatedAt,
Amount,
Status,
Connector,
Method,
}
impl DrillSortKey for ScopeDrillSortKey {
fn as_str(self) -> &'static str {
match self {
Self::CreatedAt => "created_at",
Self::PaymentCreatedAt => "payment_created_at",
Self::Amount => "amount",
Self::Status => "status",
Self::Connector => "connector",
Self::Method => "method",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientDrillSortKey {
CreatedAt,
PaymentCreatedAt,
Amount,
Status,
Connector,
Method,
TimeToPay,
}
impl DrillSortKey for ClientDrillSortKey {
fn as_str(self) -> &'static str {
match self {
Self::CreatedAt => "created_at",
Self::PaymentCreatedAt => "payment_created_at",
Self::Amount => "amount",
Self::Status => "status",
Self::Connector => "connector",
Self::Method => "method",
Self::TimeToPay => "time_to_pay",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionDrillSortKey {
CreatedAt,
PaymentCreatedAt,
Amount,
Status,
Connector,
Plan,
}
impl DrillSortKey for SubscriptionDrillSortKey {
fn as_str(self) -> &'static str {
match self {
Self::CreatedAt => "created_at",
Self::PaymentCreatedAt => "payment_created_at",
Self::Amount => "amount",
Self::Status => "status",
Self::Connector => "connector",
Self::Plan => "plan",
}
}
}
#[derive(Debug, Clone)]
pub struct DrillListControls<K: DrillSortKey> {
pub q: Option<String>,
pub sort_on: Option<K>,
pub sort_by: Option<SortDirection>,
pub status: Option<String>,
pub connector: Option<String>,
pub method: Option<String>,
pub channel: Option<AnalyticsChannel>,
pub currency: Option<String>,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl<K: DrillSortKey> Default for DrillListControls<K> {
fn default() -> Self {
Self {
q: None,
sort_on: None,
sort_by: None,
status: None,
connector: None,
method: None,
channel: None,
currency: None,
limit: None,
offset: None,
}
}
}
impl<K: DrillSortKey> DrillListControls<K> {
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
if let Some(v) = &self.q {
q.push(("q", v.clone()));
}
if let Some(v) = self.sort_on {
q.push(("sort_on", v.as_str().to_string()));
}
if let Some(v) = self.sort_by {
q.push(("sort_by", v.as_str().to_string()));
}
if let Some(v) = &self.status {
q.push(("status", v.clone()));
}
if let Some(v) = &self.connector {
q.push(("connector", v.clone()));
}
if let Some(v) = &self.method {
q.push(("method", v.clone()));
}
if let Some(v) = self.channel {
q.push(("channel", v.as_str().to_string()));
}
if let Some(v) = &self.currency {
q.push(("currency", v.clone()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
}
}
#[derive(Debug, Clone, Default)]
pub struct DrillScope {
pub days: Option<i64>,
pub start_date: Option<String>,
pub end_date: Option<String>,
pub merchant_id: Option<String>,
pub project_id: Option<String>,
pub shop_id: Option<String>,
pub test_mode: Option<bool>,
pub country: Option<String>,
pub country_source: Option<String>,
pub device_class: Option<String>,
}
impl DrillScope {
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
if let Some(v) = self.days {
q.push(("days", v.to_string()));
}
if let Some(v) = &self.start_date {
q.push(("start_date", v.clone()));
}
if let Some(v) = &self.end_date {
q.push(("end_date", v.clone()));
}
if let Some(v) = &self.merchant_id {
q.push(("merchant_id", v.clone()));
}
if let Some(v) = &self.project_id {
q.push(("project_id", v.clone()));
}
if let Some(v) = &self.shop_id {
q.push(("shop_id", v.clone()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
if let Some(v) = &self.country {
q.push(("country", v.clone()));
}
if let Some(v) = &self.country_source {
q.push(("country_source", v.clone()));
}
if let Some(v) = &self.device_class {
q.push(("device_class", v.clone()));
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ScopeDrillTargets {
pub connector: Option<String>,
pub outcome: Option<AnalyticsOutcome>,
pub bucket: Option<String>,
pub method: Option<String>,
pub method_type: Option<String>,
pub child: Option<String>,
pub child_kind: Option<DrillChildKind>,
}
impl ScopeDrillTargets {
fn is_empty(&self) -> bool {
self.connector.is_none()
&& self.outcome.is_none()
&& self.bucket.is_none()
&& self.method.is_none()
&& self.child.is_none()
}
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
if let Some(v) = &self.connector {
q.push(("target_connector", v.clone()));
}
if let Some(v) = self.outcome {
q.push(("target_outcome", v.as_str().to_string()));
}
if let Some(v) = &self.bucket {
q.push(("target_bucket", v.clone()));
}
if let Some(v) = &self.method {
q.push(("target_method", v.clone()));
}
if let Some(v) = &self.method_type {
q.push(("target_method_type", v.clone()));
}
if let Some(v) = &self.child {
q.push(("target_child", v.clone()));
}
if let Some(v) = self.child_kind {
q.push(("target_child_kind", v.as_str().to_string()));
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum GeoDrillTarget {
Country {
country: String,
city: Option<String>,
},
HeatmapCell {
dow: i64,
hour: i64,
},
}
impl GeoDrillTarget {
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
match self {
Self::Country { country, city } => {
q.push(("target_country", country.clone()));
if let Some(city) = city {
q.push(("target_city", city.clone()));
}
}
Self::HeatmapCell { dow, hour } => {
q.push(("dow", dow.to_string()));
q.push(("hour", hour.to_string()));
}
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DeviceDrillTarget {
Browser(String),
Platform(String),
Model(String),
DeviceClass(String),
TimeToPayBucket(TimeToPayBucket),
Channel {
channel: AnalyticsChannel,
bucket: Option<String>,
},
}
impl DeviceDrillTarget {
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
match self {
Self::Browser(v) => q.push(("target_browser", v.clone())),
Self::Platform(v) => q.push(("target_platform", v.clone())),
Self::Model(v) => q.push(("target_model", v.clone())),
Self::DeviceClass(v) => q.push(("target_device_class", v.clone())),
Self::TimeToPayBucket(v) => q.push(("target_ttp_bucket", v.as_str().to_string())),
Self::Channel { channel, bucket } => {
q.push(("target_channel", channel.as_str().to_string()));
if let Some(bucket) = bucket {
q.push(("target_bucket", bucket.clone()));
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionInvoiceOutcome {
PaidFirst,
Retried,
Recovered,
Unpaid,
}
impl SubscriptionInvoiceOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::PaidFirst => "paid_first",
Self::Retried => "retried",
Self::Recovered => "recovered",
Self::Unpaid => "unpaid",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubscriptionMovement {
New,
Expansion,
Contraction,
Churn,
}
impl SubscriptionMovement {
pub fn as_str(self) -> &'static str {
match self {
Self::New => "new",
Self::Expansion => "expansion",
Self::Contraction => "contraction",
Self::Churn => "churn",
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum SubscriptionDrillTarget {
Outcome(SubscriptionInvoiceOutcome),
BillingProcessor(String),
ChargingConnector(String),
Plan(String),
Status(String),
Movement(SubscriptionMovement),
Child {
id: String,
kind: DrillChildKind,
},
}
impl SubscriptionDrillTarget {
fn push_query(&self, q: &mut Vec<(&'static str, String)>) {
match self {
Self::Outcome(v) => q.push(("target_outcome", v.as_str().to_string())),
Self::BillingProcessor(v) => q.push(("target_billing_processor", v.clone())),
Self::ChargingConnector(v) => q.push(("target_charging_connector", v.clone())),
Self::Plan(v) => q.push(("target_plan", v.clone())),
Self::Status(v) => q.push(("target_status", v.clone())),
Self::Movement(v) => q.push(("target_movement", v.as_str().to_string())),
Self::Child { id, kind } => {
q.push(("target_child", id.clone()));
q.push(("target_child_kind", kind.as_str().to_string()));
}
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ScopeDrillParams {
pub scope: DrillScope,
pub controls: DrillListControls<ScopeDrillSortKey>,
pub granularity: Option<AnalyticsGranularity>,
pub targets: ScopeDrillTargets,
}
impl ScopeDrillParams {
fn validate(&self) -> Result<()> {
if self.targets.is_empty() {
return Err(DelopayError::InvalidRequest(
"a payments drill needs at least one target: an untargeted request lists the \
whole window, which no click means"
.to_string(),
));
}
if self.targets.method_type.is_some() && self.targets.method.is_none() {
return Err(DelopayError::InvalidRequest(
"`method_type` qualifies `method`: sent alone it narrows nothing and the list \
silently answers a different question"
.to_string(),
));
}
if self.targets.child.is_some() != self.targets.child_kind.is_some() {
return Err(DelopayError::InvalidRequest(
"`child` and `child_kind` travel together: the server resolves a child id only \
with its kind, and matches nothing without it"
.to_string(),
));
}
Ok(())
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
self.scope.push_query(&mut q);
if let Some(v) = self.granularity {
q.push(("granularity", v.as_str().to_string()));
}
self.targets.push_query(&mut q);
self.controls.push_query(&mut q);
q
}
}
#[derive(Debug, Clone)]
pub struct GeoDrillParams {
pub scope: DrillScope,
pub controls: DrillListControls<ClientDrillSortKey>,
pub mode: Option<String>,
pub target: GeoDrillTarget,
}
impl GeoDrillParams {
pub fn country(country: impl Into<String>) -> Self {
Self::new(GeoDrillTarget::Country {
country: country.into(),
city: None,
})
}
pub fn new(target: GeoDrillTarget) -> Self {
Self {
scope: DrillScope::default(),
controls: DrillListControls::default(),
mode: None,
target,
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
self.scope.push_query(&mut q);
if let Some(v) = &self.mode {
q.push(("mode", v.clone()));
}
self.target.push_query(&mut q);
self.controls.push_query(&mut q);
q
}
}
#[derive(Debug, Clone)]
pub struct DeviceDrillParams {
pub scope: DrillScope,
pub controls: DrillListControls<ClientDrillSortKey>,
pub target: DeviceDrillTarget,
}
impl DeviceDrillParams {
pub fn new(target: DeviceDrillTarget) -> Self {
Self {
scope: DrillScope::default(),
controls: DrillListControls::default(),
target,
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
self.scope.push_query(&mut q);
self.target.push_query(&mut q);
self.controls.push_query(&mut q);
q
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionDrillParams {
pub scope: DrillScope,
pub controls: DrillListControls<SubscriptionDrillSortKey>,
pub target: Option<SubscriptionDrillTarget>,
pub bucket: Option<String>,
}
impl SubscriptionDrillParams {
pub fn new(target: SubscriptionDrillTarget) -> Self {
Self {
scope: DrillScope::default(),
controls: DrillListControls::default(),
target: Some(target),
bucket: None,
}
}
pub fn bucket(bucket: impl Into<String>) -> Self {
Self {
scope: DrillScope::default(),
controls: DrillListControls::default(),
target: None,
bucket: Some(bucket.into()),
}
}
fn validate(&self) -> Result<()> {
if self.target.is_none() && self.bucket.is_none() {
return Err(DelopayError::InvalidRequest(
"a subscription drill needs a target or a bucket: an untargeted request lists \
every cycle in the window, which no click means"
.to_string(),
));
}
Ok(())
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
self.scope.push_query(&mut q);
if let Some(target) = &self.target {
target.push_query(&mut q);
}
if let Some(v) = &self.bucket {
q.push(("target_bucket", v.clone()));
}
self.controls.push_query(&mut q);
q
}
}
#[derive(Debug, Clone, Default)]
pub struct ClientAnalyticsParams {
pub days: Option<i64>,
pub start_date: Option<String>,
pub end_date: Option<String>,
pub merchant_id: Option<String>,
pub project_id: Option<String>,
pub shop_id: Option<String>,
pub test_mode: Option<bool>,
pub granularity: Option<ClientAnalyticsGranularity>,
pub sections: Option<String>,
pub mode: Option<String>,
pub country: Option<String>,
pub country_source: Option<String>,
pub device_class: Option<String>,
}
impl ClientAnalyticsParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.days {
q.push(("days", v.to_string()));
}
if let Some(v) = &self.start_date {
q.push(("start_date", v.clone()));
}
if let Some(v) = &self.end_date {
q.push(("end_date", v.clone()));
}
if let Some(v) = &self.merchant_id {
q.push(("merchant_id", v.clone()));
}
if let Some(v) = &self.project_id {
q.push(("project_id", v.clone()));
}
if let Some(v) = &self.shop_id {
q.push(("shop_id", v.clone()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
if let Some(v) = self.granularity {
q.push(("granularity", v.as_str().to_string()));
}
if let Some(v) = &self.sections {
q.push(("sections", v.clone()));
}
if let Some(v) = &self.mode {
q.push(("mode", v.clone()));
}
if let Some(v) = &self.country {
q.push(("country", v.clone()));
}
if let Some(v) = &self.country_source {
q.push(("country_source", v.clone()));
}
if let Some(v) = &self.device_class {
q.push(("device_class", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionAnalyticsParams {
pub days: Option<i64>,
pub start_date: Option<String>,
pub end_date: Option<String>,
pub merchant_id: Option<String>,
pub project_id: Option<String>,
pub shop_id: Option<String>,
pub test_mode: Option<bool>,
pub sections: Option<String>,
pub country: Option<String>,
pub country_source: Option<String>,
pub device_class: Option<String>,
}
impl SubscriptionAnalyticsParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.days {
q.push(("days", v.to_string()));
}
if let Some(v) = &self.start_date {
q.push(("start_date", v.clone()));
}
if let Some(v) = &self.end_date {
q.push(("end_date", v.clone()));
}
if let Some(v) = &self.merchant_id {
q.push(("merchant_id", v.clone()));
}
if let Some(v) = &self.project_id {
q.push(("project_id", v.clone()));
}
if let Some(v) = &self.shop_id {
q.push(("shop_id", v.clone()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
if let Some(v) = &self.sections {
q.push(("sections", v.clone()));
}
if let Some(v) = &self.country {
q.push(("country", v.clone()));
}
if let Some(v) = &self.country_source {
q.push(("country_source", v.clone()));
}
if let Some(v) = &self.device_class {
q.push(("device_class", v.clone()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
#[tokio::test]
async fn scope_serializes_every_named_param_in_order() {
let (client, mock) = client_with(vec![Step::ok(r#"{"series":[]}"#)]);
let params = AnalyticsScopeParams {
days: Some(30),
start_date: Some("2026-01-01T00:00:00".to_string()),
end_date: Some("2026-01-31T00:00:00".to_string()),
merchant_id: Some("mer_1".to_string()),
project_id: Some("pro_1".to_string()),
shop_id: Some("shop_1".to_string()),
sections: Some("series,previous".to_string()),
granularity: Some(AnalyticsGranularity::Hour),
test_mode: Some(false),
};
client.analytics().scope(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/analytics/scope?days=30&start_date=2026-01-01T00:00:00\
&end_date=2026-01-31T00:00:00&merchant_id=mer_1&project_id=pro_1\
&shop_id=shop_1§ions=series,previous&granularity=hour&test_mode=false"
);
}
#[tokio::test]
async fn scope_without_params_sends_no_query() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
client.analytics().scope(None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/analytics/scope");
}
#[tokio::test]
async fn search_posts_the_body_to_analytics_search() {
let (client, mock) = client_with(vec![Step::ok("[]")]);
client
.analytics()
.search(&json!({"query": "pay_abc"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/analytics/search");
assert_eq!(seen[0].body_json()["query"], "pay_abc");
}
#[tokio::test]
async fn search_domain_encodes_the_domain_segment() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
client
.analytics()
.search_domain("payment intents/v2", &json!({"query": "x"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/analytics/search/payment%20intents%2Fv2"
);
assert_eq!(seen[0].body_json()["query"], "x");
}
#[tokio::test]
async fn info_encodes_the_domain_segment() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
client.analytics().info("payment intents").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/analytics/payment%20intents/info"
);
}
#[tokio::test]
async fn event_log_feeds_hit_their_own_paths() {
let (client, mock) = client_with(vec![
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
Step::ok("{}"),
]);
client
.analytics()
.api_event_logs(&[("limit", "5".to_string())])
.await
.unwrap();
client
.analytics()
.sdk_event_logs(&json!({"payment_id": "pay_1"}))
.await
.unwrap();
client
.analytics()
.connector_event_logs(&[("payment_id", "pay_1".to_string())])
.await
.unwrap();
client.analytics().routing_event_logs(&[]).await.unwrap();
client
.analytics()
.outgoing_webhook_event_logs(&[])
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
("GET", "https://api.test/analytics/api-event-logs?limit=5")
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("POST", "https://api.test/analytics/sdk-event-logs")
);
assert_eq!(seen[1].body_json()["payment_id"], "pay_1");
assert_eq!(
(seen[2].method, seen[2].url.as_str()),
(
"GET",
"https://api.test/analytics/connector-event-logs?payment_id=pay_1"
)
);
assert_eq!(
(seen[3].method, seen[3].url.as_str()),
("GET", "https://api.test/analytics/routing-event-logs")
);
assert_eq!(
(seen[4].method, seen[4].url.as_str()),
(
"GET",
"https://api.test/analytics/outgoing-webhook-event-logs"
)
);
}
#[tokio::test]
async fn a_drill_row_keeps_the_observation_time_and_the_payment_age_apart() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"enabled": true,
"caveats": [],
"total": 2,
"payments": [{
"payment_id": "pay_1",
"merchant_id": "mer_1",
"status": "succeeded",
"created_at": "2026-03-12T09:00:00Z",
"payment_created_at": "2026-02-01T08:00:00Z",
"connector": "stripe",
"payment_method": "card",
"payment_method_type": "credit",
"channel": "hosted",
"device_class": "phone",
"browser_family": "safari",
"platform_family": "ios",
"time_to_pay_s": 41.5,
"amount_usd": 12.5,
"refunded_minor": 0,
"customer_id": "cus_1",
"brand_new_field": 1
}],
"summary": {
"count": 2,
"successful_count": 1,
"successful_volume_usd": 12.5,
"refund_volume_usd": 0.0,
"success_rate": 0.5,
"median_amount_usd": 12.5,
"median_time_to_pay_s": 41.5,
"subscriptions": null,
"unconverted_count": 1
}
}"#,
)]);
let params = ScopeDrillParams {
targets: ScopeDrillTargets {
connector: Some("stripe".to_string()),
outcome: Some(AnalyticsOutcome::Failed),
..ScopeDrillTargets::default()
},
..ScopeDrillParams::default()
};
let drill = client
.analytics()
.scope_transactions(¶ms)
.await
.unwrap();
let row = &drill.payments[0];
assert_eq!(row.created_at, "2026-03-12T09:00:00Z");
assert_eq!(row.payment_created_at, "2026-02-01T08:00:00Z");
assert_eq!(row.connector.as_deref(), Some("stripe"));
assert!(row.extra.contains_key("brand_new_field"));
assert_eq!(drill.total, 2);
let summary = drill.summary.as_ref().unwrap();
assert_eq!(summary.unconverted_count, 1);
assert!(!summary.usd_is_complete());
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/scope/transactions\
?target_connector=stripe&target_outcome=failed"
);
}
#[tokio::test]
async fn a_missing_summary_is_absent_rather_than_zero() {
let (client, _mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
)]);
let drill = client
.analytics()
.device_transactions(&DeviceDrillParams::new(DeviceDrillTarget::Browser(
"chrome".to_string(),
)))
.await
.unwrap();
assert!(drill.summary.is_none());
}
#[tokio::test]
async fn a_payments_drill_refuses_the_targets_that_answer_a_different_question() {
let (client, mock) = client_with(vec![]);
let untargeted = ScopeDrillParams::default();
assert!(matches!(
client.analytics().scope_transactions(&untargeted).await,
Err(DelopayError::InvalidRequest(_))
));
let orphan_type = ScopeDrillParams {
targets: ScopeDrillTargets {
connector: Some("stripe".to_string()),
method_type: Some("credit".to_string()),
..ScopeDrillTargets::default()
},
..ScopeDrillParams::default()
};
assert!(matches!(
client.analytics().scope_transactions(&orphan_type).await,
Err(DelopayError::InvalidRequest(_))
));
let child_without_kind = ScopeDrillParams {
targets: ScopeDrillTargets {
child: Some("pro_1".to_string()),
..ScopeDrillTargets::default()
},
..ScopeDrillParams::default()
};
assert!(matches!(
client
.analytics()
.scope_transactions(&child_without_kind)
.await,
Err(DelopayError::InvalidRequest(_))
));
assert!(mock.seen.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_subscription_drill_needs_a_target_or_a_bucket() {
let (client, mock) = client_with(vec![]);
assert!(matches!(
client
.analytics()
.subscriptions_list(&SubscriptionDrillParams::default())
.await,
Err(DelopayError::InvalidRequest(_))
));
assert!(mock.seen.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_subscription_bucket_drill_sends_the_bucket_and_its_controls() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
)]);
let mut params = SubscriptionDrillParams::bucket("2026-03-12");
params.scope.days = Some(30);
params.controls.sort_on = Some(SubscriptionDrillSortKey::Plan);
params.controls.sort_by = Some(SortDirection::Ascending);
params.controls.limit = Some(200);
client
.analytics()
.subscriptions_list(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/subscriptions/list\
?days=30&target_bucket=2026-03-12&sort_on=plan&sort_by=asc&limit=200"
);
}
#[tokio::test]
async fn a_geo_drill_sends_its_claim_mode_and_city() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
)]);
let mut params = GeoDrillParams::new(GeoDrillTarget::Country {
country: "DE".to_string(),
city: Some("Berlin".to_string()),
});
params.mode = Some("billing".to_string());
client.analytics().geo_transactions(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/geo/transactions\
?mode=billing&target_country=DE&target_city=Berlin"
);
}
#[tokio::test]
async fn a_device_channel_drill_sends_the_channel_and_its_bucket() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
)]);
let params = DeviceDrillParams::new(DeviceDrillTarget::Channel {
channel: AnalyticsChannel::Embedded,
bucket: Some("2026-03-12".to_string()),
});
client
.analytics()
.device_transactions(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/devices/transactions\
?target_channel=embedded&target_bucket=2026-03-12"
);
}
#[tokio::test]
async fn a_time_to_pay_drill_sends_the_bar_token() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"caveats":[],"total":0,"payments":[]}"#,
)]);
let params = DeviceDrillParams::new(DeviceDrillTarget::TimeToPayBucket(
TimeToPayBucket::FiveToFifteenMinutes,
));
client
.analytics()
.device_transactions(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/devices/transactions?target_ttp_bucket=m5_15"
);
}
#[tokio::test]
async fn the_scope_series_takes_a_sub_hour_grain() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
let params = AnalyticsScopeParams {
days: Some(7),
granularity: Some(AnalyticsGranularity::FiveMinutes),
..AnalyticsScopeParams::default()
};
client.analytics().scope(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/scope?days=7&granularity=5m"
);
}
#[tokio::test]
async fn devices_and_geo_share_a_window_shape() {
let (client, mock) = client_with(vec![Step::ok("{}"), Step::ok("{}")]);
let params = ClientAnalyticsParams {
days: Some(30),
granularity: Some(ClientAnalyticsGranularity::Hour),
sections: Some("totals,children".to_string()),
device_class: Some("phone".to_string()),
..ClientAnalyticsParams::default()
};
client.analytics().devices(Some(¶ms)).await.unwrap();
client.analytics().geo(Some(¶ms)).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/devices\
?days=30&granularity=hour§ions=totals,children&device_class=phone"
);
assert!(
seen[1]
.url
.starts_with("https://api.test/analytics/geo?days=30")
);
}
#[tokio::test]
async fn subscription_analytics_sends_its_window_without_a_grain() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
let params = SubscriptionAnalyticsParams {
days: Some(92),
sections: Some("totals,movement".to_string()),
country: Some("DE".to_string()),
..SubscriptionAnalyticsParams::default()
};
client
.analytics()
.subscriptions(Some(¶ms))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/analytics/subscriptions\
?days=92§ions=totals,movement&country=DE"
);
}
}