use serde::Serialize;
use serde_json::{json, Value};
use crate::transport::{seg, Executor, Req};
use crate::types::{Created, ListParams, Platform};
macro_rules! namespace {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Debug, Clone)]
pub struct $name<C> {
c: C,
}
impl<C: Executor> $name<C> {
pub(crate) fn new(c: C) -> Self {
$name { c }
}
}
};
}
macro_rules! params {
($(#[$doc:meta])* $name:ident { $($(#[$fdoc:meta])* $field:ident : $ty:ty),* $(,)? }) => {
$(#[$doc])*
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct $name {
$($(#[$fdoc])* #[serde(skip_serializing_if = "Option::is_none")] pub $field: Option<$ty>,)*
}
};
}
namespace!(
Emails
);
impl<C: Executor> Emails<C> {
pub fn send<B: Serialize + ?Sized>(
&self,
email: &B,
idempotency_key: Option<&str>,
) -> C::Out<Created> {
self.c.run(
Req::post("/emails")
.json(email)
.idempotency(idempotency_key),
)
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!("/emails/{}", seg(id))))
}
pub fn list(&self, params: &ListParams) -> C::Out<Value> {
self.c.run(Req::get("/emails").query(params))
}
pub fn update(&self, id: &str, scheduled_at: &str) -> C::Out<Value> {
self.c.run(
Req::patch(format!("/emails/{}", seg(id)))
.json(&json!({ "scheduled_at": scheduled_at })),
)
}
pub fn cancel(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::post(format!("/emails/{}/cancel", seg(id))))
}
}
namespace!(
Batch
);
impl<C: Executor> Batch<C> {
pub fn send<B: Serialize>(&self, emails: &[B]) -> C::Out<Value> {
self.c.run(Req::post("/emails/batch").json(emails))
}
}
params!(
KnowledgeListParams { collection: String, tag: String, locale: String, after: String, limit: u32 }
);
namespace!(
Knowledge
);
impl<C: Executor> Knowledge<C> {
pub fn upsert<B: Serialize + ?Sized>(&self, id: &str, document: &B) -> C::Out<Value> {
self.c
.run(Req::put(format!("/chat/knowledge/documents/{}", seg(id))).json(document))
}
pub fn batch<B: Serialize>(&self, documents: &[B]) -> C::Out<Value> {
self.c.run(
Req::post("/chat/knowledge/documents/batch").json(&json!({ "documents": documents })),
)
}
pub fn sync<B: Serialize>(&self, collection: &str, documents: &[B]) -> C::Out<Value> {
self.c.run(
Req::post(format!(
"/chat/knowledge/collections/{}/sync",
seg(collection)
))
.json(&json!({ "documents": documents })),
)
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c
.run(Req::get(format!("/chat/knowledge/documents/{}", seg(id))))
}
pub fn list(&self, params: &KnowledgeListParams) -> C::Out<Value> {
self.c
.run(Req::get("/chat/knowledge/documents").query(params))
}
pub fn remove(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::delete(format!(
"/chat/knowledge/documents/{}",
seg(id)
)))
}
pub fn search(&self, q: &str, locale: Option<&str>, limit: Option<u32>) -> C::Out<Value> {
self.c.run(
Req::get("/chat/knowledge/search")
.query(&json!({ "q": q, "locale": locale, "limit": limit })),
)
}
}
params!(
SubscriptionListParams { external_user_id: String, platform: Platform, status: Vec<String>, limit: u32 }
);
namespace!(
Subscriptions
);
impl<C: Executor> Subscriptions<C> {
pub fn upsert<B: Serialize + ?Sized>(
&self,
platform: Platform,
original_id: &str,
payload: &B,
) -> C::Out<Value> {
self.c.run(
Req::put(format!(
"/chat/subscriptions/{}/{}",
platform.as_str(),
seg(original_id)
))
.json(payload),
)
}
pub fn list(&self, params: &SubscriptionListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/subscriptions").query(params))
}
pub fn for_customer(&self, customer_id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!(
"/chat/customers/{}/subscriptions",
seg(customer_id)
)))
}
pub fn purchase_token(&self, site_id: &str, user_id: &str) -> C::Out<Value> {
self.c.run(
Req::get(format!("/chat/sites/{}/purchase-token", seg(site_id)))
.query(&json!({ "user_id": user_id })),
)
}
}
params!(
PurchaseListParams { external_user_id: String, platform: Platform, limit: u32 }
);
namespace!(
Purchases
);
impl<C: Executor> Purchases<C> {
pub fn upsert<B: Serialize + ?Sized>(
&self,
platform: Platform,
transaction_id: &str,
payload: &B,
) -> C::Out<Value> {
self.c.run(
Req::put(format!(
"/chat/purchases/{}/{}",
platform.as_str(),
seg(transaction_id)
))
.json(payload),
)
}
pub fn list(&self, params: &PurchaseListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/purchases").query(params))
}
pub fn for_customer(&self, customer_id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!(
"/chat/customers/{}/purchases",
seg(customer_id)
)))
}
}
params!(
CustomerListParams { q: String, stage: String, label: String, owner_id: String, channel: String, limit: u32, after: String }
);
namespace!(
Customers
);
impl<C: Executor> Customers<C> {
pub fn list(&self, params: &CustomerListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/customers").query(params))
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!("/chat/customers/{}", seg(id))))
}
pub fn update<B: Serialize + ?Sized>(&self, id: &str, payload: &B) -> C::Out<Value> {
self.c
.run(Req::patch(format!("/chat/customers/{}", seg(id))).json(payload))
}
pub fn conversations(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!(
"/chat/customers/{}/conversations",
seg(id)
)))
}
pub fn export_csv(&self, params: &CustomerListParams) -> C::Out<String> {
self.c
.run_text(Req::get("/chat/customers/export.csv").query(params))
}
}
params!(
ConversationListParams { status: Vec<String>, unanswered: bool, limit: u32, after: String }
);
params!(
MessageListParams { after_seq: u64, limit: u32, include_private: bool }
);
namespace!(
Conversations
);
impl<C: Executor> Conversations<C> {
pub fn list(&self, params: &ConversationListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/conversations").query(params))
}
pub fn list_with<Q: Serialize + ?Sized>(&self, filters: &Q) -> C::Out<Value> {
self.c.run(Req::get("/chat/conversations").query(filters))
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c
.run(Req::get(format!("/chat/conversations/{}", seg(id))))
}
pub fn update<B: Serialize + ?Sized>(&self, id: &str, payload: &B) -> C::Out<Value> {
self.c
.run(Req::patch(format!("/chat/conversations/{}", seg(id))).json(payload))
}
pub fn messages(&self, id: &str, params: &MessageListParams) -> C::Out<Value> {
self.c
.run(Req::get(format!("/chat/conversations/{}/messages", seg(id))).query(params))
}
pub fn send<B: Serialize + ?Sized>(
&self,
id: &str,
message: &B,
idempotency_key: Option<&str>,
) -> C::Out<Value> {
self.c.run(
Req::post(format!("/chat/conversations/{}/messages", seg(id)))
.json(message)
.idempotency(idempotency_key),
)
}
pub fn send_products(
&self,
id: &str,
product_ids: &[&str],
intro: Option<&str>,
) -> C::Out<Value> {
let mut body = json!({ "product_ids": product_ids });
if let Some(intro) = intro.filter(|s| !s.is_empty()) {
body["intro"] = json!(intro);
}
self.c
.run(Req::post(format!("/chat/conversations/{}/products", seg(id))).json(&body))
}
}
params!(
ProductListParams { q: String, category: String, active: bool, limit: u32, after: String }
);
namespace!(
Products
);
impl<C: Executor> Products<C> {
pub fn list(&self, params: &ProductListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/products").query(params))
}
pub fn search(&self, q: &str, limit: Option<u32>) -> C::Out<Value> {
self.c
.run(Req::get("/chat/products/search").query(&json!({ "q": q, "limit": limit })))
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!("/chat/products/{}", seg(id))))
}
pub fn create<B: Serialize + ?Sized>(&self, payload: &B) -> C::Out<Value> {
self.c.run(Req::post("/chat/products").json(payload))
}
pub fn update<B: Serialize + ?Sized>(&self, id: &str, payload: &B) -> C::Out<Value> {
self.c
.run(Req::patch(format!("/chat/products/{}", seg(id))).json(payload))
}
pub fn remove(&self, id: &str) -> C::Out<Value> {
self.c
.run(Req::delete(format!("/chat/products/{}", seg(id))))
}
}
params!(
OrderListParams {
status: String,
customer_id: String,
conversation_id: String,
payment_status: String,
q: String,
limit: u32,
after: String,
}
);
namespace!(
Orders
);
impl<C: Executor> Orders<C> {
pub fn list(&self, params: &OrderListParams) -> C::Out<Value> {
self.c.run(Req::get("/chat/orders").query(params))
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!("/chat/orders/{}", seg(id))))
}
pub fn create<B: Serialize + ?Sized>(&self, payload: &B) -> C::Out<Value> {
self.c.run(Req::post("/chat/orders").json(payload))
}
pub fn update<B: Serialize + ?Sized>(&self, id: &str, payload: &B) -> C::Out<Value> {
self.c
.run(Req::patch(format!("/chat/orders/{}", seg(id))).json(payload))
}
pub fn payment_link(
&self,
id: &str,
expires_in: Option<u64>,
send_card: Option<bool>,
) -> C::Out<Value> {
let mut body = serde_json::Map::new();
if let Some(v) = expires_in {
body.insert("expires_in".into(), json!(v));
}
if let Some(v) = send_card {
body.insert("send_card".into(), json!(v));
}
self.c
.run(Req::post(format!("/chat/orders/{}/payment-link", seg(id))).json(&body))
}
}
#[derive(Debug, Clone)]
pub struct Chat<C> {
pub customers: Customers<C>,
pub conversations: Conversations<C>,
pub subscriptions: Subscriptions<C>,
pub purchases: Purchases<C>,
pub products: Products<C>,
pub orders: Orders<C>,
}
impl<C: Executor> Chat<C> {
pub(crate) fn new(c: C) -> Self {
Chat {
customers: Customers::new(c.clone()),
conversations: Conversations::new(c.clone()),
subscriptions: Subscriptions::new(c.clone()),
purchases: Purchases::new(c.clone()),
products: Products::new(c.clone()),
orders: Orders::new(c),
}
}
}
params!(
PaymentListParams { status: String, connection_id: String, limit: u32, after: String }
);
namespace!(
Payments
);
impl<C: Executor> Payments<C> {
pub fn create<B: Serialize + ?Sized>(
&self,
payment: &B,
idempotency_key: Option<&str>,
) -> C::Out<Value> {
self.c.run(
Req::post("/payments")
.json(payment)
.idempotency(idempotency_key),
)
}
pub fn get(&self, id: &str) -> C::Out<Value> {
self.c.run(Req::get(format!("/payments/{}", seg(id))))
}
pub fn list(&self, params: &PaymentListParams) -> C::Out<Value> {
self.c.run(Req::get("/payments").query(params))
}
pub fn cancel(&self, id: &str) -> C::Out<Value> {
self.c
.run(Req::post(format!("/payments/{}/cancel", seg(id))))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Contact<'a> {
Id(&'a str),
Email(&'a str),
}
namespace!(
Events
);
impl<C: Executor> Events<C> {
pub fn send(
&self,
event: &str,
contact: Contact<'_>,
payload: Option<&Value>,
) -> C::Out<Value> {
let mut body = json!({ "event": event });
match contact {
Contact::Id(id) => body["contact_id"] = json!(id),
Contact::Email(email) => body["email"] = json!(email),
}
if let Some(p) = payload {
body["payload"] = p.clone();
}
self.c.run(Req::post("/events/send").json(&body))
}
}