shared/domain/
user.rs

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
//! Types for users.

use chrono::{DateTime, NaiveDate, Utc};
use macros::make_path_parts;
use serde::{Deserialize, Serialize, Serializer};
use std::fmt;
use strum_macros::Display;

use crate::domain::billing::{
    AccountId, AmountInCents, PlanTier, PlanType, SchoolId, SubscriptionStatus, UserAccountSummary,
};
use crate::{
    api::endpoints::PathPart,
    domain::{
        circle::CircleId,
        image::ImageId,
        meta::{AffiliationId, AgeRangeId, SubjectId},
    },
};

pub mod public_user;

wrap_uuid! {
    /// Wrapper type around [`Uuid`], represents the ID of a User.
    pub struct UserId
}

/// Represents a user's permissions.
///
/// Note: 5 was `ManageModule`, and has been deleted, but cannot be replaced(?)
#[derive(Deserialize, Serialize, PartialEq, Eq, Debug, Clone, Copy)]
#[non_exhaustive]
#[repr(i16)]
pub enum UserScope {
    /// The user has access to everything, implies all other scopes.
    Admin = 1,

    /// The user can create/delete/modify categories
    ManageCategory = 2,

    /// The user can create/delete/modify images.
    ManageImage = 3,

    /// The user can delete/modify *any* asset.
    AdminAsset = 4,

    /// The user can create/delete/modify animations.
    ManageAnimation = 6,

    /// The user can create/delete/modify locale entries.
    ManageEntry = 7,

    /// The user can create/modify/delete assets of their own.
    ManageSelfAsset = 8,

    /// The User can create/delete/modify audio files of their own.
    ManageAudio = 9,

    /// The User can create resource focused jigs.
    Resources = 10,
}

impl TryFrom<i16> for UserScope {
    type Error = anyhow::Error;

    fn try_from(i: i16) -> Result<Self, Self::Error> {
        match i {
            1 => Ok(Self::Admin),
            2 => Ok(Self::ManageCategory),
            3 => Ok(Self::ManageImage),
            4 => Ok(Self::AdminAsset),
            6 => Ok(Self::ManageAnimation),
            7 => Ok(Self::ManageEntry),
            8 => Ok(Self::ManageSelfAsset),
            9 => Ok(Self::ManageAudio),
            10 => Ok(Self::Resources),
            _ => anyhow::bail!("Scope {} is invalid", i),
        }
    }
}

make_path_parts!(UserLookupPath => "/v1/user/lookup");

/// Query to lookup a user by unique data
/// no filters will return that the user does not exist.
/// multiple filters will act as a logical `OR` of them (multiple choices will return an arbitrary user).
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct UserLookupQuery {
    /// The user ID we're filtering by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<UserId>,

    /// The name we're filtering by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// Publicly accessible information about a user.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OtherUser {
    /// The user's id.
    pub id: UserId,
}

make_path_parts!(ResetEmailPath => "/v1/user/me/reset-email");

/// Update user email request
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ResetEmailRequest {
    /// user's email
    pub email: String,
}

/// Update user email response (returns the paseto token for the user)
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ResetEmailResponse {
    /// paseto token with user's email
    pub paseto_token: String,
}

/// user badge
#[derive(Debug, Display, Serialize, Deserialize, Clone, Copy)]
#[cfg_attr(feature = "backend", derive(sqlx::Type))]
#[serde(rename_all = "camelCase")]
#[strum(serialize_all = "camelCase")]
#[repr(i16)]
pub enum UserBadge {
    /// Master teacher
    MasterTeacher = 0,
    /// JI team member
    JiTeam = 1,
    ///  No Badge
    NoBadge = 10,
}

impl UserBadge {
    /// get str
    pub fn as_str(&self) -> &'static str {
        match self {
            UserBadge::MasterTeacher => "master-teacher",
            UserBadge::JiTeam => "ji-team",
            UserBadge::NoBadge => "",
        }
    }

    /// get display name
    pub fn display_name(&self) -> &'static str {
        match self {
            UserBadge::MasterTeacher => "Master Teacher",
            UserBadge::JiTeam => "JI Team",
            UserBadge::NoBadge => "",
        }
    }
}

/// A user's profile.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserProfile {
    /// The user's id.
    pub id: UserId,

    /// The user's username.
    pub username: String,

    /// The user's email address.
    pub email: String,

    /// Indicator for Oauth email
    pub is_oauth: bool,

    /// The user's given name (first name)
    pub given_name: String,

    /// The user's family name (last name)
    pub family_name: String,

    /// ID to the user's profile image in the user image library.
    pub profile_image: Option<ImageId>,

    /// The user's preferred application language.
    pub language_app: String,

    /// The user's preferred email language.
    pub language_emails: String,

    /// The user's preferred language.
    pub languages_spoken: Vec<String>,

    /// Does the user want educational resources sent to them?
    pub opt_into_edu_resources: bool,

    /// Is the user over 18 years old?
    pub over_18: bool,

    /// The user's timezone.
    pub timezone: chrono_tz::Tz,

    /// Bio for User
    pub bio: String,

    /// Badge of User
    pub badge: Option<UserBadge>,

    /// Allow location to be public
    #[serde(default)]
    pub location_public: bool,

    /// Allow organization to be public
    #[serde(default)]
    pub organization_public: bool, // default to false

    /// Allow persona to be public
    #[serde(default)]
    pub persona_public: bool, // default to false

    /// Allow languages_spoken to be public
    #[serde(default)]
    pub languages_spoken_public: bool, // default to false

    /// Allow bio to be public
    #[serde(default)]
    pub bio_public: bool, // default to false

    /// User associated Circles
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub circles: Vec<CircleId>,

    /// The scopes associated with the user.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub scopes: Vec<UserScope>,

    /// When the user was created.
    pub created_at: DateTime<Utc>,

    /// When the user was last updated.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<DateTime<Utc>>,

    /// The organization that the user belongs to.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization: Option<String>,

    /// The persona of the user
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub persona: Vec<String>,

    /// The user's taught subjects.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub subjects: Vec<SubjectId>,

    /// The user's age-ranges.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub age_ranges: Vec<AgeRangeId>,

    /// The user's affiliations.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub affiliations: Vec<AffiliationId>,

    /// The user's location
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<serde_json::Value>,

    /// Number of Jigs
    #[serde(default)]
    pub jig_count: u64,

    /// Number of Resources
    #[serde(default)]
    pub resource_count: u64,

    /// Number of Courses
    #[serde(default)]
    pub course_count: u64,

    /// Number of playlists
    #[serde(default)]
    pub playlist_count: u64,

    /// Total number of assets
    #[serde(default)]
    pub total_asset_count: u64,

    /// The user's account summary, if available.
    ///
    /// Note: This is not set when fetching a user profile. It must be explicitly set using a
    /// function such as [`db::account::get_user_account_summary()`]
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_summary: Option<UserAccountSummary>,
}

impl UserProfile {
    /// Returns the school or organization associated with this user if any.
    pub fn school_or_organization(&self) -> Option<&str> {
        self.account_summary
            .as_ref()
            .and_then(|summary| summary.school_name.as_deref())
            .or(self.organization.as_deref())
    }
}

/// Login types
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "backend", derive(sqlx::Type))]
pub enum UserLoginType {
    /// Google
    Google,
    /// Email
    Email,
}

impl fmt::Display for UserLoginType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UserLoginType::Google => write!(f, "Google"),
            UserLoginType::Email => write!(f, "Email"),
        }
    }
}

/// User Response (used for Admin).
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserResponse {
    /// The user's id.
    pub id: UserId,

    /// The user's username.
    pub username: String,

    /// The user's given name (first name)
    pub given_name: String,

    /// The user's family name (last name)
    pub family_name: String,

    /// The user's email address.
    pub email: String,

    /// The user's country.
    #[serde(default)]
    pub country: Option<String>,

    /// The user's state.
    #[serde(default)]
    pub state: Option<String>,

    /// The user's city.
    #[serde(default)]
    pub city: Option<String>,

    /// The user's associated organization/school.
    #[serde(default)]
    pub organization: Option<String>,

    /// The date the user signed up on .
    pub created_at: NaiveDate,

    /// The user's preferred email language for newsletters.
    pub language: String,

    /// The user's city.
    #[serde(default)]
    pub badge: Option<UserBadge>,

    /// The users subscription plan type
    #[serde(default)]
    pub plan_type: Option<PlanType>,

    /// The users subscription status
    #[serde(default)]
    pub subscription_status: Option<SubscriptionStatus>,

    /// Whether the user's subscription is in a trial period
    #[serde(default)]
    pub is_trial: Option<bool>,

    /// The users subscription expiry/renewal date
    #[serde(default)]
    pub current_period_end: Option<DateTime<Utc>>,

    /// The amount due on the users subscription
    #[serde(default)]
    pub amount_due_in_cents: Option<AmountInCents>,

    /// Whether the user is an admin of the account
    #[serde(default)]
    pub is_admin: Option<bool>,

    /// The school name associated with the users account
    #[serde(default)]
    pub school_id: Option<SchoolId>,

    /// The school name associated with the users account
    #[serde(default)]
    pub school_name: Option<String>,

    /// The account id for the user
    #[serde(default)]
    pub account_id: Option<AccountId>,

    /// Plan tier override
    #[serde(default)]
    pub tier_override: Option<PlanTier>,

    /// Login type
    pub login_type: UserLoginType,
}

/// A user's profile export representation.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserProfileExport {
    /// The user's id.
    pub id: UserId,
    /// The user's username.
    pub username: String,
    /// The user's email address.
    pub email: String,
    /// The user's given name (first name)
    pub given_name: String,
    /// The user's family name (last name)
    pub family_name: String,
    /// ID to the user's profile image in the user image library.
    pub profile_image: Option<ImageId>,
    /// Last time user logged in.
    pub last_login: Option<DateTime<Utc>>,
    /// Last time user did an action.
    pub last_action: Option<DateTime<Utc>>,
    /// The user's preferred application language.
    pub language_app: String,
    /// The user's preferred email language.
    pub language_emails: String,
    /// The user's preferred language.
    #[serde(default)]
    #[serde(serialize_with = "serialize_list")]
    pub languages_spoken: Vec<String>,
    /// When the user was created.
    pub created_at: DateTime<Utc>,
    /// When the user was last updated.
    #[serde(default)]
    pub updated_at: Option<DateTime<Utc>>,
    /// The organization that the user belongs to.
    #[serde(default)]
    pub organization: Option<String>,
    /// The persona of the user
    #[serde(default)]
    #[serde(serialize_with = "serialize_list")]
    pub persona: Vec<String>,
    /// The user's taught subjects.
    #[serde(default)]
    #[serde(serialize_with = "serialize_list")]
    pub subjects: Vec<String>,
    /// The user's age-ranges.
    #[serde(default)]
    #[serde(serialize_with = "serialize_list")]
    pub age_ranges: Vec<String>,
    /// The user's affiliations.
    #[serde(default)]
    #[serde(serialize_with = "serialize_list")]
    pub affiliations: Vec<String>,
    /// The user's city
    #[serde(default)]
    pub city: Option<String>,
    /// The user's state/province
    #[serde(default)]
    pub state: Option<String>,
    /// The user's country
    #[serde(default)]
    pub country: Option<String>,
    /// Whether this user has opted in to receive educational resources
    pub opt_into_edu_resources: bool,
    /// Number of liked jigs
    pub liked_jig_count: i64,
    /// Number of published jigs
    pub published_jigs_count: i64,
    // /// Users plan type
    // pub plan_type: Option<String>
}

fn serialize_list<S, T>(list: &Vec<T>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: Serialize,
{
    list.iter()
        .map(|v| serde_json::to_string(v).unwrap())
        .collect::<Vec<String>>()
        .join(", ")
        .serialize(serializer)
}

impl UserProfile {
    /// Returns the display name for UI purposes
    pub fn display_name(&self) -> String {
        format!("{} {}", self.given_name, self.family_name)
            .trim()
            .to_string()
    }
}

make_path_parts!(VerifyEmailPath => "/v1/user/verify-email");

/// Request for [`VerifyEmail`](crate::api::endpoints::user::VerifyEmail)
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum VerifyEmailRequest {
    /// Attempt to verify the email
    Verify {
        /// The token to verify.
        token: String,
    },

    /// Resend a confirmation link if a verification is in progress
    Resend {
        /// The email to send a verification link to.
        email: String,
    },
}

make_path_parts!(VerifyResetEmailPath => "/v1/user/verify-reset-email");

/// Request for [`VerifyUpdateEmail`](crate::api::endpoints::user::VerifyEmail)
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum VerifyResetEmailRequest {
    /// Attempt to verify the email
    #[serde(rename_all = "camelCase")]
    Verify {
        /// paseto token
        paseto_token: String,

        /// Forcibly logout of all sessions.
        force_logout: bool,
    },

    /// Resend a confirmation link if a verification is in progress
    #[serde(rename_all = "camelCase")]
    Resend {
        /// paseto token
        paseto_token: String,
    },
}

make_path_parts!(CreateProfilePath => "/v1/user/me/profile");

/// Request for [`user::profile::Create`](crate::api::endpoints::user::CreateProfile)
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateProfileRequest {
    /// The user's username.
    ///
    /// This must be unique.
    pub username: String,

    /// Is the user >= 18 yeas old?
    pub over_18: bool,

    /// The user's given name / "first name".
    pub given_name: String,

    /// The user's family name / "last name".
    pub family_name: String,

    /// URL to the user's profile image. The API server uploads and processes the image so that the
    /// profile image is stored in Cloud Storage in the user image library.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_image_url: Option<String>,

    /// The user's preferred application language.
    pub language_app: String,

    /// The user's preferred email language.
    pub language_emails: String,

    /// The user's preferred language.
    pub languages_spoken: Vec<String>,

    /// the timezone that the user uses.
    pub timezone: chrono_tz::Tz,

    // todo: does this have something to do with emails?
    /// Does the user want educational resources sent to them?
    pub opt_into_edu_resources: bool,

    /// The organization that the user belongs to.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization: Option<String>,

    /// The persona of the user
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub persona: Vec<String>,

    /// The user's taught subjects.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub subjects: Vec<SubjectId>,

    /// The user's age-ranges.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub age_ranges: Vec<AgeRangeId>,

    /// The user's affiliations.
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub affiliations: Vec<AffiliationId>,

    /// The user's location
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<serde_json::Value>,
}

make_path_parts!(GetProfilePath => "/v1/user/me/profile");

make_path_parts!(PatchProfilePath => "/v1/user/me/profile");

/// Request for [`PatchProfile`](crate::api::endpoints::user::PatchProfile)
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PatchProfileRequest {
    /// The user's username.
    ///
    /// This must be unique.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,

    /// The user's given name / "first name".
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub given_name: Option<String>,

    /// The user's family name / "last name".
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub family_name: Option<String>,

    /// ID to the user's profile image in the user image library.
    #[serde(default)]
    #[serde(deserialize_with = "super::deserialize_optional_field")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_image: Option<Option<ImageId>>,

    /// The user's bio
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bio: Option<String>,

    /// the language the user prefers the application to be in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language_app: Option<String>,

    /// the language the user prefers emails to be in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language_emails: Option<String>,

    /// the languages the user prefers.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages_spoken: Option<Vec<String>>,

    /// the timezone that the user uses.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timezone: Option<chrono_tz::Tz>,

    /// Does the user want educational resources sent to them?
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub opt_into_edu_resources: Option<bool>,

    /// Publicize Users organization
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization_public: Option<bool>,

    /// Publicize user persona
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona_public: Option<bool>,

    /// Publicize user lanuage
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub languages_spoken_public: Option<bool>,

    /// Publicize user location
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location_public: Option<bool>,

    /// Publicize user bio
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bio_public: Option<bool>,

    /// The organization that the user belongs to.
    ///
    /// Field is updated if `Some(_)` with the inner contents.
    #[serde(default)]
    #[serde(deserialize_with = "super::deserialize_optional_field")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub organization: Option<Option<String>>,

    /// The persona of the user.
    ///
    /// Field is updated if `Some(_)` with the inner contents.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona: Option<Vec<String>>,

    /// The user's taught subjects.
    ///
    /// If `Some`, replace the existing `SubjectId`s with this.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subjects: Option<Vec<SubjectId>>,

    /// The user's age-ranges.
    ///
    /// If `Some`, replace the existing `AgeRangeId`s with this.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub age_ranges: Option<Vec<AgeRangeId>>,

    /// The user's affiliations.
    ///
    /// If `Some`, replace the existing `AffiliationId`s with this.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub affiliations: Option<Vec<AffiliationId>>,

    /// The user's location.
    /// * If the outer `Option` is `None`, then no update is done,
    /// * If `Some(None)`, sets the location to `None`,
    /// * If `Some(Some(_))`, updates the user location to `Some(_)`.
    #[serde(default)]
    #[serde(deserialize_with = "super::deserialize_optional_field")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<Option<serde_json::Value>>,
}

make_path_parts!(PatchProfileAdminDataPath => "/v1/user/me/profile/{}/admin-data" => UserId);

/// Request for [`PatchProfileAdminData`](crate::api::endpoints::user::PatchProfileAdminData)
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PatchProfileAdminDataRequest {
    /// Users badge
    #[serde(default)]
    #[serde(deserialize_with = "super::deserialize_optional_field")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub badge: Option<Option<UserBadge>>,
}

make_path_parts!(CreateUserPath => "/v1/user");

/// Request for [`Create`](crate::api::endpoints::user::Create)
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateUserRequest {
    /// The new user's email
    pub email: String,

    /// The new user's password
    pub password: String,
}

make_path_parts!(ResetPasswordPath => "/v1/user/password-reset");

/// Request for [`ResetPassword`](crate::api::endpoints::user::ResetPassword)
#[derive(Debug, Serialize, Deserialize)]
pub struct ResetPasswordRequest {
    /// The email to request a password reset for
    pub email: String,
}

make_path_parts!(ChangePasswordPath => "/v1/user/me/password");

/// Request for [`ChangePassword`](crate::api::endpoints::user::ChangePassword)
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ChangePasswordRequest {
    /// Change the email
    Change {
        /// The token to verify with
        token: String,

        /// The new password
        password: String,

        /// Forcibly logout of all sessions.
        force_logout: bool,
    },
}

make_path_parts!(UserDeletePath => "/v1/user/me");

// Colors

make_path_parts!(UserColorCreatePath => "/v1/user/me/color");

// i32 is color index
make_path_parts!(UserColorUpdatePath => "/v1/user/me/color/{}" => i32);

/// Request for [`CreateColor`](crate::api::endpoints::user::CreateColor), [`UpdateColor`](crate::api::endpoints::user::UpdateColor)
#[derive(Debug, Serialize, Deserialize)]
pub struct UserColorValueRequest {
    /// the color to add/change to.
    pub color: rgb::RGBA8,
}

make_path_parts!(UserColorGetPath => "/v1/user/me/color");

/// Response for [`GetColors`](crate::api::endpoints::user::GetColors)
#[derive(Debug, Serialize, Deserialize)]
pub struct UserColorResponse {
    /// The user's colors.
    pub colors: Vec<rgb::RGBA8>,
}

// i32 is color index
make_path_parts!(UserColorDeletePath => "/v1/user/me/color/{}" => i32);

// Fonts

make_path_parts!(UserFontCreatePath => "/v1/user/me/font");

// i32 is font index
make_path_parts!(UserFontUpdatePath => "/v1/user/me/font/{}" => i32);

/// Request for [`CreateFont`](crate::api::endpoints::user::CreateFont), [`UpdateFont`](crate::api::endpoints::user::UpdateFont)
#[derive(Debug, Serialize, Deserialize)]
pub struct UserFontNameRequest {
    /// Name of the font to add/change.
    pub name: String,
}

make_path_parts!(UserFontGetPath => "/v1/user/me/font");

/// Response for [`GetFonts`](crate::api::endpoints::user::GetFonts)
#[derive(Debug, Serialize, Deserialize)]
pub struct UserFontResponse {
    /// Names of the user's fonts.
    pub names: Vec<String>,
}

// i32 is font index
make_path_parts!(UserFontDeletePath => "/v1/user/me/font/{}" => i32);

//
// Browse users
//
// Authorization:
//  - Admin

/// Query for [`Browse`](crate::api::endpoints::user::Browse).
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserBrowseQuery {
    /// filter User by Id.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_id: Option<UserId>,

    /// The page number of the Users to get.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,

    /// The hits per page to be returned
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_limit: Option<u32>,

    /// Optional filter for user badges
    #[serde(default)]
    #[serde(deserialize_with = "super::from_csv")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub badge: Vec<UserBadge>,
}

/// Response for [`Browse`](crate::api::endpoints::user::Browse).
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserBrowseResponse {
    /// the users returned.
    pub users: Vec<UserResponse>,

    /// The number of pages found.
    pub pages: u32,

    /// The total number of users found
    pub total_user_count: u64,
}

make_path_parts!(UserBrowsePath => "/v1/user/browse");

//
// Search users
//
// Authorization:
//  - Admin

/// Query for [`Search`](crate::api::endpoints::user::Search).
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserSearchQuery {
    /// The query string.
    #[serde(default)]
    #[serde(skip_serializing_if = "String::is_empty")]
    pub q: String,

    /// The query string.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_id: Option<UserId>,

    /// The page number of the Users to get.
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,

    /// The hits per page to be returned
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_limit: Option<u32>,
}

/// Response for [`Search`](crate::api::endpoints::user::Search).
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct UserSearchResponse {
    /// the users returned.
    pub users: Vec<UserResponse>,

    /// The number of pages found.
    pub pages: u32,

    /// The total number of users found
    pub total_user_count: u64,
}

make_path_parts!(UserSearchPath => "/v1/user");