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
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::collections::HashSet;

use derive_builder::Builder;

use crate::api::common::{AccessLevel, NameOrId, SortOrder};
use crate::api::endpoint_prelude::*;
use crate::api::ParamValue;

/// Keys subgroup results may be ordered by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupSubgroupsOrderBy {
    /// Order by the user ID.
    Id,
    /// Order by the user display name.
    Name,
    /// Order by the path.
    Path,
}

impl Default for GroupSubgroupsOrderBy {
    fn default() -> Self {
        GroupSubgroupsOrderBy::Name
    }
}

impl GroupSubgroupsOrderBy {
    /// The ordering as a query parameter.
    fn as_str(self) -> &'static str {
        match self {
            GroupSubgroupsOrderBy::Id => "id",
            GroupSubgroupsOrderBy::Name => "name",
            GroupSubgroupsOrderBy::Path => "path",
        }
    }
}

impl ParamValue<'static> for GroupSubgroupsOrderBy {
    fn as_value(self) -> Cow<'static, str> {
        self.as_str().into()
    }
}

/// Query subgroups of a group.
#[derive(Debug, Clone, Builder)]
#[builder(setter(strip_option))]
pub struct GroupSubgroups<'a> {
    /// The group to query for subgroups.
    #[builder(setter(into))]
    group: NameOrId<'a>,

    /// Skip the group IDs passed
    #[builder(setter(name = "_skip_groups"), default, private)]
    skip_groups: HashSet<u64>,

    /// Show all the groups you have access to (defaults to false
    /// for authenticated users, true for admin);
    /// Attributes owned and min_access_level have precedence.
    #[builder(default)]
    all_available: Option<bool>,

    /// Search for subgroup using a query string.
    ///
    /// The search query will be escaped automatically.
    #[builder(setter(into), default)]
    search: Option<Cow<'a, str>>,
    /// Return subgroups ordered by keys.
    #[builder(default)]
    order_by: Option<GroupSubgroupsOrderBy>,
    /// Return subgroups sorted in asc or desc order.
    #[builder(default)]
    sort: Option<SortOrder>,

    /// Include group statistics (admins only).
    #[builder(default)]
    statistics: Option<bool>,
    /// Include custom attributes in response (admins only).
    #[builder(default)]
    with_custom_attributes: Option<bool>,
    /// Limit by subgroups owned by the current user.
    #[builder(default)]
    owned: Option<bool>,
    /// Limit to subgroups where current user has at least this access level.
    #[builder(default)]
    min_access_level: Option<AccessLevel>,
}

impl<'a> GroupSubgroups<'a> {
    /// Create a builder for the endpoint.
    pub fn builder() -> GroupSubgroupsBuilder<'a> {
        GroupSubgroupsBuilder::default()
    }
}

impl<'a> GroupSubgroupsBuilder<'a> {
    /// Filter results by skipping the given group ID.
    pub fn skip_group(&mut self, group_id: u64) -> &mut Self {
        self.skip_groups
            .get_or_insert_with(HashSet::new)
            .insert(group_id);
        self
    }

    /// Filter results by skipping the given group IDs.
    pub fn skip_groups<I>(&mut self, iter: I) -> &mut Self
    where
        I: Iterator<Item = u64>,
    {
        self.skip_groups
            .get_or_insert_with(HashSet::new)
            .extend(iter);
        self
    }
}

impl<'a> Endpoint for GroupSubgroups<'a> {
    fn method(&self) -> Method {
        Method::GET
    }

    fn endpoint(&self) -> Cow<'static, str> {
        format!("groups/{}/subgroups", self.group).into()
    }

    fn parameters(&self) -> QueryParams {
        let mut params = QueryParams::default();

        params
            .push_opt("all_available", self.all_available)
            .push_opt("search", self.search.as_ref())
            .push_opt("order_by", self.order_by)
            .push_opt("sort", self.sort)
            .push_opt("statistics", self.statistics)
            .push_opt("with_custom_attributes", self.with_custom_attributes)
            .push_opt("owned", self.owned)
            .push_opt(
                "min_access_level",
                self.min_access_level.map(AccessLevel::as_u64),
            )
            .extend(
                self.skip_groups
                    .iter()
                    .map(|&value| ("skip_groups[]", value)),
            );

        params
    }
}

impl<'a> Pageable for GroupSubgroups<'a> {}

#[cfg(test)]
mod tests {
    use crate::api::common::{AccessLevel, SortOrder};
    use crate::api::groups::subgroups::{GroupSubgroups, GroupSubgroupsOrderBy};
    use crate::api::{self, Query};
    use crate::test::client::{ExpectedUrl, SingleTestClient};

    #[test]
    fn order_by_default() {
        assert_eq!(
            GroupSubgroupsOrderBy::default(),
            GroupSubgroupsOrderBy::Name
        );
    }

    #[test]
    fn order_by_as_str() {
        let items = &[
            (GroupSubgroupsOrderBy::Id, "id"),
            (GroupSubgroupsOrderBy::Name, "name"),
            (GroupSubgroupsOrderBy::Path, "path"),
        ];

        for (i, s) in items {
            assert_eq!(i.as_str(), *s);
        }
    }

    #[test]
    fn group_is_needed() {
        let err = GroupSubgroups::builder().build().unwrap_err();
        assert_eq!(err, "`group` must be initialized");
    }

    #[test]
    fn group_is_sufficient() {
        GroupSubgroups::builder().group(1).build().unwrap();
    }

    #[test]
    fn endpoint() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_skip_groups() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("skip_groups[]", "42")])
            .add_query_params(&[("skip_groups[]", "1337")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .skip_groups(vec![42, 1337].into_iter())
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_all_available() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("all_available", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .all_available(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_search() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("search", "name")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .search("name")
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_order_by() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("order_by", "id")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .order_by(GroupSubgroupsOrderBy::Id)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_sort() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("sort", "asc")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .sort(SortOrder::Ascending)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_statistics() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("statistics", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .statistics(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_with_custom_attributes() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("with_custom_attributes", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .with_custom_attributes(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_owned() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("owned", "true")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .owned(true)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }

    #[test]
    fn endpoint_min_access_level() {
        let endpoint = ExpectedUrl::builder()
            .endpoint("groups/group%2Fsubgroup/subgroups")
            .add_query_params(&[("min_access_level", "30")])
            .build()
            .unwrap();
        let client = SingleTestClient::new_raw(endpoint, "");

        let endpoint = GroupSubgroups::builder()
            .group("group/subgroup")
            .min_access_level(AccessLevel::Developer)
            .build()
            .unwrap();
        api::ignore(endpoint).query(&client).unwrap();
    }
}