zenkit 0.6.3

Zenkit client library in Rust
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
#![allow(missing_docs, clippy::upper_case_acronyms)]
//! This module defines the data types used in the ZenKit Api. Most are specified
//! by [Zenkit API Docs](https://base.zenkit.com/docs/api/overview/introduction),
//! and a few have been added to make the code more Rust-idiomatic.
//!
//! Structs defined here that aren't directly in Zenkit API:
//! - ListInfo - wraps a List with its field definitions, and contains business field getters and setters.
//! - Item - wraps a list Entry, and has getters and setters to simplify access to business fields.
//!   (derefs to Entry)
//! - Various structures whose names have a suffix of 'Request' or 'Response', for api parameters and
//!   responses.
//! - ChangedArray,ChangedValue - describe data changed inside an Activity object
//!
//! All struct, enum and field names follow Rust naming and capitalization convention,
//!   (Pascal case for struct/enum names, snake_case for field names)
//!   Serde rules are used to map to/from the json-defined names on a per-field/per-struct basis
//! All color fields use 'color' (no _hex suffix)
//! Whenever I felt fairly confident that a type could be made more specific, I did so
//!   (String -> UUID, int -> ID, String -> DateTime<Utc>), etc.

use crate::{f32_or_str, Error};
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::{clone::Clone, default::Default, fmt, iter::Iterator, str::FromStr};

// re-export
pub use crate::datetime::{DateTime, Utc};

// re-export from item and list
pub use crate::{
    item::Item,
    list::{
        fset_f, fset_i, fset_id, fset_s, fset_t, fset_vid, fset_vs, fup_f, fup_i, fup_id, fup_s,
        fup_t, fup_vid, fup_vs, FieldSetVal, FieldVal, ListInfo,
    },
};

/// Zenkit-assigned Object ID (positive int)
pub type ID = u64;
/// Zenkit-assigned short object id (string)
pub type ShortId = String; // 7-14 chars, includes at least 1 letter, may include '-'
/// Zenkit-assigned object UUID
pub type UUID = String; // RFC 4122
/// Error code returned from zenkit api calls. See https://base.zenkit.com/docs/api/type/errorcode
pub type ErrorCode = String;

//pub type ListSettings = Value;
//pub type Notification = Value;
/// string-indexed map of json values
pub type JsonMap = serde_json::map::Map<String, Value>;

/// Field is new/UI name for Element
pub type Field = Element;

fn default_bool() -> bool {
    false
}
fn empty_string() -> String {
    String::from("")
}

/// AllId is used when function parameters may accept more than one name for an object. In addition
/// to id or uuid, many functions also accept a String name (e.g., a field name)
#[derive(Debug)]
pub enum AllId {
    #[allow(non_camel_case_types)]
    /// Object ID
    ID(u64),
    /// Object short id
    ShortId(String),
    /// Object uuid
    UUID(String),
    /// Any of the above, as a string
    Any(String),
}

/// Zenkit object with ID and UUID
pub trait ZKObjectID {
    /// Returns the zenkit-assigned ID (positive int)
    fn get_id(&self) -> ID;

    /// Returns the zenkit-assigned uuid
    fn get_uuid(&self) -> &UUID;
}

impl fmt::Display for AllId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tmp: String;
        write!(
            f,
            "{}",
            match self {
                AllId::ID(val) => {
                    tmp = val.to_string();
                    &tmp
                }
                AllId::ShortId(s) => (*s).as_str(),
                AllId::UUID(s) => (*s).as_str(),
                AllId::Any(s) => (*s).as_str(),
            }
        )
    }
}

impl From<ID> for AllId {
    fn from(id: ID) -> AllId {
        AllId::ID(id)
    }
}

impl From<&ID> for AllId {
    fn from(pid: &ID) -> AllId {
        AllId::ID(*pid)
    }
}

impl From<String> for AllId {
    fn from(s: String) -> AllId {
        AllId::Any(s)
    }
}
impl From<&String> for AllId {
    fn from(s: &String) -> AllId {
        AllId::Any(s.clone())
    }
}

impl From<&'_ str> for AllId {
    fn from(s: &str) -> AllId {
        AllId::Any(s.to_string())
    }
}

//impl Into<String> for AllId {
//    fn into(self) -> String {
//       self.to_string()
//    }
//}

/// Sort direction
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum SortDirection {
    /// Ascending
    Asc,
    /// Descending
    Desc,
}

/// Element(field) data type
#[derive(
    strum_macros::Display,
    Serialize_repr,
    Deserialize_repr,
    PartialEq,
    Debug,
    Copy,
    Clone,
    FromPrimitive,
)]
#[repr(u8)]
pub enum ElementCategoryId {
    /// Text field
    Text = 1,
    /// Numeric field (integer or float)
    Number = 2,
    /// URL (Link) field
    #[allow(non_camel_case_types)]
    URL = 3,
    /// Date field
    Date = 4,
    /// Checkbox (boolean) field
    Checkbox = 5,
    /// Choice/Label field
    Categories = 6,
    /// Formula
    Formula = 7,
    /// date created field
    DateCreated = 8,
    /// date updated field
    DateUpdated = 9,
    /// date deprecated field
    DateDeprecated = 10,
    /// user created by field
    UserCreatedBy = 11,
    /// user last updated field
    UserUpdatedBy = 12,
    /// user deprecated by field
    UserDeprecatedBy = 13,
    /// person or list of persons
    Persons = 14,
    /// file field (e.g., attachment)
    Files = 15,
    /// reference(s) to other items
    References = 16,
    /// Hierarchy field (sub-items)
    Hierarchy = 17,
    /// sub-entries (possibly unused?)
    SubEntries = 18,
    /// dependencies (possibly unused?)
    Dependencies = 19,
}

/// for elements of type Category, PredefinedCategory defines the choices
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct PredefinedCategory {
    /// object id
    pub id: ID,
    /// object short id
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    /// object uuid
    pub uuid: UUID,
    /// category name
    pub name: String,
    /// color, in hex
    #[serde(rename = "colorHex")]
    pub color: String,
    /// date created
    pub created_at: DateTime<Utc>,
    /// date updated
    pub updated_at: DateTime<Utc>,
    /// date deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    /// element(field) id
    #[serde(rename = "elementId")]
    pub element_id: ID,
    /// containing list id
    #[serde(rename = "listId")]
    pub list_id: ID,
    //origin_data: Option<Value>, // null
    //origin_provider: Option<Value>,
    //origin_created_at
    //origin_deprecated_at
    //origin_updated_at
    /// list of resource tags
    #[serde(rename = "resourceTags")]
    pub resource_tags: Vec<Value>,
    /// sort order
    #[serde(rename = "sortOrder", deserialize_with = "f32_or_str")]
    pub sort_order: f32,
}

impl ZKObjectID for PredefinedCategory {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Embedded list, if accessible
#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(untagged)]
pub enum ChildList {
    /// Embedded list
    Child(List),
    /// No accessible list
    NoList(NoAccessList),
}

/// Inaccessible lit
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct NoAccessList {
    /// user does not have access to list
    #[serde(rename = "ACCESS_DENIED")]
    pub access_denied: bool,
    /// list is deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    /// list name
    pub name: String,
    /// list uuid
    pub uuid: String,
}

/// definition of type of data held by Element/field
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct ElementData {
    /// for elements of type Category, predefined_categories defines the choices
    #[serde(rename = "predefinedCategories")]
    pub predefined_categories: Option<Vec<PredefinedCategory>>,

    /// true if the field can have multiple values (labels, persons, etc.)
    #[serde(default = "default_bool")]
    pub multiple: bool,

    /// embedded list, for hierarchies
    #[serde(rename = "childList")]
    pub child_list: Option<ChildList>,
    //#[serde(rename = "childListElements")]
    //child_list_elements: Option<Vec<Element>>,
    /// uuid of child list, for hierarchies
    #[serde(rename = "childListUUID")]
    pub child_list_uuid: Option<UUID>,
    /// mirror element
    #[serde(rename = "mirrorElementUUID")]
    pub mirror_element_uuid: Option<UUID>,

    /// catch-all for all other fields
    #[serde(flatten)]
    pub fields: JsonMap,
    /*
    #[serde(rename = "highlightOverdue")]
    pub highlight_overdue: Option<bool>,
    pub list_users: Option<Vec<ID>>,
    pub placeholder: Option<String>,
    #[serde(rename = "allowCreation")]
    pub allow_creation: Option<bool>,
    #[serde(rename = "allowSearch")]
    pub allow_search: Option<bool>,
    */
}

/// Definitions of business data (user-defined) fields
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct BusinessData {
    /// field definitions
    #[serde(flatten)]
    pub fields: JsonMap,
}

/// Metadata about label/choice fields
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct ElementDataCategories {
    #[serde(rename = "allowInlineCreation")]
    pub allow_inline_creation: bool,
    #[serde(default = "default_bool")]
    pub multiple: bool,
    #[serde(rename = "predefinedCategories")]
    pub predefined_categories: Vec<PredefinedCategory>,
}

/// Sort order for filtered query
#[derive(Serialize, Deserialize, Debug)]
pub struct OrderBy {
    /// Column name
    pub column: Option<String>,
    //#[serde(rename = "elementId")]
    //pub element_id: Option<u64>, // element number
    /// Sort direction
    pub direction: SortDirection,
}

/// Parameters for get_list_entries
#[derive(Serialize, Deserialize, Debug)]
pub struct GetEntriesRequest {
    /// filter object to filter the response
    pub filter: Value,
    /// number of entries that will be returned
    pub limit: usize,
    /// number of entries to skip
    pub skip: usize,
    /// whether to include deprecated entries
    #[serde(rename = "allowDeprecated")]
    pub allow_deprecated: bool,
    /// sort order
    #[serde(rename = "orderBy")]
    pub order_by: Vec<OrderBy>,
}

impl Default for GetEntriesRequest {
    fn default() -> Self {
        Self {
            filter: Value::Object(JsonMap::new()),
            limit: 0,
            skip: 0,
            allow_deprecated: false,
            order_by: Vec::new(),
        }
    }
}

/// Parameters for get_entries_for_list_view
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetEntriesViewRequest {
    /// filter-object to filter the response
    pub filter: Value,
    /// optional group_by (for persons and categories)
    pub group_by_element_id: ID,
    /// number of items to return
    pub limit: u64,
    /// starting item number
    pub skip: u64,
    /// Allow deprecated entries to be included in the response.
    /// countData will also count deprecated entries in this case.
    /// An additional property called countDataNonDeprecated{total, filteredTotal} will be added,
    /// that does not count deprecated items.
    pub allow_deprecated: bool,
    /// Divide the entries into two groups, todo and done.
    /// This only works for lists that have the task addon activated,
    /// meaning that list.settings.tasks is set.
    /// Calling the route with this parameter set to true for a list that is not a task list
    /// will result in an error (LIST_HAS_NO_TASK_ELEMENT:C13).
    /// If everything works out, the result will contain countDataPerGroup
    /// for the keys "todo" and "done":
    /// {todo: {total: n, filteredTotal: m}, done: {total: i, filteredTotal: j}}.
    pub task_style: bool,
}

impl Default for GetEntriesViewRequest {
    fn default() -> Self {
        Self {
            filter: Value::Object(JsonMap::new()),
            group_by_element_id: 0,
            limit: 0,
            skip: 0,
            allow_deprecated: false,
            task_style: false,
        }
    }
}

/// filtered view response data
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FilterCountData {
    /// total number of items returned
    pub total: u64,
    /// number of filtered items
    pub filtered_total: u64,
    /// All other response fields go into the catch-all 'fields'
    #[serde(flatten)]
    pub fields: JsonMap,
}

/// Response returned from get_entries_for_list_view
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct GetEntriesViewResponse {
    /// number of filtered items returned
    pub count_data: FilterCountData,
    /// per group counts (todo, done, etc.)
    pub count_data_per_group: Vec<FilterCountData>,
    /// entries returned
    pub list_entries: Vec<Entry>,
}

/// Error details returned from Zenkit
//noinspection SpellCheckingInspection
#[derive(Deserialize, Debug)]
// in api docs this is "StrucdError", but I kept misspelling it so I'm calling it ErrorInfo
pub struct ErrorInfo {
    /// Error name
    pub name: String,
    /// Error code (see errorcode.rs)
    pub code: ErrorCode,
    /// HTTP status code
    #[serde(rename = "statusCode")]
    pub status_code: u16,
    /// Error message
    pub message: String,
    /// Additional description
    pub description: String,
}

/// Error response returned from Zenkit
#[derive(Deserialize, Debug)]
pub struct ErrorResult {
    /// Error detailed info
    pub error: ErrorInfo,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum RoleID {
    ListOwner,
    ListAdmin,
    ListUser,
    CommentOnlyListUser,
    ReadOnlyListUser,
    WorkspaceOwner,
    WorkspaceUser,
    WorkspaceAdmin,
    CommentOnlyWorkspaceUser,
    ReadOnlyWorkspaceUser,
    OrganizationOwner,
    OrganizationUser,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "lowercase")]
pub enum LoginProvider {
    Local,
    Facebook,
    Google,
    Github,
    Slack,
    Trello,
}

#[derive(Serialize, Deserialize, Debug)]
pub enum AccessType {
    Organization,
    Workspace,
    List,
    Project,
}

/// User access type and role
#[derive(Serialize, Deserialize, Debug)]
pub struct Access {
    pub id: Option<ID>,
    #[serde(rename = "shortId")]
    pub short_id: Option<ShortId>,
    pub uuid: Option<UUID>,
    /// scope of access
    #[serde(rename = "accessType")]
    pub access_type: AccessType,
    #[serde(rename = "userId")]
    pub user_id: Option<ID>,
    #[serde(rename = "workspaceId")]
    pub workspace_id: Option<ID>,
    #[serde(rename = "listId")]
    pub list_id: Option<ID>,
    #[serde(rename = "organizationId")]
    pub organization_id: Option<ID>,
    /// Access role
    #[serde(rename = "roleId")]
    pub role_id: RoleID,
    pub created_at: Option<DateTime<Utc>>,
}

#[derive(Serialize, Deserialize, Debug)]
#[allow(non_camel_case_types)]
pub enum DeviceOperatingSystem {
    Android,
    iOS,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum FilterKeys {
    Text,
    NumberFrom,
    NumberTo,
    DateType,
    DateFrom,
    DateTo,
    Checked,
    FilterCategories,
    FilterPersons,
    FilterReference,
    Level,
}

#[derive(Serialize, Deserialize, Debug)]
pub enum ElementCategoryGroup {
    Control,
}

/// Metadata about field data type
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ElementCategory {
    pub id: ElementCategoryId,
    pub short_id: ShortId,
    pub uuid: UUID,
    /// Human-readable name
    pub name: String,
    pub group: ElementCategoryGroup,
    /// Template for human-readable name of an element with this category
    pub display_name: String,
    /// unused
    pub placeholder_schema: String,
    /// unused
    pub container: bool,
    /// unused
    pub listable: bool,
    /// unused
    pub filterable: bool,
    pub filter_keys: Vec<String>,
    /// Entry key by which to sort values of this element category
    pub sort_key: String,
    pub searchable: bool,
    pub is_static: bool,
    pub min_width: String,
    pub width: String,
    pub max_width: String,
    pub is_width_fixed: bool,
    /// Whether elements of this category can be changed through the "Set" bulk action
    pub can_set: bool,
    /// Whether elements of this category can be changed through the "Add" bulk action
    pub can_add: bool,
    /// Whether elements of this category can be changed through the "Remove" bulk action
    pub can_remove: bool,
    /// Whether elements of this category can be changed through the "Replace" bulk action
    pub can_replace: bool,
    /// Definition of the business data of an element with this category. Only some fields are valid per category
    pub business_data_definition: Value,
    /// Defaults for an element's business data fields
    pub business_data_defaults: Value,
    /// Definition of the element data of an element with this category. Only some fields are valid per category
    pub element_data_definition: Value,
    /// Defaults for an element's element data fields
    pub element_data_defaults: Value,
    #[serde(rename = "created_at")]
    /// The timestamp at which this element category was created
    pub created_at: DateTime<Utc>,
}

/// Field definition
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct Element {
    pub id: ID, // The ID
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    pub uuid: UUID,
    pub name: String,
    // documentation says displayName is unused
    //#[serde(rename = "displayName", default = "empty_string")]
    //pub display_name: String, // Unused
    /// undocumented
    pub description: Option<String>,

    /// The business data
    #[serde(rename = "businessData")]
    pub business_data: BusinessData,

    /// The element data { placeholder: "", listUsers:Option<Value> }
    #[serde(rename = "elementData")]
    pub element_data: ElementData,

    // pub blocked: Option<bool>, // Unused
    /// true if this is a list's primary element
    #[serde(rename = "isPrimary")]
    pub is_primary: bool,

    /// true if this element was created through an automatic process, such as an import, rather than user interaction
    #[serde(rename = "isAutoCreated")]
    pub is_auto_created: bool,

    /// The sort order compared to other elements of the same list
    #[serde(rename = "sortOrder", deserialize_with = "f32_or_str")]
    pub sort_order: f32,
    pub visible: bool,
    /// The timestamp at which this element was created
    pub created_at: DateTime<Utc>,
    /// The timestamp at which this element was last updated
    pub updated_at: DateTime<Utc>,
    /// The timestamp at which this element was deprecated. Is null if not deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    #[serde(rename = "elementcategory")]
    /// The element category
    pub element_category: ElementCategoryId,
    /// The ID of the list this element belongs to
    #[serde(rename = "listId")]
    pub list_id: ID,
    /// undocumented
    #[serde(rename = "visibleInPublicList")]
    pub visible_in_public_list: Option<bool>,
}

impl Element {
    /// Returns the element description, or an empty string if none was provided
    pub fn get_description(&self) -> &str {
        match &self.description {
            Some(s) => s.as_str(),
            None => "",
        }
    }

    /// lookup choice id from its name or uuid. Returns Error if there is no match
    pub fn get_choice_id(&self, choice_name: &str) -> Result<ID, Error> {
        if self.element_category == ElementCategoryId::Categories {
            if let Some(categories) = &self.element_data.predefined_categories {
                for c in categories {
                    if c.uuid == choice_name || c.name == choice_name {
                        return Ok(c.id);
                    }
                }
            }
        }
        Err(Error::Other(format!(
            "Invalid choice '{}' for field '{}'",
            choice_name, &self.name
        )))
    }

    /// Returns whether the numeric field is Integer or Decimal.
    /// Returns None if the field is not numeric
    pub fn numeric_type(&self) -> Option<NumericType> {
        if self.element_category == ElementCategoryId::Number {
            if let Some(format_val) = self.element_data.fields.get("format") {
                if let Some(format_obj) = format_val.as_object() {
                    if let Some(name_val) = format_obj.get("name") {
                        return match name_val.as_str() {
                            Some("integer") => Some(NumericType::Integer),
                            Some("decimal") => Some(NumericType::Decimal),
                            _ => None,
                        };
                    }
                }
            }
        }
        None
    }
}

impl ZKObjectID for Element {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Type of numeric field
pub enum NumericType {
    /// Integer (signed)
    Integer,
    /// Decimal - in Rust, interpreted as float
    Decimal,
}

/// Activity filter type
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum ActivityFilter {
    /// All activities (no filter)
    All = 0,
    /// System messages (unused?)
    SystemMessages = 1,
    /// Comments
    Comments = 2,
    /// Deleted
    Deleted = 3,
}

/// Type of activity
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum ActivityType {
    /// Comment
    Comment = 0,
    /// resource was created
    ResourceCreated = 1,
    /// resource was updated
    ResourceUpdated = 2,
    /// resource was deprecated
    ResourceDeprecated = 3,
    /// resource was imported
    ResourceImported = 4,
    /// resource was copied
    ResourceCopied = 5,
    /// resource was restored
    ResourceRestored = 6,
    /// bulk operation in list
    BulkOperationInList = 7,
    /// resource was deleted
    ResourceDeleted = 8,
}

/// Where activity occurred
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum ActivityCreatedIn {
    /// in workspace
    Workspace = 0,
    /// list
    List = 1,
    /// list entry (item)
    ListEntry = 2,
    /// list element (field)
    ListElement = 3,
}

/// Activity type for bulk action
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum ActivityBulkAction {
    /// add value
    Add = 0,
    /// set value
    Set = 1,
    /// remove value
    Remove = 2,
    /// replace value
    Replace = 3,
}

/// Data that changed
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ActivityChangedData {
    ///
    pub bulk_action: ActivityBulkAction,
}

/// Activity report
//noinspection SpellCheckingInspection
#[derive(Deserialize, Debug)]
pub struct Activity {
    /// activity id
    pub id: ID,
    // short id
    //#[serde(rename = "shortId")]
    //pub short_id: ShortId,
    /// activity uuid
    pub uuid: UUID,
    /// Activity type
    #[serde(rename = "type")]
    pub activity_type: ActivityType,
    /// object type
    pub created_in: ActivityCreatedIn,
    /// message - only used if activity type is Comment
    pub message: Option<String>,
    /// whether activity is bulk action
    #[serde(rename = "isBulk")]
    pub is_bulk: bool,
    /// if is_bulk, this field holds number of units affected by bulk action
    pub bulk_rowcount: Option<u64>,
    //#[serde(rename = "isShownInList", default = "default_bool")]
    //pub is_shown_in_list: bool, // unused
    //#[serde(rename = "isShownInListEntry", default = "default_bool")]
    //pub is_shown_in_list_entry: bool, // unused
    //#[serde(rename = "isSystemMessage", default = "default_bool")]
    //pub is_system_message: bool, // unused
    //#[serde(rename = "originData")]
    //pub origin_data: Option<Value>// unused
    /// object describing what changed through this activity.
    #[serde(rename = "changedData")]
    pub changed_data: ElementChange,

    /// element id of changed data
    #[serde(rename = "changedDataElementId")]
    pub changed_data_element_id: Option<ID>,

    /// id of activity's subject, if it is a workspace
    #[serde(rename = "workspaceId")]
    pub workspace_id: Option<ID>,

    /// short id of activity's subject, if it is a workspace
    #[serde(rename = "workspaceShortId")]
    pub workspace_short_id: Option<ShortId>,

    /// uuid of activity's subject, if it is a workspace
    #[serde(rename = "workspaceUUID")]
    pub workspace_uuid: Option<UUID>,

    /// name of activity's subject, if it's a workspace
    #[serde(rename = "workspaceName")]
    pub workspace_name: Option<String>,

    // description of activity's subject, if it is a workspace
    //#[serde(rename = "workspaceDescription")]
    //pub workspace_description: String,
    /// date activity's subject was deprecated, if it is a workspace
    #[serde(rename = "workspaceDeprecated_at")]
    pub workspace_deprecated_at: Option<DateTime<Utc>>,

    ///
    #[serde(rename = "parentUUID")]
    pub parent_uuid: Option<UUID>,

    /// id of activity's subject, if it is a list
    #[serde(rename = "listId")]
    pub list_id: Option<ID>,

    /// short id of activity's subject, if it is a list
    #[serde(rename = "listShortId")]
    pub list_short_id: Option<ShortId>,

    /// uuid of activity's subject, if it is a list
    #[serde(rename = "listUUID")]
    pub list_uuid: Option<UUID>,
    /// name of activity's subject, if it is a list
    #[serde(rename = "listName")]
    pub list_name: Option<String>,

    //#[serde(rename = "listDescription")]
    //pub list_description: Option<String>,
    /// date list deprecated
    #[serde(rename = "listDeprecated_at")]
    pub list_deprecated_at: Option<DateTime<Utc>>,

    /// id of activity's subject, if it is a list entry
    #[serde(rename = "listEntryId")]
    pub list_entry_id: Option<ID>,

    /// uuid of activity's subject, if it is a list entry
    #[serde(rename = "listEntryUUID")]
    pub list_entry_uuid: Option<UUID>,

    //#[serde(rename = "listEntryShortId")]
    //pub list_entry_short_id: ShortId,
    /// name of activity's subject, if it is a list entry
    #[serde(rename = "listEntryName")]
    pub list_entry_name: Option<String>,
    /// description of activity's subject, if it is a list entry
    #[serde(rename = "listEntryDescription")]
    pub list_entry_description: Option<String>,
    /// date at which activity's subject was deprecated, if it is a list entry
    #[serde(rename = "listEntryDeprecated_at")]
    pub list_entry_deprecated_at: Option<DateTime<Utc>>,

    /// Name of field updated. Can be None if activity is a Comment
    #[serde(rename = "elementName")]
    pub element_name: Option<String>,

    //#[serde(rename = "elementData")]
    //pub element_data: Element,
    /// date activity created
    pub created_at: DateTime<Utc>,
    /// date activity updated
    pub updated_at: DateTime<Utc>,
    /// date activity deprecated
    pub deprecated_at: Option<DateTime<Utc>>,

    /// user id this actiity belongs to
    #[serde(rename = "userId")]
    pub user_id: ID,
    /// display name of activity's subject, if it is a user
    #[serde(rename = "userDisplayname")] // docs incorrectly calls it 'userDisplayName'
    pub user_display_name: String,
    /// full name of activity's subject, if it is a user
    #[serde(rename = "userFullname")]
    pub user_full_name: String,
    /// username of activity's subject, if it is a user
    #[serde(rename = "userUsername")]
    pub user_username: String,
    /// user initials of the activity's subject, if it is a user
    #[serde(rename = "userInitials")]
    pub user_initials: String,
    /// user image preference setting of the activity's subject, if it is a user
    #[serde(rename = "userIsImagePreferred")]
    pub user_is_image_preferred: bool,
    //#[serde(rename = "userImageLink")]
    //pub user_image_link: Option<bool>,
}

impl ZKObjectID for Activity {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Original and new value
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ChangedValue<T> {
    /// value before change
    pub value_from: Option<T>,
    /// value after change
    pub value_to: Option<T>,
}

/// Selection of changed data
pub enum FromTo {
    /// Value before change
    From,
    /// Value after change
    To,
}

impl<T> ChangedValue<T> {
    fn get(&self, ft: FromTo) -> &Option<T> {
        match ft {
            FromTo::From => &self.value_from,
            FromTo::To => &self.value_to,
        }
    }
}

/// Set of changed values
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ChangedArray<T> {
    /// Values before change
    pub value_from: Vec<T>,
    /// values after change
    pub value_to: Vec<T>,
    /// values before change, in string representation
    pub value_from_as_strings: Vec<String>,
    /// values after change, in string representation
    pub value_to_as_strings: Vec<String>,
}

impl<T> ChangedArray<T> {
    fn get(&self, ft: FromTo) -> &Vec<T> {
        match ft {
            FromTo::From => &self.value_from,
            FromTo::To => &self.value_to,
        }
    }
    fn as_strings(&self, ft: FromTo) -> &Vec<String> {
        match ft {
            FromTo::From => &self.value_from_as_strings,
            FromTo::To => &self.value_to_as_strings,
        }
    }
}

/// Value of date from or to
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DateValue {
    pub date: Option<String>,
    pub end_date: Option<String>,
    pub has_time: bool,
    pub duration: Option<String>, // ex: "4 day"
}

/// ChangedData, within an Activity, represents the previous and new data values.
/// Not all field types have been implemented as structs; the other field types
/// have change data as a (serde_json) Value.
///
/// This data will be most applicable if the activity_type is 2 (ResourceUpdated).
/// For example, if activity_type is 0 (Comment), ChangedData is Other(Null).
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum ChangedData {
    /// change to text data
    Text(ChangedValue<String>),
    /// change to numeric data
    Number(ChangedValue<f64>),
    /// change to date field
    Date(ChangedValue<DateValue>),
    /// change to label field
    Categories(ChangedArray<ID>),
    /// change to person(s)
    Persons(ChangedArray<ID>),
    /// change to reference(s)
    References(ChangedArray<UUID>),
    /// change not covered by any of the other types
    Other(Value),
}

fn opt_to_string<T: ToString>(v: &Option<T>) -> String {
    match v {
        Some(x) => x.to_string(),
        None => "".to_string(),
    }
}

impl ChangedData {
    /// Generate printable string value for from (previous) or to (new) value
    pub fn val_to_string(&self, ft: FromTo) -> String {
        use crate::join;
        match self {
            ChangedData::Text(txt_val) => opt_to_string(txt_val.get(ft)),
            ChangedData::Number(num_val) => opt_to_string(num_val.get(ft)),
            ChangedData::Date(date_val) => match date_val.get(ft) {
                Some(DateValue {
                    date: Some(ref date),
                    end_date: _,
                    has_time: _,
                    duration: _,
                }) => date.clone(),
                Some(DateValue {
                    date: None,
                    end_date: _,
                    has_time: _,
                    duration: _,
                }) => "".to_string(),
                None => "".to_string(),
            },
            ChangedData::Categories(arr) => join(",", arr.as_strings(ft)),
            ChangedData::Persons(arr) => join(",", arr.as_strings(ft)),
            ChangedData::References(arr) => join(",", arr.get(ft)),
            ChangedData::Other(_) => "<value>".to_string(),
        }
    }
}

/// change of object field
#[derive(Debug)]
pub struct ElementChange {
    /// field type
    pub category_id: Option<ElementCategoryId>,
    /// data of changed field
    pub data: ChangedData,
}

///
#[derive(Serialize, Deserialize, Debug)]
pub struct NewActivityElement {
    /// element name
    pub name: String,
    /// field type
    #[serde(rename = "elementCategory")]
    pub element_category: ElementCategoryId,
}

/// new comment
#[derive(Serialize, Deserialize, Debug)]
pub struct NewComment {
    /// comment text
    pub message: String,
}

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum BackgroundRole {
    UserDefault = 0,
}

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum BackgroundType {
    AdminColor = 0,
    AdminImage = 1,
    AdminTexture = 2,
    UserImage = 3,
    WorkspaceImage = 4,
    ListImage = 5,
    AdminThemes = 6,
}

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum BackgroundTheme {
    Dark = 0,
    Light = 1,
    Tron = 2,
    DarkTransparent = 3,
    LightTransparent = 4,
    Matrix = 5,
    IronMan = 6,
}

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum BackgroundStyle {
    Cover = 0,
    Tile = 1,
}

/// Background theme and style
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Background {
    pub id: ID,
    pub short_id: ShortId,
    pub uuid: UUID,
    pub role: BackgroundRole,
    pub r#type: BackgroundType,
    /// id of background target. target can be a user, list, or a workspace
    pub target_id: ID,
    /// file associated with this background
    pub file_id: ShortId,
    /// background color, in hex
    #[serde(rename = "color_hex")]
    pub color: String,
    pub theme: BackgroundTheme,
    pub style: BackgroundStyle,
    pub description: String,
    /// reference link
    pub link: String,
    /// shortId of preview image file
    pub preview_file_short_id: ShortId,
}

impl ZKObjectID for Background {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// item in a checklist
#[derive(Serialize, Deserialize, Debug)]
pub struct ChecklistItem {
    /// true if item is checked
    pub checked: bool,
    /// checklist item text
    pub text: String,
}

/// Checklist field
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Checklist {
    /// checklist uuid
    pub uuid: Option<UUID>,
    /// checklist name
    pub name: String,
    /// The content
    pub items: Vec<ChecklistItem>,
    /// if true, checked item should be hidden in display
    pub should_checked_items_be_hidden: bool,
}

/// user email info
#[derive(Serialize, Deserialize, Debug)]
pub struct Email {
    /// email object id
    pub id: ID,
    /// email object short id
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    /// email object uuid
    pub uuid: UUID,
    /// email address
    pub email: String,
    /// whether this is the primary email
    #[serde(rename = "isPrimary")]
    pub is_primary: bool,
    /// date created
    pub created_at: DateTime<Utc>,
    /// date updated
    pub updated_at: DateTime<Utc>,
    /// date deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    #[serde(rename = "isVerified")]
    /// whether email has been verified
    pub is_verified: bool,
}

impl ZKObjectID for Email {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// List item
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, Debug)]
pub struct Entry {
    /// object id
    pub id: ID,
    #[serde(rename = "shortId")]
    /// object short id
    pub short_id: ShortId,
    /// object uuid
    pub uuid: UUID,
    /// id of list containing this entry
    #[serde(rename = "listId")]
    pub list_id: ID,
    /// entry created date
    pub created_at: DateTime<Utc>,
    /// entry updated date
    pub updated_at: DateTime<Utc>,
    /// entry deprecated date
    pub deprecated_at: Option<DateTime<Utc>>,
    /// user that created entry
    pub created_by_displayname: Option<String>,
    /// user that updated entry
    pub updated_by_displayname: Option<String>,
    /// user that deprecated entry
    pub deprecated_by_displayname: Option<String>,
    /// id of user that created entry
    pub created_by: ID,
    /// id of user that updated entry
    pub updated_by: ID,
    /// id of user that deprecated entry
    pub deprecated_by: Option<ID>,
    /// Entry title
    // I encountered a null displayString after creating an Entry via api without specifying it
    // To simplify coding elsewhere, coerce (rare/unlikely) null to empty string
    #[serde(rename = "displayString", default = "empty_string")]
    pub display_string: String,
    /// Sort order
    #[serde(rename = "sortOrder", deserialize_with = "f32_or_str")]
    pub sort_order: f32, // sometimes negative
    /// number of comments
    pub comment_count: u64,
    /// checklist items attached to this entry
    pub checklists: Vec<Checklist>,
    /// Catch-all: User-defined fields (name_uuid, etc.) will be here
    #[serde(flatten)]
    pub fields: JsonMap,
}

impl ZKObjectID for Entry {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

impl Entry {
    /// Returns value of text string or None if undefined
    pub fn get_text_value(&self, field_uuid: &str) -> Result<Option<&str>, Error> {
        let field_name = format!("{}_text", field_uuid);
        Ok(self
            .fields
            .get(&field_name)
            .map(|v| v.as_str())
            .unwrap_or_default())
    }

    /// Returns int value of numeric field
    pub fn get_int_value(&self, field_uuid: &str) -> Result<Option<i64>, Error> {
        let field_name = format!("{}_number", field_uuid);
        Ok(self
            .fields
            .get(&field_name)
            .map(|n| n.as_i64())
            .unwrap_or_default())
    }

    /// Returns float value of numeric field
    pub fn get_float_value(&self, field_uuid: &str) -> Result<Option<f64>, Error> {
        let field_name = format!("{}_number", field_uuid);
        Ok(self
            .fields
            .get(&field_name)
            .map(|n| n.as_f64())
            .unwrap_or_default())
    }

    /// Returns value of date string or None if undefined
    pub fn get_date_value(&self, field_uuid: &str) -> Result<Option<&str>, Error> {
        let field_name = format!("{}_date", field_uuid);
        Ok(self
            .fields
            .get(&field_name)
            .map(|v| v.as_str())
            .unwrap_or_default())
    }

    /// Returns label/category value(s) (as strings)
    pub fn get_category_names(&self, field_uuid: &str) -> Vec<&str> {
        self.map_values(field_uuid, "categories_sort", "name", |v| v.as_str())
    }

    /// Returns label/category ids
    pub fn get_category_ids(&self, field_uuid: &str) -> Vec<ID> {
        self.map_values(field_uuid, "categories_sort", "id", |v| v.as_u64())
    }

    //noinspection SpellCheckingInspection
    /// Returns display names of people referenced by this field
    pub fn get_person_names(&self, field_uuid: &str) -> Vec<&str> {
        self.map_values(field_uuid, "persons_sort", "displayname", |v| v.as_str())
    }

    /// Returns IDs of people referenced by this field
    pub fn get_person_ids(&self, field_uuid: &str) -> Vec<ID> {
        self.map_values(field_uuid, "persons_sort", "id", |v| v.as_u64())
    }

    /// Returns UUIDs of referent items, or empty array
    pub fn get_references(&self, field_uuid: &str) -> Vec<&str> {
        self.map_values(field_uuid, "references_sort", "uuid", |v| v.as_str())
    }

    // obtain Vec<value> from array of maps of key-value
    fn map_values<'v, T>(
        &'v self,
        field_uuid: &'_ str,
        field_kind: &'_ str,
        key: &'_ str,
        pred: fn(&'v Value) -> Option<T>,
    ) -> Vec<T> {
        let field_name = format!("{}_{}", field_uuid, field_kind);
        self.fields
            .get(&field_name)
            .map(|v| v.as_array())
            .unwrap_or_default()
            .map(|v| {
                v.iter()
                    .filter_map(|val| val.as_object())
                    .filter_map(|val| val.get(key))
                    .filter_map(|val| pred(val))
                    .collect()
            })
            .unwrap_or_else(Vec::new)
    }
}

/// deleted item reference
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeleteListEntryDetail {
    /// object id
    pub id: ID,
    /// object uuid
    pub uuid: UUID,
    /// object short id
    pub short_id: ShortId,
}

impl ZKObjectID for DeleteListEntryDetail {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Response from delete entry
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeleteListEntryResponse {
    ///
    pub action: String,
    ///
    pub list_entry: DeleteListEntryDetail,
}

/// File attachment
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, Debug)]
pub struct File {
    /// object id
    pub id: ID,
    /// object short id
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    /// object uuid
    pub uuid: UUID,
    /// file name
    #[serde(rename = "fileName")]
    pub file_name: String,
    /// file size
    pub size: Option<i64>,
    /// file mime type
    #[serde(rename = "mimetype")]
    pub mime_type: Option<String>,
    /// image flag
    #[serde(rename = "isImage")]
    pub is_image: Option<bool>, //can be null
    /// AWS S3 identity
    #[serde(rename = "s3key")]
    pub s3_key: Option<String>,
    /// file url
    #[serde(rename = "fileUrl")]
    pub file_url: Option<String>,
    /// crop parameters
    #[serde(rename = "cropParams")]
    pub crop_params: Value,
    // I uploaded an image and both height and width were null
    // their size was in metadata.height, metadata.width
    //pub width: Option<String>,
    //pub height: Option<String>,
    /// date created
    pub created_at: DateTime<Utc>,
    /// date updated
    pub updated_at: DateTime<Utc>,
    /// date deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    /// user that uploaded
    #[serde(rename = "uploaderId")]
    pub uploader_id: ID,
    /// containing list
    #[serde(rename = "listId")]
    pub list_id: ID,
    /// field id
    #[serde(rename = "elementId")]
    pub element_id: ID,
    /// queries
    #[serde(rename = "cachedQuerys")]
    pub cached_queries: Value, // note spelling change
    /// error during import
    #[serde(rename = "importError")]
    pub import_error: Option<String>,
    /// file provider: link for url type, None for uploads (undocumented)
    pub provider: Option<String>,
    /// undocumented field "metadata"
    /// for jpeg: {format: "jpeg", height: number, width: number}
    pub metadata: Option<Value>,
}

impl ZKObjectID for File {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Filter expression term
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum FilterTermModus {
    /// empty field
    IsEmpty,
    /// non-empty field
    IsNotEmpty,
    /// field contains text
    Contains,
    /// field does not contain text
    NotContains,
    /// field equals text
    Equals,
    /// field does ot equal text
    NotEquals,
    /// field starts with text
    StartsWith,
    /// field does not start with text
    NotStartsWith,
    /// field ends with text
    EndsWith,
    /// field does not end with text
    NotEndsWith,
    /// field has value within range
    InRange,
    /// field value is not within range
    NotInRange,
    /// field is greater or equal to value
    GreaterOrEqual,
    /// field is less than or equal to value
    LessOrEqual,
}

/// date expression term
//noinspection SpellCheckingInspection
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum DateFilterTermModus {
    Any = 0,
    ThisYear = 1,
    ThisMonth = 2,
    ThisWeek = 3,
    Yesterday = 4,
    Today = 5,
    Tomorrow = 6,
    NextWeek = 7,
    NextMonth = 8,
    NextYear = 9,
    Custom = 10,
    LastWeek = 11,
    LastMonth = 12,
    LastYear = 13,
    Empty = 14,
    NotEmpty = 15,
}

/// List (aka Collection).
/// See also ListInfo, which wraps a List with field definitions,
/// to provide getters and setters for user-defined fields
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct List {
    /// object id
    pub id: ID, // List ID
    /// object short id
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    /// object uuid
    pub uuid: UUID,
    /// list name / title
    #[serde(default)]
    pub name: String,
    /// optional name for list item (defaults to list name)
    #[serde(rename = "itemName")]
    pub item_name: Option<String>,
    /// optional plural name for list item (defaults to list name)
    #[serde(rename = "itemNamePlural")]
    pub item_name_plural: Option<String>,
    ///
    #[serde(rename = "isBuilding")]
    pub is_building: bool,
    ///
    #[serde(rename = "isMigrating")]
    pub is_migrating: bool,
    //#[serde(rename = "isPublic")]
    //pub is_public: bool, // undocumented
    /// list sort order
    #[serde(rename = "sortOrder", deserialize_with = "f32_or_str")]
    pub sort_order: f32,
    /// description of list
    pub description: String,
    ///
    #[serde(rename = "formulaTSortOrder")]
    pub formula_tsort_order: Option<String>,
    ///
    #[serde(rename = "listFilePolicy")]
    pub list_file_policy: Option<String>,
    ///
    #[serde(rename = "originProvider")]
    pub origin_provider: Option<String>,
    ///
    #[serde(rename = "originData")]
    pub origin_data: Option<Value>,
    ///
    #[serde(rename = "defaultViewModus")]
    pub default_view_modus: i64,
    /// date list created
    pub created_at: DateTime<Utc>,
    /// date list last updated
    pub updated_at: DateTime<Utc>,
    /// date list deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    ///
    pub origin_created_at: Option<DateTime<Utc>>,
    ///
    pub origin_updated_at: Option<DateTime<Utc>>,
    ///
    pub origin_deprecated_at: Option<DateTime<Utc>>,
    #[serde(rename = "workspaceId")]
    /// id of workspace containing list
    pub workspace_id: ID,
    #[serde(rename = "backgroundId")]
    ///
    pub background_id: Option<String>,
    ///
    pub visibility: i64,
    ///
    #[serde(rename = "iconColor")]
    pub icon_color: Option<String>, // undocumented
    ///
    #[serde(rename = "iconBackgroundColor")]
    pub icon_background_color: Option<String>, // undocumented
    /// id of user that created list
    pub created_by: ID,
    //pub settings: Option<Value>, // undocumented
    //#[serde(rename = "resourceTags")]
    //pub resource_tags: Vec<ResourceTag>, // undocumented
    //     { appType: String, created_at: DateTime<Utc>, created_by: ID, is_owner: bool, tag: String,
    //     uuid: UUID }
    //#[serde(rename = "iconClassNames")]
    //pub icon_class_names: Option<Value>, // undocumented
}

impl ZKObjectID for List {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

impl List {
    /// Returns true if the list has the id, uuid, shortId, or name of the parameter
    pub fn has_id(&self, id: &str) -> bool {
        self.uuid == id || self.name == id || self.short_id == id || self.id.to_string() == id
    }
}

impl fmt::Display for List {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:<7} {} {}", self.id, self.uuid, self.name)
    }
}

/// prototype
#[derive(Serialize, Deserialize, Debug)]
pub struct ListPrototype {
    /// list name
    pub name: String,
}

#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum ListVisibility {
    ListMembersOnly = 0,
    ListMembersAndWorkspaceMembers = 1,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub enum NotificationType {
    PersonAdded,
    ListShare,
    WorkspaceShare,
    Subscription,
    Reminder,
    Mention,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MinNotification {
    pub id: ID,
    pub short_id: ShortId,
    pub uuid: UUID,
    pub list_id: ID,
    pub workspace_id: ID,
    pub list_entry_id: ID,
    pub element_id: ID,
    pub activity_id: ID,
}

/// User profile data
//noinspection SpellCheckingInspection
#[derive(Serialize, Deserialize, Debug)]
pub struct User {
    pub id: ID,
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    pub uuid: UUID,
    #[serde(rename = "displayname")]
    pub display_name: String,
    #[serde(rename = "fullname")]
    pub full_name: String,
    pub initials: String,
    #[serde(rename = "username")]
    pub user_name: String,
    #[serde(rename = "backgroundId")]
    pub background_id: Option<ID>,
    pub api_key: Option<String>,
    #[serde(rename = "imageLink")]
    pub image_link: Option<Value>,
    #[serde(rename = "isImagePreferred")]
    pub is_image_preferred: bool,
    pub anonymous: Option<bool>,
    pub locale: Option<String>,
    pub timezone: Option<String>,
    #[serde(rename = "isSuperAdmin")]
    pub is_super_admin: Option<bool>,
    pub registered_at: Option<Value>,
    pub trello_token: Option<String>,
    pub settings: Option<Value>,
    #[serde(rename = "emailCount")]
    pub email_count: u64,
    // pub emails: Vec<Email>,
}

impl ZKObjectID for User {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Workspace
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Workspace {
    /// workspace id
    pub id: ID,
    /// workspace short id
    #[serde(rename = "shortId")]
    pub short_id: ShortId,
    /// workspace uuid
    pub uuid: UUID,
    /// workspace name
    pub name: String,
    /// workspace description
    pub description: Option<String>,
    /// whether this is user's default workspace
    #[serde(rename = "isDefault")]
    pub is_default: bool,
    /// The timestamp at which this element was created
    pub created_at: DateTime<Utc>,
    /// The timestamp at which this element was last updated
    pub updated_at: DateTime<Utc>,
    /// The timestamp at which this element was deprecated. Is null if not deprecated
    pub deprecated_at: Option<DateTime<Utc>>,
    /// workspace background theme
    #[serde(rename = "backgroundId")]
    pub background_id: Option<ID>,
    /// workspace creator user id
    pub created_by: ID,

    /// lists in workspace
    pub lists: Vec<List>,
    // undocumented fields seen in output
    //#[serde(rename = "resourceTags")]
    //pub resource_tags: Vec<ResourceTag>,
    //pub settings: Value,
    //#[serde(rename = "app_data")]
    //pub app_data: Value,
}

impl ZKObjectID for Workspace {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

impl Workspace {
    /// Returns the workspace description, or an empty string if none was provided
    pub fn get_description(&self) -> &str {
        match &self.description {
            Some(s) => s.as_str(),
            None => "",
        }
    }

    /// Returns true if the workspace has the id, uuid, shortId, or name of the parameter
    pub fn has_id(&self, id: &str) -> bool {
        self.uuid == id || self.name == id || self.short_id == id || self.id.to_string() == id
    }

    pub fn get_id(&self) -> ID {
        self.id
    }

    pub fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

impl fmt::Display for Workspace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:<7} {} {}", self.id, self.uuid, self.name)
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ResourceTag {
    pub uuid: UUID,
    pub tag: String,
    #[serde(rename = "appType")]
    pub app_type: String,
    #[serde(rename = "isOwner")]
    pub is_owner: bool,
    pub created_by: ID,
    pub created_at: DateTime<Utc>,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TextFormat {
    Plain,
    #[allow(non_camel_case_types)]
    HTML,
    Markdown,
}

impl fmt::Display for TextFormat {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                TextFormat::Plain => "plain",
                TextFormat::HTML => "html",
                TextFormat::Markdown => "markdown",
            }
        )
    }
}

impl Default for TextFormat {
    fn default() -> Self {
        TextFormat::Plain
    }
}

impl FromStr for TextFormat {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "plain" => Ok(TextFormat::Plain),
            "markdown" => Ok(TextFormat::Markdown),
            "html" => Ok(TextFormat::HTML),
            _ => Err(Error::Other(format!(
                "TextFormat parse error: '{}' not 'plain', 'html', or 'markdown'",
                s
            ))),
        }
    }
}

/// Webhook trigger
#[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)]
#[repr(u8)]
pub enum WebhookTriggerType {
    Entry = 0,
    Activity = 1,
    Notification = 2,
    SystemMessage = 3,
    Comment = 4,
    Element = 5,
}

/// Webhook definition
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Webhook {
    pub id: ID,
    pub short_id: ShortId,
    pub uuid: UUID,
    pub trigger_type: WebhookTriggerType,
    pub user_id: ID,
    //pub created_by: ID, // undocumented
    pub workspace_id: Option<ID>,
    pub list_id: Option<ID>,
    pub list_entry_id: Option<ID>,
    pub url: String,
    pub provider: Option<String>,
    pub locale: String,
    pub element_id: Option<ID>,
}

impl ZKObjectID for Webhook {
    fn get_id(&self) -> ID {
        self.id
    }
    fn get_uuid(&self) -> &UUID {
        &self.uuid
    }
}

/// Parameter for creating a new webhook
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NewWebhook {
    pub trigger_type: WebhookTriggerType,
    pub url: String,
    /// restrict webhook to this workspace
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_id: Option<ID>,
    /// restrict webhook to this list
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_id: Option<ID>,
    /// restrict webhook to this item
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_entry_id: Option<ID>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub element_id: Option<ID>,
    pub locale: String,
}

/// Application OAuth client configuration
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OAuthClient {
    /// name of your app
    pub client_name: String,
    /// website of app, Optional
    pub client_url: Option<String>,
    /// OAuth 2.0 Authorization code grant redirect URI
    pub redirect_uri: String,
}

/// OAuth response data
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OAuthResponse {
    pub client_id: String,
    pub client_secret: String,
}

/// Return value from get_shared_access
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SharedAccesses {
    pub list_ids: Vec<ID>,
    pub workspace_ids: Vec<ID>,
}

/// Type of data change
#[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone)]
#[serde(rename = "lowercase")]
pub enum UpdateAction {
    /// Replace old values with new values
    Replace,
    /// Append new values to old values (assumes multi-valued)
    Append,
    /// Removes value(s)
    Remove,
    /// No update action
    Null,
}

impl fmt::Display for UpdateAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                UpdateAction::Replace => "replace",
                UpdateAction::Append => "append",
                UpdateAction::Remove => "remove",
                _ => "",
            }
        )
    }
}

/// Converts character ('=', '+', '-') to UpdateAction (Replace, Append, Remove)
/// any other char maps to Null
impl From<char> for UpdateAction {
    fn from(c: char) -> Self {
        match c {
            '=' => UpdateAction::Replace,
            '+' => UpdateAction::Append,
            '-' => UpdateAction::Remove,
            _ => UpdateAction::Null,
        }
    }
}

impl ElementChange {
    /// Convert Json Value to ChangedData. This is called during deserialization
    /// Most of the parsing logic is devoted to handling ResourceUpdate - activity type 2.
    /// For other activity types (for example, Comment, New Item, etc.)
    /// return the data as ChangedData::Other(Value).
    //noinspection SpellCheckingInspection
    fn from(mut v: Value) -> Result<Self, Error> {
        use ElementCategoryId::{Categories, Number, Persons, References, Text};
        if let Some(map) = v.as_object_mut() {
            if let Some(change_val) = map.values_mut().take(1).next() {
                let category_id: ElementCategoryId = match change_val
                    .get("elementcategoryId")
                    .map(|n| n.as_u64())
                    .unwrap_or_default()
                    .map(ElementCategoryId::from_u64)
                    .unwrap_or_default()
                {
                    Some(cid) => cid,
                    None => {
                        return Ok(ElementChange {
                            category_id: None,
                            data: ChangedData::Other(v),
                        });
                    }
                };
                let change_val = change_val.take();
                let data = match category_id {
                    Text => ChangedData::Text(serde_json::from_value(change_val)?),
                    Number => ChangedData::Number(serde_json::from_value(change_val)?),
                    Persons => ChangedData::Persons(serde_json::from_value(change_val)?),
                    References => ChangedData::References(serde_json::from_value(change_val)?),
                    Categories => ChangedData::Categories(serde_json::from_value(change_val)?),
                    ElementCategoryId::Date => {
                        ChangedData::Date(serde_json::from_value(change_val)?)
                    }
                    // not yet implemented
                    ElementCategoryId::URL
                    | ElementCategoryId::Checkbox
                    | ElementCategoryId::Formula
                    | ElementCategoryId::DateCreated
                    | ElementCategoryId::DateUpdated
                    | ElementCategoryId::DateDeprecated
                    | ElementCategoryId::UserCreatedBy
                    | ElementCategoryId::UserUpdatedBy
                    | ElementCategoryId::UserDeprecatedBy
                    | ElementCategoryId::Files
                    | ElementCategoryId::Hierarchy
                    | ElementCategoryId::SubEntries
                    | ElementCategoryId::Dependencies => {
                        // for unimplemented categories, use None to signal value needs to be decoded
                        return Ok(ElementChange {
                            category_id: None,
                            data: ChangedData::Other(change_val),
                        });
                    }
                };
                return Ok(ElementChange {
                    category_id: Some(category_id),
                    data,
                });
            }
        }
        // null value is expected when activity type is a Comment, and no fields changed
        if v.is_null() {
            return Ok(ElementChange {
                category_id: None,
                data: ChangedData::Other(Value::Null),
            });
        }
        Err(Error::Other(format!(
            "Parse error in changed_data val={:#?}",
            v
        )))
    }
}

impl<'de> Deserialize<'de> for ElementChange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v = Value::deserialize(deserializer)?;
        ElementChange::from(v).map_err(|e| {
            serde::de::Error::invalid_value(
                serde::de::Unexpected::Other(&e.to_string()),
                &"changed_data",
            )
        })
    }
}