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::project::{
MerchantOverviewResponse, ProjectLimitsResponse, ProjectResponse, ProjectStatsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Projects {
inner: Arc<Inner>,
}
impl Projects {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
params: &ProjectCreateRequest,
merchant_id: &str,
) -> Result<ProjectResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/projects",
Some(&body),
&[("merchant_id", merchant_id.to_string())],
None,
)
.await
}
pub async fn retrieve(
&self,
project_id: &str,
merchant_id: Option<&str>,
) -> Result<ProjectResponse> {
let path = format!("/projects/{}", encode_segment(project_id));
self.inner
.request(
HttpMethod::Get,
&path,
None,
&merchant_id_query(merchant_id),
None,
)
.await
}
pub async fn update(
&self,
project_id: &str,
params: &ProjectUpdateRequest,
merchant_id: Option<&str>,
) -> Result<ProjectResponse> {
params.validate()?;
let path = format!("/projects/{}", encode_segment(project_id));
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Put,
&path,
Some(&body),
&merchant_id_query(merchant_id),
None,
)
.await
}
pub async fn delete(
&self,
project_id: &str,
merchant_id: Option<&str>,
) -> Result<ProjectResponse> {
let path = format!("/projects/{}", encode_segment(project_id));
self.inner
.request(
HttpMethod::Delete,
&path,
None,
&merchant_id_query(merchant_id),
None,
)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<ProjectResponse>> {
self.inner
.request(
HttpMethod::Get,
"/projects/list",
None,
&[("merchant_id", merchant_id.to_string())],
None,
)
.await
}
pub async fn stats(
&self,
merchant_id: &str,
period: Option<StatsPeriod>,
) -> Result<ProjectStatsResponse> {
let mut query = vec![("merchant_id", merchant_id.to_string())];
if let Some(p) = period {
query.push(("period", p.to_query_value()));
}
self.inner
.request(HttpMethod::Get, "/projects/stats", None, &query, None)
.await
}
pub async fn overview(&self, merchant_id: &str) -> Result<MerchantOverviewResponse> {
self.inner
.request(
HttpMethod::Get,
"/projects/overview",
None,
&[("merchant_id", merchant_id.to_string())],
None,
)
.await
}
pub async fn limits(&self, merchant_id: &str) -> Result<ProjectLimitsResponse> {
self.inner
.request(
HttpMethod::Get,
"/projects/limits",
None,
&[("merchant_id", merchant_id.to_string())],
None,
)
.await
}
}
fn merchant_id_query(merchant_id: Option<&str>) -> Vec<(&'static str, String)> {
match merchant_id {
Some(id) => vec![("merchant_id", id.to_string())],
None => Vec::new(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatsPeriod {
Days(u32),
All,
}
impl StatsPeriod {
pub(crate) fn to_query_value(self) -> String {
match self {
StatsPeriod::Days(days) => days.to_string(),
StatsPeriod::All => "all".to_string(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProjectCreateRequest {
pub project_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_id: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ProjectCreateRequest {
pub fn new(project_name: impl Into<String>) -> Self {
Self {
project_name: project_name.into(),
..Default::default()
}
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn parent_id(mut self, parent_id: impl Into<String>) -> Self {
self.parent_id = Some(parent_id.into());
self
}
}
const PROJECT_CREATE_REQUEST_NAMED: &[&str] = &["project_name", "description", "parent_id"];
impl ValidateRequest for ProjectCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROJECT_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ProjectCreateRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProjectUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub project_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parent_id: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ProjectUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn project_name(mut self, project_name: impl Into<String>) -> Self {
self.project_name = Some(project_name.into());
self
}
#[must_use]
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn is_active(mut self, is_active: bool) -> Self {
self.is_active = Some(is_active);
self
}
#[must_use]
pub fn parent_id(mut self, parent_id: impl Into<String>) -> Self {
self.parent_id = Some(parent_id.into());
self
}
}
const PROJECT_UPDATE_REQUEST_NAMED: &[&str] =
&["project_name", "description", "is_active", "parent_id"];
impl ValidateRequest for ProjectUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROJECT_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ProjectUpdateRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const PROJECT_JSON: &str = r#"{
"id": "prj_1",
"merchant_id": "merch_123",
"project_name": "EU Stores",
"is_active": true,
"created_at": "2024-01-01T00:00:00Z",
"modified_at": "2024-01-02T00:00:00Z",
"description": "all EU shops",
"parent_id": "prj_0",
"level": 2,
"path": [{"id": "prj_0", "project_name": "Europe"}, {"id": "prj_1", "project_name": "EU Stores"}],
"child_project_count": 0,
"direct_shop_count": 3,
"surprise_field": 1
}"#;
const STATS_JSON: &str = r#"{
"projects": [
{
"project_id": "prj_1",
"project_name": "EU Stores",
"orders": 4,
"revenue": 5000,
"revenue_usd": 54.5,
"revenue_by_currency": [{"currency": "EUR", "amount_minor": 5000, "orders": 4}],
"unconverted_orders": 0,
"parent_id": null,
"level": 1,
"scope": "subtree",
"direct": {"orders": 1, "revenue": 100, "revenue_usd": 1.09,
"revenue_by_currency": [], "unconverted_orders": 0},
"descendant_shop_ids": ["pro_1", "pro_3"],
"shops": [
{
"shop_id": "pro_1",
"shop_name": "EU Store",
"project_id": "prj_1",
"orders": 4,
"revenue": 5000,
"revenue_usd": 54.5,
"revenue_by_currency": [],
"unconverted_orders": 0
}
]
}
],
"shops": [
{
"shop_id": "pro_2",
"shop_name": "Ungrouped Store",
"project_id": null,
"orders": 1,
"revenue": 100,
"revenue_usd": 1.09,
"revenue_by_currency": [],
"unconverted_orders": 1
}
],
"total_orders": 5,
"total_revenue": 5100,
"total_revenue_usd": 55.59,
"total_revenue_by_currency": [{"currency": "EUR", "amount_minor": 5100, "orders": 5}],
"unconverted_orders": 1,
"period_days": 7,
"analytics_exclusions_active": true
}"#;
#[tokio::test]
async fn create_posts_to_projects_with_the_merchant_query() {
let (client, mock) = client_with(vec![Step::ok(PROJECT_JSON)]);
let project = client
.projects()
.create(&ProjectCreateRequest::new("EU Stores"), "merch_123")
.await
.unwrap();
assert_eq!(project.id, "prj_1");
assert_eq!(project.parent_id.as_deref(), Some("prj_0"));
assert_eq!(project.level, 2);
assert_eq!(project.path[0].project_name, "Europe");
assert_eq!(project.direct_shop_count, 3);
assert_eq!(project.merchant_id, "merch_123");
assert_eq!(project.description.as_deref(), Some("all EU shops"));
assert!(project.is_active);
assert_eq!(project.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/projects?merchant_id=merch_123"
);
assert_eq!(seen[0].body_json()["project_name"], "EU Stores");
}
#[tokio::test]
async fn retrieve_encodes_the_project_id_and_omits_an_absent_merchant_scope() {
let (client, mock) = client_with(vec![Step::ok(PROJECT_JSON)]);
client.projects().retrieve("prj/1 x", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/projects/prj%2F1%20x");
}
#[tokio::test]
async fn retrieve_sends_the_merchant_scope_when_given() {
let (client, mock) = client_with(vec![Step::ok(PROJECT_JSON)]);
client
.projects()
.retrieve("prj_1", Some("merch_123"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/projects/prj_1?merchant_id=merch_123"
);
}
#[tokio::test]
async fn update_puts_the_body_and_the_merchant_scope() {
let (client, mock) = client_with(vec![Step::ok(PROJECT_JSON)]);
let params = ProjectUpdateRequest::new()
.project_name("APAC Stores")
.is_active(false);
client
.projects()
.update("prj_1", ¶ms, Some("merch_123"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/projects/prj_1?merchant_id=merch_123"
);
let body = seen[0].body_json();
assert_eq!(body["project_name"], "APAC Stores");
assert_eq!(body["is_active"], false);
}
#[tokio::test]
async fn delete_deletes_the_project_path() {
let (client, mock) = client_with(vec![Step::ok(PROJECT_JSON)]);
client.projects().delete("prj_1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/projects/prj_1");
}
#[tokio::test]
async fn list_gets_the_list_path_with_the_merchant_query() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{PROJECT_JSON}]"))]);
let projects = client.projects().list("merch_123").await.unwrap();
assert_eq!(projects[0].project_name, "EU Stores");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/projects/list?merchant_id=merch_123"
);
}
#[tokio::test]
async fn stats_serializes_both_period_forms_and_omits_an_absent_period() {
let (client, mock) = client_with(vec![
Step::ok(STATS_JSON),
Step::ok(STATS_JSON),
Step::ok(STATS_JSON),
]);
let projects = client.projects();
projects.stats("merch_123", None).await.unwrap();
projects
.stats("merch_123", Some(StatsPeriod::All))
.await
.unwrap();
projects
.stats("merch_123", Some(StatsPeriod::Days(7)))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/projects/stats?merchant_id=merch_123"
);
assert_eq!(
seen[1].url,
"https://api.test/projects/stats?merchant_id=merch_123&period=all"
);
assert_eq!(
seen[2].url,
"https://api.test/projects/stats?merchant_id=merch_123&period=7"
);
}
#[tokio::test]
async fn limits_gets_the_limits_path_with_the_merchant_scope() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"max_depth":3,"source":"merchant_override","deepest_level":2,"surprise_field":1}"#,
)]);
let limits = client.projects().limits("merch_123").await.unwrap();
assert_eq!(limits.max_depth, 3);
assert_eq!(limits.source, "merchant_override");
assert_eq!(limits.deepest_level, 2);
assert_eq!(limits.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/projects/limits?merchant_id=merch_123"
);
}
#[tokio::test]
async fn overview_gets_the_overview_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"total_shops": {"label": "Total shops", "value": 3, "change_percent": 50.0},
"active_shops": {"label": "Active shops", "value": 2, "change_percent": 0.0}
}"#,
)]);
let overview = client.projects().overview("merch_123").await.unwrap();
assert_eq!(overview.total_shops.label, "Total shops");
assert_eq!(overview.total_shops.value, 3.0);
assert_eq!(overview.total_shops.change_percent, 50.0);
assert_eq!(overview.active_shops.value, 2.0);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/projects/overview?merchant_id=merch_123"
);
}
#[tokio::test]
async fn stats_decodes_the_project_tree_and_the_flat_shop_list() {
let (client, _mock) = client_with(vec![Step::ok(STATS_JSON)]);
let stats = client.projects().stats("merch_123", None).await.unwrap();
assert_eq!(stats.total_orders, 5);
assert_eq!(stats.total_revenue, 5100);
assert_eq!(stats.total_revenue_usd, 55.59);
assert_eq!(stats.total_revenue_by_currency[0].currency, "EUR");
assert_eq!(stats.total_revenue_by_currency[0].amount_minor, 5100);
assert_eq!(stats.unconverted_orders, 1);
assert_eq!(stats.period_days, Some(7));
assert_eq!(stats.projects[0].project_id, "prj_1");
assert_eq!(stats.projects[0].revenue_usd, 54.5);
assert_eq!(stats.projects[0].shops[0].shop_id, "pro_1");
assert_eq!(stats.shops[0].shop_id, "pro_2");
assert_eq!(stats.shops[0].project_id, None);
assert_eq!(stats.shops[0].unconverted_orders, 1);
assert_eq!(stats.projects[0].scope.as_deref(), Some("subtree"));
assert_eq!(stats.projects[0].direct.as_ref().unwrap().orders, 1);
assert_eq!(stats.projects[0].descendant_shop_ids, ["pro_1", "pro_3"]);
assert!(stats.analytics_exclusions_active);
}
#[test]
fn project_create_request_named_fields_are_complete() {
let req = ProjectCreateRequest::new("EU Stores")
.description("all EU shops")
.parent_id("prj_0");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROJECT_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"PROJECT_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn project_update_request_named_fields_are_complete() {
let req = ProjectUpdateRequest::new()
.project_name("EU Stores")
.description("all EU shops")
.is_active(true)
.parent_id("prj_0");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROJECT_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"PROJECT_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = ProjectCreateRequest::new("EU Stores");
req.extra.insert("description".to_string(), json!("dupe"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("description")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn update_validate_rejects_colliding_extra_key() {
let mut req = ProjectUpdateRequest::new();
req.extra.insert("is_active".to_string(), json!(true));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("is_active")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}