beisen/
impl_organization.rs

1use async_trait::async_trait;
2use serde_json::json;
3use tracing::debug;
4
5use super::{
6    dto::{SearchTimeWindowOption, REQUEST_ORGANIZATION_COLUMNS},
7    model::response::BeisenResponse,
8    Client, Organization, Organizationer, Result, BASE_URL,
9};
10
11#[async_trait]
12impl Organizationer for Client {
13    async fn search_organization_by_ids(&self, oids: Vec<u32>) -> Result<Vec<Organization>> {
14        let url = format!(
15            "{}/tenantbase/v1/{}/organization/ids/search",
16            BASE_URL, self.tenant_id
17        );
18
19        let post_body = json!({
20            "Ids":   oids,
21            "Columns": REQUEST_ORGANIZATION_COLUMNS,
22        });
23
24        let resp = match self.request(None, &url, post_body).await {
25            Ok(t) => t,
26            Err(err) => {
27                if err.is_authentication_error() {
28                    return self.search_organization_by_ids(oids).await;
29                }
30                return Err(err);
31            }
32        };
33
34        Ok(resp.json().await?)
35    }
36
37    async fn search_organization_with_timewindow(
38        &self,
39        opt: &SearchTimeWindowOption,
40    ) -> Result<Vec<Organization>> {
41        let url = format!(
42            "{}/tenantbase/v1/{}/organization/timewindow/search",
43            BASE_URL, self.tenant_id
44        );
45
46        let post_body = serde_json::to_value(opt)?;
47
48        let resp = match self.request(None, &url, post_body).await {
49            Ok(t) => t,
50            Err(err) => {
51                if err.is_authentication_error() {
52                    return self.search_organization_with_timewindow(opt).await;
53                }
54                return Err(err);
55            }
56        };
57
58        let mut items = vec![];
59        // let resp: serde_json::Value = resp.json().await?;
60        // tracing::debug!("{}", resp.to_string());
61        let resp: BeisenResponse<Vec<Organization>, u32> = resp.json().await?;
62        if let Some(mut data) = resp.data {
63            items.append(&mut data);
64        }
65        // 如果当前加载的数据还未达到总数, 则说明还有分页数据
66        debug!("total: {}, current: {}", resp.total, opt.total());
67
68        if opt.total() < resp.total {
69            let next_page_index = opt.page_index() + 1;
70            debug!("next_page_index: {}", next_page_index);
71
72            let next_opt = opt.clone_with_page_index(next_page_index);
73            let mut datas = self.search_organization_with_timewindow(&next_opt).await?;
74            items.append(&mut datas);
75        }
76        Ok(items)
77    }
78}