hatang 0.1.0

Official Rust SDK for Ha Tang (Hạ Tầng): support CRM and live chat, plans and purchases, the AI assistant's knowledge, email, VietQR payments and webhooks.
Documentation
//! Typed request bodies and query parameters, matching the REST API and the other SDKs.
//!
//! Every body parameter of the client takes `impl Serialize`: these structs, or `serde_json::json!({...})` for
//! anything they do not cover. Fields left `None` are not sent. Responses are `serde_json::Value`, as the API sends
//! them.

use std::collections::BTreeMap;

use base64::Engine as _;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Where a plan or purchase was bought.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Platform {
    Web,
    Ios,
    Android,
}

impl Platform {
    pub fn as_str(self) -> &'static str {
        match self {
            Platform::Web => "web",
            Platform::Ios => "ios",
            Platform::Android => "android",
        }
    }
}

/// What a create call answers: the new object's `id`, with any other fields the API sends in `extra`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Created {
    pub id: String,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

// ---- email ----

/// A file attached to an email. Build it from bytes with [`Attachment::new`] (base64-encoded for you).
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Attachment {
    pub filename: String,
    /// The file, base64-encoded.
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// For inline images referenced as `cid:` in the HTML.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_id: Option<String>,
}

impl Attachment {
    /// An attachment from the file's bytes.
    pub fn new(filename: impl Into<String>, bytes: impl AsRef<[u8]>) -> Self {
        Attachment {
            filename: filename.into(),
            content: base64::engine::general_purpose::STANDARD.encode(bytes),
            ..Default::default()
        }
    }

    /// Sets the MIME type (`application/pdf`…).
    pub fn content_type(mut self, value: impl Into<String>) -> Self {
        self.content_type = Some(value.into());
        self
    }
}

/// A tag on an email, echoed back in webhooks.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Tag {
    pub name: String,
    pub value: String,
}

/// A saved template and the values for its variables.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct EmailTemplate {
    pub id: String,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub variables: BTreeMap<String, Value>,
}

/// An email to send. `to` is required; `from` and `subject` too unless a `template` sets them.
///
/// ```
/// let email = hatang::SendEmail::new("Mộc Hương <hello@mochuong.vn>", ["chi.ha@example.com"], "Đơn DH000010")
///     .html("<p>Đơn của chị đã giao cho bên vận chuyển.</p>");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct SendEmail {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    pub to: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<EmailTemplate>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub cc: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub bcc: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub reply_to: Vec<String>,
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub headers: BTreeMap<String, String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<Tag>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<Attachment>,
    /// ISO 8601 time, or natural language such as `in 1 hour`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic_id: Option<String>,
}

impl SendEmail {
    pub fn new<I, S>(from: impl Into<String>, to: I, subject: impl Into<String>) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        SendEmail {
            from: Some(from.into()),
            to: to.into_iter().map(Into::into).collect(),
            subject: Some(subject.into()),
            ..Default::default()
        }
    }
    pub fn html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }
    pub fn attach(mut self, attachment: Attachment) -> Self {
        self.attachments.push(attachment);
        self
    }
    pub fn tag(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.push(Tag {
            name: name.into(),
            value: value.into(),
        });
        self
    }
    pub fn scheduled_at(mut self, when: impl Into<String>) -> Self {
        self.scheduled_at = Some(when.into());
        self
    }
}

/// Cursor paging for list calls: `limit`, then `after` (or `before`) an id from the previous page.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ListParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
}

// ---- knowledge ----

/// A document the AI assistant answers from. `title` and `content` (Markdown, up to 200,000 characters) are
/// required.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct KnowledgeDocument {
    pub title: String,
    pub content: String,
    /// The page the document lives at, cited in answers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Its language, such as `vi` or `en`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// A set you can sync as a whole (`knowledge.sync`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection: Option<String>,
    /// Your id for it, in `knowledge.batch` and `knowledge.sync`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_id: Option<String>,
}

impl KnowledgeDocument {
    pub fn new(title: impl Into<String>, content: impl Into<String>) -> Self {
        KnowledgeDocument {
            title: title.into(),
            content: content.into(),
            ..Default::default()
        }
    }
}

// ---- plans and purchases ----

/// A plan your backend knows about. `status` is required (`trial`, `active`, `grace`, `on_hold`, `paused`,
/// `canceled`, `expired`, `refunded`, `revoked`).
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct SubscriptionUpsert {
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub store_product_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_plan_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    /// The catalog product's SKU: how a plan sold on your own site finds its product.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sku: Option<String>,
    /// The user id you pass to `identify` in the chat: links the plan to the customer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_renew: Option<bool>,
    /// `production` or `sandbox`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_period_end: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub canceled_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    /// What happened, for the customer's timeline (`renewed`, `canceled`…).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_at: Option<String>,
}

/// A one-time purchase (credit pack, unlock, course). `store_product_id` is required: the store's product id, or
/// on the web your own code for what was sold.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct PurchaseUpsert {
    pub store_product_id: String,
    /// `consumable`, `non_consumable` or `non_renewing`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// `purchased` or `refunded`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sku: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purchased_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refunded_at: Option<String>,
}

// ---- chat ----

/// A reply as an agent. `content` is required; `visibility: "private"` is an internal note the visitor never sees.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ChatMessage {
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<String>,
    /// Ids of files uploaded before.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

impl ChatMessage {
    pub fn new(content: impl Into<String>) -> Self {
        ChatMessage {
            content: content.into(),
            ..Default::default()
        }
    }
    /// An internal note instead of a reply.
    pub fn private(mut self) -> Self {
        self.visibility = Some("private".into());
        self
    }
}

// ---- payments ----

/// Who pays, shown on the payment page.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct PaymentCustomer {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone: Option<String>,
}

/// A VietQR payment. `amount` (VND) is required.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct CreatePayment {
    pub amount: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Your own transfer description (your order number): letters and digits, 6 to 20.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_id: Option<String>,
    /// Seconds until the QR expires.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_in: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Your endpoint for this payment's IPN calls; check them with [`crate::verify_ipn`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ipn_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer: Option<PaymentCustomer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

impl CreatePayment {
    pub fn new(amount: u64) -> Self {
        CreatePayment {
            amount,
            ..Default::default()
        }
    }
}