hatang 0.2.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! API namespaces, shared by the async and blocking clients.
//!
//! Each method returns `C::Out<T>`: a future to `.await` with [`crate::Hatang`], the result itself with
//! `blocking::Hatang`. Names follow the other SDKs (`@hatang/sdk`, `hatang` for Python) in snake_case.

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 }
            }
        }
    };
}

/// Query parameters for list calls that take filters beyond paging.
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>,)*
        }
    };
}

// ---- email ----

namespace!(
    /// Transactional email: send, schedule, look up.
    Emails
);

impl<C: Executor> Emails<C> {
    /// Send an email (or schedule it with `scheduled_at`). See [`crate::SendEmail`].
    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))
    }
    /// Move a scheduled email.
    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 })),
        )
    }
    /// Cancel a scheduled email.
    pub fn cancel(&self, id: &str) -> C::Out<Value> {
        self.c.run(Req::post(format!("/emails/{}/cancel", seg(id))))
    }
}

namespace!(
    /// Several emails in one call.
    Batch
);

impl<C: Executor> Batch<C> {
    /// Up to 100 emails in one call.
    pub fn send<B: Serialize>(&self, emails: &[B]) -> C::Out<Value> {
        self.c.run(Req::post("/emails/batch").json(emails))
    }
}

// ---- knowledge ----

params!(
    /// Filters for [`Knowledge::list`].
    KnowledgeListParams { collection: String, tag: String, locale: String, after: String, limit: u32 }
);

namespace!(
    /// The documents the AI assistant answers from, under your own ids.
    Knowledge
);

impl<C: Executor> Knowledge<C> {
    /// Create or replace a document. See [`crate::KnowledgeDocument`].
    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))
    }
    /// Several documents at once; each needs its `external_id`.
    pub fn batch<B: Serialize>(&self, documents: &[B]) -> C::Out<Value> {
        self.c.run(
            Req::post("/chat/knowledge/documents/batch").json(&json!({ "documents": documents })),
        )
    }
    /// The collection then holds exactly these documents; unchanged ones are not re-indexed.
    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)
        )))
    }
    /// What the assistant would find for a question.
    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 })),
        )
    }
}

// ---- chat ----

params!(
    /// Filters for [`Subscriptions::list`]. `status` takes one status or several, comma-separated.
    SubscriptionListParams { external_user_id: String, platform: Platform, status: Vec<String>, limit: u32 }
);

namespace!(
    /// Plans on the web, the App Store and Google Play, on the customer's profile.
    Subscriptions
);

impl<C: Executor> Subscriptions<C> {
    /// Create or update by platform and your / the store's id (Apple originalTransactionId, Play purchase token).
    /// Sending the same state again changes nothing. See [`crate::SubscriptionUpsert`].
    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)
        )))
    }
    /// The app account token, from the API. [`crate::purchase_token`] computes the same value locally.
    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!(
    /// Filters for [`Purchases::list`].
    PurchaseListParams { external_user_id: String, platform: Platform, limit: u32 }
);

namespace!(
    /// One-time purchases: credit packs, unlocks, courses; refunds included.
    Purchases
);

impl<C: Executor> Purchases<C> {
    /// Record or update by platform and your order id (web) or the store's transaction id. See
    /// [`crate::PurchaseUpsert`].
    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!(
    /// Filters for [`Customers::list`] and [`Customers::export_csv`].
    CustomerListParams { q: String, stage: String, label: String, owner_id: String, channel: String, limit: u32, after: String }
);

namespace!(
    /// The people who talk to you, on every channel.
    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))))
    }
    /// Name, email, phone, owner, lead stage, labels and custom `fields`.
    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)
        )))
    }
    /// Everyone matching the filters, as CSV text.
    pub fn export_csv(&self, params: &CustomerListParams) -> C::Out<String> {
        self.c
            .run_text(Req::get("/chat/customers/export.csv").query(params))
    }
}

params!(
    /// Filters for [`Conversations::list`]; [`Conversations::list_with`] takes any other filter.
    ConversationListParams { status: Vec<String>, unanswered: bool, limit: u32, after: String }
);

params!(
    /// Paging for [`Conversations::messages`].
    MessageListParams { after_seq: u64, limit: u32, include_private: bool }
);

namespace!(
    /// Conversations in the inbox and their messages.
    Conversations
);

impl<C: Executor> Conversations<C> {
    pub fn list(&self, params: &ConversationListParams) -> C::Out<Value> {
        self.c.run(Req::get("/chat/conversations").query(params))
    }
    /// Like [`Conversations::list`], with any other filter the API takes (`assignee_id`, `channel`, `tag`…).
    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))))
    }
    /// Assign, tag, resolve, hide.
    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))
    }
    /// Reply as an agent, or add a private note. See [`crate::ChatMessage`].
    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),
        )
    }
    /// A product card (up to 10 products) with an optional intro line.
    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!(
    /// Filters for [`Products::list`].
    ProductListParams { q: String, category: String, active: bool, limit: u32, after: String }
);

namespace!(
    /// Your catalog: what the assistant recommends and orders are made of.
    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))))
    }
    /// `name` is required; `prices` holds the App Store / Google Play prices and store ids.
    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!(
    /// Filters for [`Orders::list`].
    OrderListParams {
        status: String,
        customer_id: String,
        conversation_id: String,
        payment_status: String,
        q: String,
        limit: u32,
        after: String,
    }
);

namespace!(
    /// Orders made in conversations, with VietQR payment links.
    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))))
    }
    /// `items` (`name`, `price`, `quantity`) is required.
    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))
    }
    /// A VietQR payment for the order's total; the card lands in the conversation unless `send_card` is false.
    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))
    }
}

/// Support: customers, conversations, plans and purchases, products, orders.
#[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),
        }
    }
}

// ---- payments ----

params!(
    /// Filters for [`Payments::list`].
    PaymentListParams { status: String, connection_id: String, limit: u32, after: String }
);

namespace!(
    /// VietQR payments, confirmed by your bank's transfer notification.
    Payments
);

impl<C: Executor> Payments<C> {
    /// See [`crate::CreatePayment`].
    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))))
    }
}

// ---- events ----

/// Who an event is about: a contact id or an email.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Contact<'a> {
    Id(&'a str),
    Email(&'a str),
}

namespace!(
    /// Events that trigger automations.
    Events
);

impl<C: Executor> Events<C> {
    /// Trigger automations waiting for this event, for one contact.
    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))
    }
}