zammad-api 0.2.0

Async, idiomatic Rust client for the Zammad REST API
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
//! Knowledge Base ("FAQ") endpoints.
//!
//! Zammad's Knowledge Base API does not hand back plain records the way the
//! ticket or user endpoints do. Instead it returns an *assets* bundle: a set of
//! id-keyed maps (`KnowledgeBaseAnswer`, `KnowledgeBaseAnswerTranslation`,
//! `KnowledgeBaseAnswerTranslationContent`, `KnowledgeBaseCategory`, ...) that
//! the caller is expected to stitch together. This module hides that stitching
//! and exposes flat [`KbAnswer`] / [`KbSearchHit`] values.
//!
//! Three operations are provided:
//!
//! - [`KnowledgeBaseApi::list`] — every answer with its title and category
//!   (no body).
//! - [`KnowledgeBaseApi::search`] — full-text search, returning highlighted
//!   title/body snippets.
//! - [`KnowledgeBaseApi::get`] — a single answer including its full body.
//!
//! The answer body is not part of the default `init` payload; it is fetched in
//! a second `init` call that names the wanted
//! `answer_translation_content_ids`.

use std::collections::BTreeMap;

use reqwest::Method;
use serde::Deserialize;

use crate::client::Client;
use crate::error::{Error, Result};

const INIT_PATH: &str = "api/v1/knowledge_bases/init";
const SEARCH_PATH: &str = "api/v1/knowledge_bases/search";

/// Publishing state-machine action that makes an answer public.
const PUBLISH_ACTION: &str = "publish";
/// Publishing state-machine action that moves an answer back to a draft.
const UNPUBLISH_ACTION: &str = "unpublish";

/// Knowledge Base (FAQ) endpoints.
#[derive(Debug)]
pub struct KnowledgeBaseApi<'a> {
    client: &'a Client,
}

impl<'a> KnowledgeBaseApi<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// List every answer known to the instance, flattened to
    /// [`KbAnswer`]s (title + category, no body).
    ///
    /// `POST /api/v1/knowledge_bases/init`.
    pub async fn list(&self) -> Result<Vec<KbAnswer>> {
        let assets = self.init(&[]).await?;
        let mut answers: Vec<KbAnswer> = assets
            .answers
            .iter()
            .map(|(&id, raw)| assets.to_answer(id, raw, None))
            .collect();
        answers.sort_by_key(|a| a.id);
        Ok(answers)
    }

    /// Fetch a single answer by its numeric id, including its full body.
    ///
    /// Returns [`Error::NotFound`] when no answer with that id exists.
    ///
    /// Issues two `POST /api/v1/knowledge_bases/init` calls: one for the
    /// structure and one that requests the answer's translation content.
    pub async fn get(&self, answer_id: u64) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let raw = assets.answers.get(&answer_id).ok_or(Error::NotFound)?;

        // The body lives on the translation's content record, addressed by
        // `content_id`. Ask a second `init` to include it.
        let content_id = assets.primary_translation(raw).and_then(|t| t.content_id);
        let body = self.body_of(content_id).await?;

        Ok(assets.to_answer(answer_id, raw, Some(body)))
    }

    /// Create a new answer in a category, in the knowledge base's primary
    /// locale.
    ///
    /// When [`NewKbAnswer::published`] is `true` the answer is published in the
    /// same request; otherwise it is left as a draft. The knowledge base and
    /// locale are resolved from the category.
    ///
    /// `POST /api/v1/knowledge_bases/:kb_id/answers`.
    pub async fn create_answer(&self, answer: NewKbAnswer) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let kb_id = assets.kb_of_category(answer.category_id).ok_or_else(|| {
            Error::Config(format!(
                "no knowledge base found for category {}",
                answer.category_id
            ))
        })?;
        let kb_locale_id = assets
            .primary_locale_id(kb_id)
            .ok_or_else(|| Error::Config(format!("no locale found for knowledge base {kb_id}")))?;

        let mut body = serde_json::json!({
            "category_id": answer.category_id,
            "translations": [{
                "title": answer.title,
                "kb_locale_id": kb_locale_id,
                "content": { "body": answer.body },
            }],
        });
        if answer.published {
            body["additional_action"] = serde_json::json!(PUBLISH_ACTION);
        }

        let path = format!("api/v1/knowledge_bases/{kb_id}/answers");
        let req = self.client.request(Method::POST, &path).json(&body);
        let created: AnswerWriteResponse = self.client.send_json(req).await?;
        self.get(created.id).await
    }

    /// Update an existing answer's title, body, and/or published state. Fields
    /// left as `None` in the [`KbAnswerPatch`] are preserved.
    ///
    /// Returns [`Error::NotFound`] when no answer with that id exists.
    ///
    /// `PATCH /api/v1/knowledge_bases/:kb_id/answers/:id`.
    pub async fn update_answer(&self, answer_id: u64, patch: KbAnswerPatch) -> Result<KbAnswer> {
        let assets = self.init(&[]).await?;
        let raw = assets.answers.get(&answer_id).ok_or(Error::NotFound)?;
        let category_id = raw
            .category_id
            .ok_or_else(|| Error::Config("answer has no category".into()))?;
        let kb_id = assets.kb_of_category(category_id).ok_or_else(|| {
            Error::Config(format!(
                "no knowledge base found for category {category_id}"
            ))
        })?;
        let kb_locale_id = assets
            .primary_locale_id(kb_id)
            .ok_or_else(|| Error::Config(format!("no locale found for knowledge base {kb_id}")))?;

        let translation_id = *raw
            .translation_ids
            .first()
            .ok_or_else(|| Error::Config("answer has no translation to update".into()))?;
        let translation = assets
            .translations
            .get(&translation_id)
            .ok_or_else(|| Error::Config("answer translation missing from payload".into()))?;
        let content_id = translation.content_id;

        // Merge: keep the current title/body for whichever field the caller
        // left unset, so a partial update never blanks the other.
        let title = match patch.title {
            Some(t) => t,
            None => translation.title.clone().unwrap_or_default(),
        };
        let body = match patch.body {
            Some(b) => b,
            None => self.body_of(content_id).await?.unwrap_or_default(),
        };

        let mut content = serde_json::json!({ "body": body });
        if let Some(cid) = content_id {
            content["id"] = serde_json::json!(cid);
        }
        let mut payload = serde_json::json!({
            "category_id": category_id,
            "translations": [{
                "id": translation_id,
                "kb_locale_id": kb_locale_id,
                "title": title,
                "content": content,
            }],
        });
        if let Some(published) = patch.published {
            let action = if published {
                PUBLISH_ACTION
            } else {
                UNPUBLISH_ACTION
            };
            payload["additional_action"] = serde_json::json!(action);
        }

        let path = format!("api/v1/knowledge_bases/{kb_id}/answers/{answer_id}");
        let req = self.client.request(Method::PATCH, &path).json(&payload);
        let _: AnswerWriteResponse = self.client.send_json(req).await?;
        self.get(answer_id).await
    }

    /// Fetch the body for a translation content id, if any.
    async fn body_of(&self, content_id: Option<u64>) -> Result<Option<String>> {
        let Some(cid) = content_id else {
            return Ok(None);
        };
        let assets = self.init(&[cid]).await?;
        Ok(assets.contents.get(&cid).and_then(|c| c.body.clone()))
    }

    /// Full-text search across the Knowledge Base.
    ///
    /// Returns a builder; call [`SearchKnowledgeBase::send`] to run it.
    pub fn search(&self, query: impl Into<String>) -> SearchKnowledgeBase<'a> {
        SearchKnowledgeBase {
            client: self.client,
            query: query.into(),
            flavor: "public".to_string(),
            per_page: 50,
        }
    }

    /// `POST /api/v1/knowledge_bases/init`, optionally requesting the body
    /// content for the given answer-translation content ids.
    async fn init(&self, content_ids: &[u64]) -> Result<KbAssets> {
        let body = serde_json::json!({ "answer_translation_content_ids": content_ids });
        let req = self.client.request(Method::POST, INIT_PATH).json(&body);
        self.client.send_json(req).await
    }
}

/// Builder for `POST /api/v1/knowledge_bases/search`.
#[derive(Debug)]
pub struct SearchKnowledgeBase<'a> {
    client: &'a Client,
    query: String,
    flavor: String,
    per_page: u32,
}

impl SearchKnowledgeBase<'_> {
    /// Result flavor. `"public"` (the default) searches published,
    /// publicly-visible answers; `"agent"` also covers answers only visible
    /// to signed-in agents.
    pub fn flavor(mut self, flavor: impl Into<String>) -> Self {
        self.flavor = flavor.into();
        self
    }

    /// Maximum number of hits to return (default 50).
    pub fn per_page(mut self, n: u32) -> Self {
        self.per_page = n;
        self
    }

    /// Run the search.
    pub async fn send(self) -> Result<Vec<KbSearchHit>> {
        let body = serde_json::json!({
            "query": self.query,
            "flavor": self.flavor,
            "per_page": self.per_page,
            "include_subtitle": true,
        });
        let req = self.client.request(Method::POST, SEARCH_PATH).json(&body);
        let resp: SearchResponse = self.client.send_json(req).await?;

        // `details` carries the presentable fields (title, body snippet,
        // category subtitle, url); `id` there is the answer *translation* id.
        // Resolve each to its stable answer id via `init` so callers can hand
        // the id straight to [`KnowledgeBaseApi::get`].
        let hits = resp.details;
        if hits.is_empty() {
            return Ok(Vec::new());
        }

        let assets = KnowledgeBaseApi::new(self.client).init(&[]).await?;
        Ok(hits
            .into_iter()
            .map(|d| KbSearchHit {
                answer_id: assets.translations.get(&d.id).map(|t| t.answer_id),
                translation_id: d.id,
                title: strip_highlight(d.title),
                category: d.subtitle,
                snippet: strip_highlight(d.body),
                url: d.url,
            })
            .collect())
    }
}

/// A single Knowledge Base answer, flattened from Zammad's assets bundle.
#[derive(Debug, Clone)]
pub struct KbAnswer {
    /// Numeric answer id (stable; accepted by [`KnowledgeBaseApi::get`]).
    pub id: u64,
    /// Answer title, in the Knowledge Base's primary locale.
    pub title: Option<String>,
    /// Id of the category the answer belongs to.
    pub category_id: Option<u64>,
    /// Title of that category, in the primary locale.
    pub category: Option<String>,
    /// Whether the answer has been published.
    pub published: bool,
    /// The answer body (HTML). Only populated by [`KnowledgeBaseApi::get`];
    /// always `None` for [`KnowledgeBaseApi::list`].
    pub body: Option<String>,
}

/// Fields for creating a Knowledge Base answer via
/// [`KnowledgeBaseApi::create_answer`].
#[derive(Debug, Clone)]
pub struct NewKbAnswer {
    /// Category the answer belongs to. The knowledge base and locale are
    /// resolved from it.
    pub category_id: u64,
    /// Answer title.
    pub title: String,
    /// Answer body (HTML or plain text).
    pub body: String,
    /// Publish the answer immediately (`true`) or leave it a draft (`false`).
    pub published: bool,
}

/// A partial update for [`KnowledgeBaseApi::update_answer`]. Every field is
/// optional; `None` leaves the current value untouched.
#[derive(Debug, Clone, Default)]
pub struct KbAnswerPatch {
    /// New title.
    pub title: Option<String>,
    /// New body (HTML or plain text).
    pub body: Option<String>,
    /// `Some(true)` publishes, `Some(false)` reverts to a draft, `None` leaves
    /// the published state unchanged.
    pub published: Option<bool>,
}

/// A single full-text search hit.
#[derive(Debug, Clone)]
pub struct KbSearchHit {
    /// Stable answer id, resolved from the matched translation. `None` only if
    /// the translation could not be found in the structure payload.
    pub answer_id: Option<u64>,
    /// Id of the answer *translation* that matched.
    pub translation_id: u64,
    /// Answer title (search highlight markers stripped).
    pub title: Option<String>,
    /// Category the answer sits under.
    pub category: Option<String>,
    /// A snippet of the body around the match (highlight markers stripped).
    pub snippet: Option<String>,
    /// Relative help-center URL of the answer.
    pub url: Option<String>,
}

// --- wire types -------------------------------------------------------------

/// The `init` assets bundle, with only the maps this module joins on.
#[derive(Debug, Default, Deserialize)]
struct KbAssets {
    #[serde(rename = "KnowledgeBaseAnswer", default)]
    answers: BTreeMap<u64, RawAnswer>,
    #[serde(rename = "KnowledgeBaseAnswerTranslation", default)]
    translations: BTreeMap<u64, RawTranslation>,
    #[serde(rename = "KnowledgeBaseAnswerTranslationContent", default)]
    contents: BTreeMap<u64, RawContent>,
    #[serde(rename = "KnowledgeBaseCategory", default)]
    categories: BTreeMap<u64, RawCategory>,
    #[serde(rename = "KnowledgeBaseCategoryTranslation", default)]
    category_translations: BTreeMap<u64, RawCategoryTranslation>,
    #[serde(rename = "KnowledgeBaseLocale", default)]
    locales: BTreeMap<u64, RawLocale>,
}

impl KbAssets {
    /// The primary-locale translation for an answer (the first listed).
    fn primary_translation(&self, raw: &RawAnswer) -> Option<&RawTranslation> {
        raw.translation_ids
            .first()
            .and_then(|tid| self.translations.get(tid))
    }

    /// The knowledge base a category belongs to.
    fn kb_of_category(&self, category_id: u64) -> Option<u64> {
        self.categories
            .get(&category_id)
            .and_then(|c| c.knowledge_base_id)
    }

    /// The primary `kb_locale_id` of a knowledge base (needed to address a
    /// translation on write). Falls back to that KB's first locale.
    fn primary_locale_id(&self, kb_id: u64) -> Option<u64> {
        let mut first = None;
        for (&id, loc) in &self.locales {
            if loc.knowledge_base_id != kb_id {
                continue;
            }
            if loc.primary {
                return Some(id);
            }
            first.get_or_insert(id);
        }
        first
    }

    /// Build a [`KbAnswer`]. `body` is `Some(...)` for a fetched answer (the
    /// inner `Option` being whether a body actually exists), `None` for a
    /// listing where the body was never requested.
    fn to_answer(&self, id: u64, raw: &RawAnswer, body: Option<Option<String>>) -> KbAnswer {
        let title = self.primary_translation(raw).and_then(|t| t.title.clone());
        let category = raw
            .category_id
            .and_then(|cid| self.categories.get(&cid))
            .and_then(|c| c.translation_ids.first())
            .and_then(|ctid| self.category_translations.get(ctid))
            .and_then(|ct| ct.title.clone());
        KbAnswer {
            id,
            title,
            category_id: raw.category_id,
            category,
            published: raw.published_at.is_some(),
            body: body.flatten(),
        }
    }
}

#[derive(Debug, Deserialize)]
struct RawAnswer {
    #[serde(default)]
    category_id: Option<u64>,
    #[serde(default)]
    translation_ids: Vec<u64>,
    #[serde(default)]
    published_at: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawTranslation {
    answer_id: u64,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    content_id: Option<u64>,
}

#[derive(Debug, Deserialize)]
struct RawContent {
    #[serde(default)]
    body: Option<String>,
}

#[derive(Debug, Deserialize)]
struct RawCategory {
    #[serde(default)]
    knowledge_base_id: Option<u64>,
    #[serde(default)]
    translation_ids: Vec<u64>,
}

#[derive(Debug, Deserialize)]
struct RawLocale {
    knowledge_base_id: u64,
    #[serde(default)]
    primary: bool,
}

#[derive(Debug, Deserialize)]
struct RawCategoryTranslation {
    #[serde(default)]
    title: Option<String>,
}

/// The `{ id, assets }` envelope returned by answer create/update.
#[derive(Debug, Deserialize)]
struct AnswerWriteResponse {
    id: u64,
}

#[derive(Debug, Deserialize)]
struct SearchResponse {
    #[serde(default)]
    details: Vec<SearchDetail>,
}

#[derive(Debug, Deserialize)]
struct SearchDetail {
    id: u64,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    body: Option<String>,
    #[serde(default)]
    subtitle: Option<String>,
    #[serde(default)]
    url: Option<String>,
}

/// Drop the `<em>…</em>` markers Zammad wraps around matched terms in search
/// highlights, leaving plain text.
fn strip_highlight(s: Option<String>) -> Option<String> {
    s.map(|s| s.replace("<em>", "").replace("</em>", ""))
}