hatang 0.3.0

Official Rust client for the Ha Tang (Hạ Tầng) API: transactional email, live chat and support CRM, VietQR payments, AI chatbot knowledge and webhook verification. Async (Tokio) and blocking.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! 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()
        }
    }
}

// ---- revenue ----

/// What counts as revenue. `Bank`: every transfer into the business's linked bank accounts, except those it marked
/// as not revenue (refunds received, transfers between its own accounts). `Payments`: Ha Tang VietQR payments that
/// were paid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RevenueBasis {
    Bank,
    #[default]
    Payments,
}

/// Money received: one bank transfer in, or one paid VietQR payment.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenueEvent {
    /// Stable: the transaction id (bank) or payment id (payments). Deduplicate by it.
    pub id: String,
    pub occurred_at: String,
    /// Whole đồng (VND has no minor unit).
    pub amount: i64,
    pub currency: String,
    pub basis: RevenueBasis,
    /// `bank_transfer` or `vietqr_payment`.
    pub source: String,
    #[serde(default)]
    pub description: String,
    pub reference: Option<String>,
    pub counterparty: Option<Counterparty>,
    pub payment_id: Option<String>,
    pub transaction_id: Option<String>,
    pub connection_id: String,
}

/// Who sent a transfer, as the bank reported it.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Counterparty {
    pub name: Option<String>,
    pub account: Option<String>,
    pub bank: Option<String>,
}

/// A page of [`RevenueEvent`]s, oldest first.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenuePage {
    pub data: Vec<RevenueEvent>,
    pub has_more: bool,
    pub next_cursor: Option<String>,
}

/// Revenue by day or month.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenueSummary {
    pub basis: RevenueBasis,
    pub currency: String,
    pub interval: String,
    pub tz: String,
    pub from: String,
    pub to: String,
    pub totals: RevenueTotals,
    pub buckets: Vec<RevenueBucket>,
}

/// Totals over fixed windows, independent of `from` / `to`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenueTotals {
    pub all_time: i64,
    /// The ranking figure for sites without subscription MRR.
    pub last_30_days: i64,
    pub previous_30_days: i64,
    /// The oldest money on record: how far back the history goes.
    pub first_at: Option<String>,
}

/// One day or month (its first day, `YYYY-MM-DD`, in the summary's time zone).
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenueBucket {
    pub start: String,
    pub amount: i64,
    pub count: u64,
}

/// Who a key belongs to.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct RevenueAccount {
    pub business: Business,
    pub environment: String,
    pub scopes: Vec<String>,
    /// No write, send or wildcard scope: safe to store on a third-party site.
    pub read_only: bool,
    pub currency: String,
    pub bank_connections: Vec<BankAccountSummary>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Business {
    pub id: String,
    pub name: String,
}

/// A linked bank account, masked.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct BankAccountSummary {
    pub id: String,
    pub bank: String,
    pub account_mask: Option<String>,
    pub account_name: Option<String>,
    pub status: String,
}